# How to change transform.position code to Rigidbody.AddForce?

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.

## 1 Answer

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.

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