Java – how do I rotate a rectangle in libgdx?

I rotate my sprites 90 degrees. I want to do the same for my rectangles so that they can be used for collisions, but the rotation () method is not available on rectangles

This is what I do:

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

Solution

The other answer is basically correct; However, I encountered some problems when using this method to locate polygons Just to clarify:

When using intersector for collision detection, libgdx does not support rotating rectangles If the rectangle needs to be rotated, polygon should be used for collision detection

To build a rectangular polygon:

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

If you want to rotate a polygon, don't forget to set its origin:

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

You can now rotate the collision polygon:

polygon.setRotation(degrees);

In addition, somewhere in the code, you may want to update the position of the collision polygon to match your Sprite:

polygon.setPosition(x,y);

We can even draw polygons on the screen (for debugging purposes):

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

Collision detection:

Overlapconvexpolygons() of intersector:

boolean collision = Intersector.overlapConvexPolygons(polygon1,polygon2)

As stated in other answers, this method is only effective if:

>Use the convex polygon where the rectangle is located > to perform a polygon to polygon check, for example: you can't mix rectangles and polygons

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>