- Home /
Moving horizontally a rigidbody2d
Hello. I have a doubt regarding rigidbody2d movement. I've seen people using different ways to move a gameobject with rigidbodies:
transform.translate
setting rigidbody.velocity
rigidbody.addForce
rigidbody.movePosition
For my purpose, I'm trying to create a Player which is affected by physics (so I'm using a rigidbody). I understood 'transalte' is not accurated as it is not taking into account physics, it just moves the gameObject to the position. Setting directly the velocity of the rigidbody looks like is not a good practice.
Then with the other two methods is where I have some doubts. With 'AddForce' the problem I faced is that it accelerated my Player, and I want it to have a constant velocity, so I "solved" the issue incrementing the linea drag, but I don't think this is a good solution, as at the end is still accelerating but a lot less.
SO, I guess I should use MovePosition, but I also read this is supposed to be used by kinematic rigidBodies, which is not my case. Why is this? I tried to use it but my character is going crazy, going through vertical collisions when I'm just trying to move it horizontally. I don't understood it. Also I saw that the rigidbody2d.position it's in game unit scales.
Any tips please? Why is MovePosition going crazy? Which one should I use?
Here is the code in which the MovePosition is not working well (commented is the AddForce which is working):
public Vector2 kSpeed = new Vector2(0.01f, 0.0f);
void Update () {
if(Input.GetKey(KeyCode.D))
{
//rigidbody2D.AddForce(kSpeed); //this works but increasing the kSpeed value
Vector2 mov = rigidbody2D.position + kSpeed;
rigidbody2D.MovePosition(mov);
}
}
When I try to move to right, tt gets stuck like in this photo. It goes through the floor, like in diagonal, when I'm just updating the x axis of the rigidBody.
The floor has a collider which works perfectly with the AddForce.
Thanks