Reputation: 15
I am creating a basic 2D game and I am currently trying to get the x and y (Point) of all of the rectangle's corners while I rotate the rectangle.
private static Graphics2D drawRect(Graphics2D g)
{
Rectangle rect = new Rectangle(350,350,75,75);
AffineTransform transform = new AffineTransform();
transform.rotate(Math.toRadians(rotation), rect.getX() + rect.width/2, rect.getY() + rect.height/2);
AffineTransform old = g.getTransform();
g.transform(transform);
g.fill(rect);
if(z >= 1000)
{
// here I am asking it to print out the x,y of the point at the top left of the rectangle
System.out.println(rect.getX() + " : " + rect.getY() + " : " + rotation);
z = 0;
}
g.setTransform(old);
z++;
return g;
}
When I run this it starts at 350, 350 as shown and will rotate in either direction depending on how I increment it. It rotates through graphics correctly. But when I want to print the point of the x,y of the original top left point it always returns with 350, 350. If I rotate it 45 degrees in the positive direction it would return 350, 350. I have made a click function so I can click on the screen and it properly returns the x and y of the click spot. When I click on the original top left corner of the rectangle it returns 311,334. This is the return I am looking for when calculating the top left corner x,y. Visual here:
Upvotes: 1
Views: 589
Reputation: 2789
You are applying your transform on the graphics object. Therefore, the rectangle object itself is not modified.
AffineTransform
has two methods you can make use of. createTransformedShape
which returns a new shape that is transformed accordingly or transform(Point2D ptSrc, Point2D ptDst)
which will transform the point ptSrc and save the transformed point in ptDst:
Point rotatedPoint = new Point();
transform.transform(new Point(rect.x, rect.y), rotatedPoint);
Upvotes: 2