Depending on the force that gets applied to a Rigidbody2D, and depending on the speed, transform.Translate()
could override the changes of the physics simulation. For this reason, it is recommended to move a game object via the rigidbody instead of manipulating the transform directly. The data from the Rigidbody2D gets processed in the physics simulation, and the physics simulation assigns the new values to the transform.
// (1)
Vector2 playerVelocity = new Vector2(moveInput.x, body.velocity.y);
rigidbody.velocity = playerVelocity * runSpeed;
// (2)
Vector2 playerVelocity = new Vector2(moveInput.x * runSpeed, body.velocity.y);
rigidbody.velocity = playerVelocity;
(1) and (2) are not the same. In (1), the runSpeed
value gets multiplied by moveInput.x
and body.velocity.y
. In the physics simulation, the player is always falling down. He rarely has exactly 0f velocity on his y-axis. By multiplying the y-velocity by runSpeed
, the player gets an additional force, if you will, and that could explain why he is falling down with your code. The edge collider is just a thin line. It is easy to push the player beyond it. Since this is very likely the explanation for the behaviour in your game, and since the problem does not occur with Rick’s code, it is not necessary for me to take a look at your game.
For further information on the maths behind the quoted code, see ‘Multiplying a Vector by a Scalar’ on this website.