Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question 2D collider inconsistent wall collision detection

Discussion in 'Physics' started by Talthilas, Jul 22, 2022.

  1. Talthilas


    Apr 1, 2014
    I am making a 2D platformer game. When my unit walks into a wall, the desired behaviour is to turn around and continue walking in the opposite direction. I have this working, however this behaviour is inconsistent. For the most part, everything appears to work, however quite often the unit will simply not turn around when it hits a wall. I have noticed that this is due to a wall collision not being detected in these instances. See below GIF of the unit correctly working on its first lap, but then getting stuck of the left wall on its second lap.

    The unit has a 2DCapsuleCollider component, and a Rigidbody2d component, with the rigidbody type set to dynamic. The terrain uses static Polygon2DCollider components (i.e. no rigidbody attached). Currently I am using the OnCollisionEnter2D and OnCollisionStay2D callbacks on a script on my unit to process wall collision checks. When the unit gets stuck, these callbacks are not being fired. Note I check for ground seperately using overlap circle checks in FixedUpdate. The unit is moved via the rigidbody2D.MovePosition method.

    In the attached example, the edges of the terrain colliders are not nice and flat. They are in fact very jaggered to follow the grass and other terrain features. See attached snapshot of the collider edges where the unit is getting stuck. This is not the intention for the finished game which will use nice and flat edges. For development I am just using a tool that generates Polygon2D colliders to match the terrain texture outline. I suspect that the 'roughness' of the terrain colliders could be playing a part in the problems I am facing, however I would like the collision code to be able to work properly despite the rough collider edges as rough collider edges could actually occur in the finished game (terrain is destructable).

    I am at a loss as to what the issue is or how to fix it using the OnCollision callback approach I am currently using. My next option to do my own wall collision checks in FixedUpdate (e.g overlap box or the like) and stop using the OnCollision callbacks altogether, however I was hoping someone may be able to identify what the problem is the way I am doing it at the moment.


    Attached Files: