- Home /
Having 2D Character fall when in collision
I'm developing a simple 2D Platformer. I can't get the character to fall normally while colliding with an object. It "shakes" or it does not fall at all.
First, I was using Update() to get player input to move the character. I was moving it through Transform.Translate(). However, when moving it with Translate in the Update function, the player "shakes" when colliding with a collider while trying to move in its direction. What I was calling in Update when the player pressed something was:
public void MoveThePlayer(Vector2 translation)
{
playerTransform.Translate(translation * speed * Time.deltaTime);
}
I did some research about it and I found out this was because using Transform.Translate in Update() bypasses physics calculations. So I moved the moving function to the FixedUpdate, but now I sometimes missed player input (because that's what happens if you try to put input in FixedUpdate).
So I called the function again in Update but changed it to this:
public void MoveThePlayer(Vector2 translation)
{
playerRigidbody.velocity = new Vector2(translation.x * speed * Time.deltaTime, playerRigidbody.velocity.y);
}
The shaking was gone, but now the player did not fall when colliding with something and trying to move in its direction. Research told me this happened because I modified directly the velocity of the object, which did not let Unity apply the gravity calculations.
So... I tried working with the physics calculations. Adding forces normally... And found the following code when called in Update removes the shaking AND lets the player fall normally when colliding with something and trying to move in its direction:
public void MoveThePlayer(Vector2 translation)
{
playerRigidbody.AddForce( translation*Time.deltaTime*speed, ForceMode2D.Impulse);
}
But it does not change the player's velocity instantaneously. Meaning, if I change direction, it will have to stop first to then move the other way.
Is there a simple way to have the player change its velocity instantaneously, while having him fall normally and keeping the game from shaking even when colliding with stuff? Oh, and letting the player keep air control.