AABB碰撞解决方案

时间:2013-01-14 02:38:54

标签: xna collision-detection

我一直在读关于AABB的碰撞。我现在有一个相当粗略的实现。我现在能够检测到两个矩形在X轴和Y轴上相交的时间。

为了计算X上的交叉深度,我基本上做了:

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));

现在我只是测试X上的深度,因为我想知道问题出在哪里。我没有考虑左,右方向。我只是假设p [0]对象在p [1]的左侧发生碰撞。

然后进行实际运动和碰撞检测:

 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;
     }
 }

现在当我与p[1]发生碰撞时,overlapX读取1. position.X -= 1应该position.X。但是,这是问题的开始。这是重叠期间的图像。您可以看到确实存在由垂直黄线显示的重叠:

Overlap http://s9.postimage.org/495f1fmv3/overlap.png

所以我的问题是,当我指示{{1}}向后移动重叠值时,它不会,至少在我向上或向下移动矩形之前。如果我这样做,它会神奇地纠正自己:

No overlap http://s7.postimage.org/wzg3sixaz/no_overlap.png

有关正在发生的事情的任何线索?也许它就在我面前,而我却没有看到它,但是在下一次运动之后,响应似乎才会触发。

如果需要更多信息,请告诉我。

1 个答案:

答案 0 :(得分:0)

这是因为你的碰撞解决方案代码放在你的动作代码中,除非你移动,否则它似乎不会运行。

解决方案是将您的Move方法之外的冲突解决代码移动到每个帧Update调用的单独方法中。