How to convert Transform.position to Rigidbody2D.velocity?

Hi all good people,

I found out that if I am using transform.position of an object it ignores collisions. So the best way is to use rigidbody2D.velocity (it is a 2D game, using 2D colliders) but how to convert this line of code to get the exact same results?

transform.position += transform.right * Time.deltaTime * planeSpeed;

I didn’t notice you where using transform.right. You can do this instead:

RigidBody2D body = GetComponent<RigidBody2D>();
Vector2 velocityDirection = transform.TransformDirection(transform.right);
velocity *= planeSpeed;
body.velocity = velocity;

You’ll have to do a component sum for this, I guess, bcause as far as I know, you can’t directly set the x and y components of RigidBody2D.velocity independently. Something like:

RigidBody2D body = GetComponent<RigidBody2D>();
body.velocity = Vector2.right * planeSpeed + Vector2.up * body.velocity.y;

You can’t convert position to velocity, you’re talking about values that mean completely different things and are expressed in diferent units.

If you want your rigidbody to move until it reachs the target position, set the velocity in that direction, and after some time the object will reach the position. You can check when it’s “close enough” to the target position to set the velocity to back to zero (or check any other condition, like releasing a key).

To set the velocity you need something like:

RigidBody2D body = GetComponent<RigidBody2D>();
body.velocity = new Vector2(planeSpeed,0f);

Note that other physic interactions will reduce the velocity, so you’ll have to keep setting it on every frame if you want a constant speed.