Question

I am writing a simple game, or so it seemed, that has a functionality of rotating a Rectangle as the mouse moves. This did not seem like a problem at first but it just became a problem. What the Rectangle should do is rotate around a point as the mouse moves around on the Panel.

enter image description here

If you look at the picture, when the mouse moves the Rectangle will rotate. I know you can use the rotate functionality with Graphics2D.

g2d.rotate(angle, centerx, centery);

This is not very help full because I can not get the coordinates of the moving rectangle. This rotates the full graphics! How will I be able to draw this Rectangle so that it does this. I don't have an idea as on how to start. Please help.

Was it helpful?

Solution

Some more code and context would be nice, but based on the current question: You could create a transformed shape. Particularly, Rectangle and Rectangle2D implement the Shape interface. And you can create an AffineTransform that represents the rotation that you are currently doing to your Graphics. So the relevant part of the code should roughly look like

Rectangle2D rectangle = ...
AffineTransform at = AffineTransform.getRotateInstance(
    angle, centerx, centery);
Shape rotatedRectangle = at.createTransformedShape(rectangle);
g2d.draw(rotatedRectangle);

You mentioned "collision" in the title. If you intend to use this rectangle in some sort of collision detection, you should note that it is not directly possible to intersect two arbitrary Shape objects. Particulary, you can not intersect the Shape rotatedRectangle with another Shape otherRotatedRectangle, but only with a Rectangle otherRectangle. If this is an issue, you have several options, but this would rather fit into a dedicated question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top