【问题标题】:How Sprite collision detection works?Sprite 碰撞检测如何工作?
【发布时间】:2018-01-23 16:32:57
【问题描述】:

我正在尝试了解 libgdx 中两个参与者的碰撞检测。 这就是我正在做的事情

Rectangle rect1 = sprite1.getBoundingRectangle();
Rectangle rect2 = sprite2.getBoundingRectangle();
if(rect1.overlaps(rect2))
 //collision occured
else
  //no collision

到目前为止还不错,但是如果您在 Actor 类中看到 getBoundingRectangle() 的代码

    public Rectangle getBoundingRectangle () {
    final float[] vertices = getVertices();

    float minx = vertices[X1];
    float miny = vertices[Y1];
    float maxx = vertices[X1];
    float maxy = vertices[Y1];

    minx = minx > vertices[X2] ? vertices[X2] : minx;
    minx = minx > vertices[X3] ? vertices[X3] : minx;
    minx = minx > vertices[X4] ? vertices[X4] : minx;

    maxx = maxx < vertices[X2] ? vertices[X2] : maxx;
    maxx = maxx < vertices[X3] ? vertices[X3] : maxx;
    maxx = maxx < vertices[X4] ? vertices[X4] : maxx;

    miny = miny > vertices[Y2] ? vertices[Y2] : miny;
    miny = miny > vertices[Y3] ? vertices[Y3] : miny;
    miny = miny > vertices[Y4] ? vertices[Y4] : miny;

    maxy = maxy < vertices[Y2] ? vertices[Y2] : maxy;
    maxy = maxy < vertices[Y3] ? vertices[Y3] : maxy;
    maxy = maxy < vertices[Y4] ? vertices[Y4] : maxy;

    if (bounds == null) bounds = new Rectangle();
    bounds.x = minx;
    bounds.y = miny;
    bounds.width = maxx - minx;
    bounds.height = maxy - miny;
    return bounds;
}

它返回精灵的(minx,miny,x投影,y投影),我们如何根据这些信息确定碰撞,IMO您需要所有四个坐标来确定碰撞对吗?因为在上述情况下,一个面向 +45° 和 -45° 的矩形可以在 BoundingRectangle 上方具有相同的值。

总结一下问题,BoundingRectangle如何足够信息来检测碰撞,是不是有些信息丢失了?

【问题讨论】:

  • 是的,对于旋转的精灵,边界框比精灵大,因为这个边界框总是轴对齐的(边界框的使用总是高速近似,精度较低) .另请注意,为了检测碰撞,精灵中的内容很重要,因为精灵本身就是一个矩形,它始终是非矩形对象(例如球)的近似值。
  • @tevemadar 我一直在努力理解这一点。我尝试使用 shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); shapeRenderer.setColor(255, 255, 255, 1); Rectangle bounds = sprite.getBoundingRectangle(); shapeRenderer.rect(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); shapeRenderer.end(); 绘制演员的边界矩形,如果演员在 x 或 y 轴上行走没问题,但在任何其他方向,边界演员都会变形,这里是 youtu.be/KyzI72CWQR0。这是预期的吗?正如你提到的。
  • 是的,这很正常。如果您可以同时绘制边界框和精灵,您可能会发现它更容易跟随。

标签: java libgdx


【解决方案1】:

Sprite 碰撞检测的工作原理是检查两个对象的 x 和 y 值是否共享一个坐标。 如果发生这种情况,那么您就知道物体发生了碰撞。对象的xy 值还包括形状内的值。

但是,有几种方法可以检查它们是否共享 xy 坐标,而无需检查所有可能性。

  • 对于x 值,您可以检查其他形状是否在x 位置和x 位置+width 之间。

  • 对于y 值,您可以检查其他形状是否在y 位置和y 位置+height 之间。

这会根据形状和边数而变化。

【讨论】:

  • 我同意你的观点,如果你沿着轴走,它会很好地工作,但是如果你沿着一个方向走,高度就会变成 x 和 y 上的投影,即youtube.com/watch?v=KyzI72CWQR0,现在你可以看到这种比较可能行不通。
猜你喜欢
  • 2014-01-09
  • 1970-01-01
  • 1970-01-01
  • 2011-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多