Java Graphics2D not rotating right

Started by
3 comments, last by ArrTaffer 9 years, 7 months ago

Hello,

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.

Code:


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.transform(af);

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

		g2.transform(old);
	}

and then:


g2.setColor(Color.BLUE);
drawRect(0,0,100,100,angle,g2);

g2.setColor(Color.RED);
drawRect(200,200,50,100,angle2,g2);
angle+=0.3;
angle2++;

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.

Help!!!

Thanks,

MatejaS

Advertisement

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.

http://docs.oracle.com/javase/8/docs/api/java/awt/Graphics2D.html#transform-java.awt.geom.AffineTransform-

I think, therefore I am. I think? - "George Carlin"
My Website: Indie Game Programming

My Twitter: https://twitter.com/indieprogram

My Book: http://amzn.com/1305076532

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 :)

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.

I think, therefore I am. I think? - "George Carlin"
My Website: Indie Game Programming

My Twitter: https://twitter.com/indieprogram

My Book: http://amzn.com/1305076532

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...

This topic is closed to new replies.

Advertisement