如何在 Libgdx 中旋转矩形?

时间:2023-03-01
本文介绍了如何在 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:

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

这篇关于如何在 Libgdx 中旋转矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:有没有办法在 libGDX(Android 和 iOS 项目)中推送通知? 下一篇:使用 libGDX 写入 Json

相关文章