【问题标题】:Simple Collision Detection - Android简单的碰撞检测 - Android
【发布时间】:2011-11-28 10:27:46
【问题描述】:

我想在类似乒乓球的游戏中进行非常简单的碰撞检测。 球是正方形,桨(球拍)是矩形。

我有两个实体进入,我可以在其中获取当前 X 和 Y 位置,以及位图高度和宽度。哪种方法最简单?

我有这个代码:

public void getCollision(Entity enitityOne, Entity enitityTwo){

    double eventCoordX = (enitityOne.getCenterX() - (enitityTwo.getBitmapWidth() / 2));
    double eventCoordY = (enitityOne.getCenterY() - (enitityTwo.getBitmapHeight() / 2));

    double X = Math.abs(enitityTwo.getxPos() - eventCoordX);
    double Y = Math.abs(enitityTwo.getyPos() - eventCoordY);

    if(X <= (enitityTwo.getBitmapWidth()) && Y <= (enitityTwo.getBitmapHeight())){
        enitityOne.collision();
        enitityTwo.collision();
    }
}

但我很盲目,这只适用于桨的中间而不是两侧。 问题是我看不到代码错在哪里。 有人吗? 有人有更好的主意吗?

【问题讨论】:

  • 我发现绘制正常情况和边缘情况的图表非常有用。
  • Joakim、getBitmapWidth 和 getBitmapHeight 返回实体的实际大小?我问这个是因为实体可以有一个边框,而这个边框不是这个大小的总和。
  • Bruno - 是的,它返回位图的实际大小,我已经仔细检查过 ;-)

标签: android collision-detection


【解决方案1】:

如果您只想确定 2 个给定矩形是否以某种方式相交(并因此发生碰撞),这是最简单的检查(C 代码;随意使用浮点值):

int RectsIntersect(int AMinX, int AMinY, int AMaxX, int AMaxY,
                   int BMinX, int BMinY, int BMaxX, int BMaxY)
{
    assert(AMinX < AMaxX);
    assert(AMinY < AMaxY);
    assert(BMinX < BMaxX);
    assert(BMinY < BMaxY);

    if ((AMaxX < BMinX) || // A is to the left of B
        (BMaxX < AMinX) || // B is to the left of A
        (AMaxY < BMinY) || // A is above B
        (BMaxY < AMinY))   // B is above A
    {
        return 0; // A and B don't intersect
    }

    return 1; // A and B intersect
}

矩形 A 和 B 由它们角的最小和最大 X 和 Y 坐标定义。

嗯...This has been asked before.

【讨论】:

  • 为什么不直接使用内置的Rect.intersect(Rect) 方法
【解决方案2】:

如果你正在处理矩形,那么

    /**
 * Check if two rectangles collide
 * x_1, y_1, width_1, and height_1 define the boundaries of the first rectangle
 * x_2, y_2, width_2, and height_2 define the boundaries of the second rectangle
 */
boolean rectangle_collision(float x_1, float y_1, float width_1, float height_1, float x_2, float y_2, float width_2, float height_2)
{
  return !(x_1 > x_2+width_2 || x_1+width_1 < x_2 || y_1 > y_2+height_2 || y_1+height_1 < y_2);
}

这是一个很好的例子……

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    相关资源
    最近更新 更多