I’m using kinematic Rigidbody2Ds to implement my own collision detection+resolution. So far the detection works great but the resolution is inaccurate. The code I’m using for the detection & resolution is:
private void Physics()
{
int numColliders = Physics2D.OverlapCollider(_collider2D, _noFilter, _collisions);
for (int i = 0; i < numColliders; ++i)
{
Collider2D c = _collisions[i];
ColliderDistance2D overlap = _collider2D.Distance(_collisions[i]);
if (overlap.isOverlapped)
{
Vector2 newPosition = new Vector2(transform.position.x + (overlap.distance * overlap.normal.x), transform.position.y + (overlap.distance * overlap.normal.y));
float distMoved = (new Vector2(transform.position.x, transform.position.y) - newPosition).magnitude;
if (!c.OverlapPoint(newPosition))
{
Debug.LogError("Wrong position, moved too far.");
}
_rigidBody.MovePosition(newPosition);
}
}
}
Problem is my resolution always moves me a tiny bit too far back so I’m a tiny distance away from the collider, as opposed to touching it as would be expected. Then if I’m holding my movement button my object ends up twitching back and forth between hitting the wall and penetrating+being pushed back too far.
This screenshot shows the erroneous result at the instant of resolution:
As you can see the player (light blue) is pushed back a little too far from the wall (dark blue) causing the twitching issue when the key is held.
The CollderDistance2D returned from “ColliderDistance2D overlap = _collider2D.Distance(_collisions*)” appears to be slightly too big and is pushing the object further away than I would expect; I would expect of course that it pushes the object far enough away that they’re touching but not overlapping and no further.*
Someone on the Unity Discord suggested that 2D colliders seem to be treated as slightly bigger than they actually are, but shouldn’t this then behave universally and not apply in some cases/functions and not others?
Is there any solution to this problem? If so some help would be appreciated.