17
\$\begingroup\$

So, I'm making a top down RPG.

Everything's going excellent, but this problem is quite annoying. Now, when the character moves against the wall, the player jitters back and forth. I'm guessing it's because the player is trying to move into the wall, and then the wall collision is pushing it back, which makes an annoying back and forth movement. My question is obviously, how do I stop this from happening?

Thanks!

PS: I'm using transform.translate to move the player, and I'm using C#.

EDIT: I'm also using a 2D Rigidbody, and 2Dbox colliders on both.

\$\endgroup\$
3
  • \$\begingroup\$ You just need a sweep test before you translate \$\endgroup\$
    – MickLH
    Jun 1, 2016 at 22:31
  • \$\begingroup\$ gamedev.net/page/resources/_/technical/game-programming/… \$\endgroup\$
    – MickLH
    Jun 1, 2016 at 22:32
  • \$\begingroup\$ Oh. Uh... I'm not sure how to add this in Unity C#. I'm a little new to C#. If you have the knowledge, would you mind explaining how to implement this? \$\endgroup\$
    – user84154
    Jun 1, 2016 at 22:42

1 Answer 1

49
\$\begingroup\$

The jittering is happening because you're warping the player into the wall using Transform.Translate, and the physics step is saying, "Hey, we're in the wall. Let's solve this collision issue and push the player back out of the wall."

To avoid this, when using a Rigidbody2D, it's advisable to use Rigidbody2D.MovePosition. This ensures you won't have overlapping colliders when moving. If a collider and rigidbody can't move because something's in the way, it won't jitter.

Using Rigidbody2D.MovePosition, you may want to set the Rigidbody2D.interpolation value to keep the movement looking smooth.

However, if Rigidbody2D.MovePosition isn't ideal for your game for some reason and you still want to use Transform.Translate, use Physics2D.Raycast (or other Physics2D casts) to see if moving would make you hit a wall or not, and only move if no wall is hit.

\$\endgroup\$
0

You must log in to answer this question.