如何在 Libgdx 中旋转矩形?

How can I rotate Rectangles in Libgdx?

我将我的精灵旋转了 90 度,我想对我的矩形执行相同的操作以便能够将它们用于碰撞,但是 rotate() 方法不适用于矩形。

这是我做的:

treeSpr=new Sprite(new Texture(Gdx.files.internal("tree.png")));
        treeSpr.setPosition(250,700);
        treeSpr.rotate(90f); 

//Rectangle
 treeRect=new Rectangle(treeSpr.getX(),treeSpr.getHeight(),
                treeSpr.getWidth(),treeSpr.getHeight());

我认为类似的东西可以提供帮助,我现在无法测试,

//Rectangle
 treeRect=new Rectangle(treeSpr.getX(),
                        treeSpr.getY(),
                        treeSpr.getHeight(), //now is change width by height
                        treeSpr.getWidth());  //now is change height by width

注意:您可能需要调整两者的旋转原点

您可以使用渲染器 ShapeRenderer 来查看结果是否符合预期:

add 用于测试变量 class

private ShapeRenderer sRDebugRectangel = new ShapeRenderer();

添加 用于更新或绘制中的测试

sRDebugRectangel.begin(ShapeType.Filled);
sRDebugRectangel.identity();

sRDebugRectangel.rect(yourRectangle.getX(), 
                      yourRectangle.getY(),
                      yourRectangle.getWidth(),
                      yourRectangle.getHeight());

sRDebugRectangel.end();

可以查看我对这个问题的回答以使用 shaperrender,也称为:

Libgdx, how can I create a rectangle from coordinates?

旋转

您可以从矩形或精灵创建一个 Polygon(为多边形构造函数提供顶点)并使用它的 rotate(float degrees) 方法:

treePoly = new Polygon(new float[] {
               treeRect.x, treeRect.y,
               treeRect.x, treeRect.y + treeRect.height,
               treeRect.x + treeRect.width, treeRect.y + treeRect.height,
               treeRect.x + treeRect.width, treeRect.y
           });

treePoly.rotate(45f);

碰撞检测

然后可以通过 Intersector class:

进行碰撞检查
Intersector.overlapConvexPolygons(polygon1, polygon2)

请记住,此方法仅在以下情况下有效:

  • 你用convex polygons,矩形是
  • 您进行多边形到多边形的检查,例如:您不能混合使用矩形和多边形

其他答案基本正确;但是,我在使用该方法定位多边形时遇到了一些问题。澄清一下:

LibGDX 在使用相交检测碰撞时不支持旋转矩形。 如果你需要旋转矩形,你应该使用 Polygon 检测碰撞改为检测。

构建矩形多边形:

polygon = new Polygon(new float[]{0,0,bounds.width,0,bounds.width,bounds.height,0,bounds.height});

如果要旋转多边形,请不要忘记设置它的原点:

polygon.setOrigin(bounds.width/2, bounds.height/2);

现在您可以旋转碰撞多边形了:

polygon.setRotation(degrees);

此外,在代码的某处,您可能希望更新碰撞多边形的位置以匹配您的精灵:

polygon.setPosition(x, y);

我们甚至可以在屏幕上绘制多边形(用于调试目的):

drawDebug(ShapeRenderer shapeRenderer) {
    shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
    shapeRenderer.polygon(polygon.getTransformedVertices());
    shapeRenderer.end();
}

碰撞检测:

Intersector的overlapConvexPolygons():

boolean collision = Intersector.overlapConvexPolygons(polygon1, polygon2)

如另一个答案中所述,此方法仅在以下情况下有效:

  • 使用凸多边形,矩形是
  • 执行多边形到多边形检查,例如:您不能混合使用矩形和 多边形