如何在Libgdx中旋转矩形? [英] How can I rotate Rectangles in 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:
当使用Intersector进行碰撞检测时,LibGDX不支持旋转的矩形。如果需要旋转矩形,则应使用用于碰撞检测的多边形。
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});
如果你要旋转它,别忘了设置Polygon的原点:
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():
boolean collision = Intersector.overlapConvexPolygons(polygon1, polygon2)
如其他答案所述,此方法仅适用于:
As mentioned in the other answer, this method only works if:
- 使用凸多边形,矩形为
- 执行多边形到多边形检查,例如:你不能混合矩形和
多边形
这篇关于如何在Libgdx中旋转矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!