Quantcast
Channel: Question and Answer » libgdx
Viewing all articles
Browse latest Browse all 434

2D Collision Response

$
0
0

I am trying to implement collision response in my libgdx game. I’m using Rectangle objects as my bounbing boxes. This makes collision detection very easy, however I can’t quite get the response working correctly. At the moment I have this:

float overlapX = getOverlap1D(dynamicBounds.x, dynamicBounds.x + dynamicBounds.width, blockBounds.x, blockBounds.x + blockBounds.width);
float overlapY = getOverlap1D(dynamicBounds.y, dynamicBounds.y + dynamicBounds.height, blockBounds.y, blockBounds.y + blockBounds.height);

if (overlapX < overlapY)
{
      if (dynamic.getVelocity().x < 0)
      {
            dynamic.getPos().add(overlapX, 0);
      }
      else
      {
            dynamic.getPos().sub(overlapX, 0);
      }
      dynamic.setVelocityX(0);
}
else
{
      if (dynamic.getVelocity().y < 0)
      {
            dynamic.getPos().add(0, overlapY);
      }
      else
      {
            dynamic.getPos().sub(0, overlapY);
      }
      dynamic.setVelocityY(0);
}

private float getOverlap1D(float min1, float max1, float min2, float max2)
{
    return Math.max(0, Math.min(max1, max2) - Math.max(min1, min2));
}

Using this, corners are handled in a very unpleasant way, resulting in less than extraoridnary results like this.
Where am I going wrong that allows this to happen?


Viewing all articles
Browse latest Browse all 434

Trending Articles