-->

How to Rotate AWT rectangle in JAVA?

2019-08-01 23:54发布

问题:

I am creating a small java 2D game and i want to know if there is any way to rotate AWT rectangle

AffineTransform origXform = g2d.getTransform();
AffineTransform newXform = (AffineTransform) origXform.clone();
newXform.rotate(angle, pivotX, pivotY); // pivotX ,pivotY is the starting 
point of the hand image
g2d.setTransform(newXform);
Rectangle arm = new Rectangle(bowX + 5,  bowY + 55, 60, 5);
g2d.drawImage(playerBowReadyImg, bowX, bowY, null);  //hand image

on the above code i simply draw the hand image which rotates based on the mouse position, i also set the rectangle on the hand but the problem is rectangle is not rotating along with the hand image.

also i am not using rectangle for any drawing purpose but to detect the collision.

however using g2d.draw(arm); draws the rotated rectangle but it not actually rotate the rectangle it just draws the rotated one.

any suggestion is appreciated.

Ok my question is marked as duplicate so i tried the answers i find there but the code i get only rotate my rectangle for the draw purpose only.

Image to depict the problem

now to be more specific the arrow in the image can only detect the collision for the blue rectangle (the original position) instead of the red one (rotated rectangle).

again i don't want to actually draw the rectangle but want to detect the collision when the arrow collide with the rectangle.

回答1:

See AffineTransform.createTransformedShape(Shape) which:

Returns a new Shape object defined by the geometry of the specified Shape after it has been transformed by this transform.