I've been reading about AABB collision. I have a pretty rough implementation of it at the moment. I am now able to detect when two rectangles intersect on both the X and Y axis.
To calculate the depth of intersection on X, I basically do:
overlapX = (Game1.p[0].boundingBox.halfWidth + Game1.p[1].boundingBox.halfWidth)
- (Math.Abs(Game1.p[0].boundingBox.center.X - Game1.p[1].boundingBox.center.X));
Right now I am just testing the depth on X as I want to see where the problem is. I am not taking the direction, left or right, into account. I am just assuming the p[0] object is colliding on the left side of p[1].
Then for the actual movement and collision detection:
public void Move(float x, float y)
{
Position.X += x;
Position.Y += y;
overlapX = (Game1.p[0].boundingBox.halfWidth
+ Game1.p[1].boundingBox.halfWidth)
- (Math.Abs(Game1.p[0].boundingBox.center.X
- Game1.p[1].boundingBox.center.X));
overlapY = (Game1.p[0].boundingBox.halfHeight
+ Game1.p[1].boundingBox.halfHeight)
- (Game1.p[1].boundingBox.center.Y
- Game1.p[0].boundingBox.center.Y);
if (Collision.testAABBAABBX(
Game1.p[0].boundingBox, Game1.p[1].boundingBox) &&
Collision.testAABBAABBY(
Game1.p[0].boundingBox, Game1.p[1].boundingBox))
{
if (overlapX < overlapY) Position.X -= overlapX;
}
}
Now when I collide with p[1]
, overlapX
reads 1. So position.X
should -= 1
. However, here is where the problem begins. Here is an image during the overlap. You can see that there is indeed an overlap shown by a vertical yellow line:
So my problem is that when I instruct the position.X
to move back by the overlap value, it does not, at least not until I move the rectangle either up or down. If I do that, it magically corrects itself:
Any clues on what's going on? Maybe it's right in front of me and I'm not seeing it, but the response only seems to trigger after the next movement.
Let me know if more info is needed.
Rectangle.Intersects()
? – user1306322