如何在 Libgdx 中旋转矩形?

2022-01-12 00:00:00 android java libgdx

我将我的精灵旋转了 90 度,我想对我的矩形做同样的事情以便能够将它们用于碰撞,但是 rotate() 方法在矩形上不可用.

I rotated my sprite 90 degrees and I want to do the same with my rectangle to be able to use them for collision, but the rotate() method is not available on rectangles.

这就是我所做的:

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

推荐答案

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

The other answer is basically correct; however, I had some issues with the positioning of the polygons using that method. Just some clarification:

LibGDX 在使用 Intersector 进行碰撞检测时不支持旋转矩形.如果您需要旋转矩形,您应该使用 Polygon 用于碰撞检测.

LibGDX does not support rotated Rectangles when using the Intersector for collision dectection. If you need rotated rectangles, you should use the Polygon for collision detection instead.

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

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

Don't forget to set the origin of the Polygon if you are going to rotate it:

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

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

Now you can rotate the collision polygon:

polygon.setRotation(degrees);

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

Also, somewhere in your code, you will likely want to update the position of the collision polygon to match your sprite:

polygon.setPosition(x, y);

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

We can even draw our polygon on screen (for debug purposes):

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

碰撞检测:

Intersector<的overlapConvexPolygons()/a>:

Collision Detection:

The overlapConvexPolygons() of the Intersector:

boolean collision = Intersector.overlapConvexPolygons(polygon1, polygon2)

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

As mentioned in the other answer, this method only works if:

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

相关文章