Jump to content
  • Advertisement
Sign in to follow this  

Java Graphics2D not rotating right

This topic is 1473 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts


I tried to make a program where two rectangles are rotating around their centers.

But the second of them is orbiting around the first one.


private void drawRect(int x, int y, int width, int height, double angle,
			Graphics2D g2) {
		AffineTransform old = g2.getTransform();
		AffineTransform af = new AffineTransform();
		af.rotate(Math.toRadians(angle), (double) width / 2.0,
				(double) height / 2.0);

		g2.fillRect(x, y, width, height);


and then:



I tried using g2.rotate first,but it gave me the same problem,so I tried using AffineTransform.Of course,nothing changed...

Screenshot is attached.




Share this post

Link to post
Share on other sites

This looks like homework.  biggrin.png


It looks like you're using the transform() method which takes the given transform and adds it to the current transform, but you want the setTransform() method which overwrites the current transform with the new transform.  


Javadocs are your friend.  


Share this post

Link to post
Share on other sites

Thanks @Glass_Knife but it didn't help...

It seems that even if I remove all code for drawing the blue rect,the red rect still orbites.Same thing if I first draw red,and then blue rect... Weird...

And it's not homework :)

Share this post

Link to post
Share on other sites

and you changed it all to setTransform() and it still didn't work?  Hmm.  It is time to create a condensed example and post to whole thing so someone can run it or at least see everything.


I do remember that the AffineTransform does a column major multiply, so the combinations go in reverse order from what you might expect, but I've done this before and it does work just like it should.

Share this post

Link to post
Share on other sites

Maybe I'm wrong here, but the anchor point you are using for your rotation is just width/2, height/2, you have to adjust for the x and y coordinates of the rectangle. If you modify your anchor point to:

af.rotate(Math.toRadians(angle), (double) (x + width / 2.0),
                (double) (y + height / 2.0));

Let us know...

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!