3
\$\begingroup\$

image

Hello,

My player sprite is moving along the wall (not even diagonal, just straight down) and get randomly blocked in the corner of some walls. By blocked, I mean that the Y movement is stopped. If I move him away from the wall, he might not be blocked again by the same wall and get blocked at some other walls, always at a corner.

The walls are all the same sprite and are of the same size.

I use 2D Box Colliders for the walls. The player sprite has a Box Collider 2D and a RigidBody 2D. I am not using any physics codes, I would just like to make it work with the built-in Unity physics.

I move the player by adjusting the velocity of the rigidbody according to Input:

RigidBody2D rb = GetComponent<Rigidbody2D>();
float horizontal = Input.GetAxisRaw ("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector2 movement = new Vector2(horizontal, vertical).normalized *speed * Time.deltaTime;
this.rb.velocity = movement;

The player is set like this:

player inspector

Do you have any idea why it behaves like this and how I could fix it?

Thanks for your help.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

This is a common issue when dealing with tiled ground/walls/terrain and BoxCollider2D. Often player collider's corner get stuck with wall's corner even if everything is perfectly lined up. I may suppose that the reason of it - floating point precision problem.

To solve this, you can try a different ways:

  • Change player's collider to EdgeCollider2D and tweak it to satisfy your needs.
  • Change player's collider to circle/capsule. Sometimes it work fine for platformer-style games, but in top-down game like yours it will cause another problem like weird diagonaly moving around a corners.
  • Apply PhysicsMaterial2D to walls or player and set it to zero Friction. It may help, if you are using built-in physics or gravity.
  • Generate one big collider for connected walls at runtime. If there is no seams between colliders, player will not stuck.
  • Detect collisions by yourself using Raycast.

Also you may read this two articles: this and this.

\$\endgroup\$
1
  • \$\begingroup\$ Thanks for your answer, I tried using the zero friction PhysicsMaterial2D but it didn't fixed the issue. I tried the Circle Collider and for now it satisfies my needs. I will implement the Raycast solution if I feel that the gameplay is weird. \$\endgroup\$
    – Sheikz
    Nov 3, 2015 at 9:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .