Vector2 vec = new Vector2(horizontal, vertical);
        vec = Vector2.ClampMagnitude(vec, 1);

        Vector3 camF = cam.transform.forward;
        Vector3 camR = cam.transform.right;

        camF.y = 0;
        camR.y = 0;
        camF = camF.normalized;
        camR = camR.normalized;

        transform.position += (camF * vec.y + camR * vec.x) * Time.deltaTime * MoveSpeed;

That's how i do my movement, but i need to change it to Rigidbody.AddForce 'cause the way that i use right now makes my character doesn't collide with objects perfectly.

Note: What i mean with "perfectly" is, if you walk to the corner of walls, you can pass through it and that's the thing that i want to prevent.


The most drop-in solution is to convert your position to a velocity needed to reach that position, then accelerate yourself to that velocity:

void FixedUpdate() {
    // Calculate your desired position however you like.
    Vector3 desiredPosition = GetDesiredPosition();

    // What velocity gets us there in one timestep?
    Vector3 desiredVelocity = (desiredPosition - transform.position)/Time.deltaTime;

    // If you want to preserve velocity on the y to let gravity accumulate, uncomment:
    // desiredVelocity.y = body.velocity.y;

    // Apply a sufficient impulse to hit reach that velocity.
    body.AddForce(desiredVelocity - body.velocity, ForceMode.VelocityChange);

Though generally I'd advise thinking of your control as seeking a target velocity rather than teleporting to a target position. I show an example of that style in this answer.

  • \$\begingroup\$ Okay i got it, it works, but how to incearese my movement speed? \$\endgroup\$ May 23 '19 at 18:42
  • \$\begingroup\$ By changing your desired position. You can also reduce the friction on your colliders' physics materials to reduce energy loss. \$\endgroup\$
    – DMGregory
    May 23 '19 at 18:43
  • \$\begingroup\$ It works fine thank you so much \$\endgroup\$ May 23 '19 at 18:44
  • \$\begingroup\$ I found a bug, gravity is so low on my character how can i fix that? \$\endgroup\$ May 27 '19 at 14:31
  • \$\begingroup\$ I have an Isgrounded method btw incase if it helps \$\endgroup\$ May 27 '19 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.