2DCharacterControllerTutorial icon indicating copy to clipboard operation
2DCharacterControllerTutorial copied to clipboard

Gravity/grounded doesn't work with negative Player BoxCollider2D y offset

Open CodySelman opened this issue 5 years ago • 2 comments

If you are working with a BoxCollider2D that has negative y offset (-0.15 in my case), the Physics2D.OverlapBoxAll check will not always detect the ground collider. This causes the player to "jitter" up and down as the grounded check fails incorrectly and gravity is applied incorrectly on the next frame.

CodySelman avatar Jan 07 '21 04:01 CodySelman

To resolve this, you'll need to update the line of code where the overlap occurs to take into account the box collider's offset, since right now it uses the position of the object:

Collider2D[] hits = Physics2D.OverlapBoxAll(transform.position, boxCollider.size, 0);

to something like

Collider2D[] hits = Physics2D.OverlapBoxAll((Vector2)transform.position + boxCollider.offset, boxCollider.size, 0);

Scale can also affect the collider's position/size (note I haven't tested the above). I'd update the code on the repo, but will also need to update the tutorial to mention the purpose of the code. Thanks for the issue :+1:

IronWarrior avatar Jan 07 '21 22:01 IronWarrior

Thank you for the quick response. That solves my issue!

CodySelman avatar Jan 09 '21 22:01 CodySelman