Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I rotate Rectangles in Libgdx?

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.

This is what I did:

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());
like image 375
Kevin Bryan Avatar asked May 31 '15 06:05

Kevin Bryan


1 Answers

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

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.

Building a Rectangular Polygon:

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

Collision Detection:

The overlapConvexPolygons() of the Intersector:

boolean collision = Intersector.overlapConvexPolygons(polygon1, polygon2)

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

  • using convex polygons, which the rectangle is
  • performing polygon to polygon checks, e.g.: you cannot mix rectangles and polygons
like image 55
Yahma Avatar answered Oct 05 '22 09:10

Yahma