0

How can I rotate a sprite in a Java 2D game, without rotating the entire screen? I want to rotate only the sprite.

I tried doing this:

(g2d is a Graphics2D object);

g2d.rotate(Math.toRadians(30), 50, 50);
g2d.drawImage(image1, 50, 50, this);

g2d.rotate(Math.toRadians(50), 100, 100);
g2d.drawImage(image2, 100, 100, this);

But instead of rotating image1 by 30 degrees, and then rotating image2 by 50 degrees, each rotation affects the entire screen.

Is there a way to rotate only a specific sprite in a game, using the g2d.rotate() method? If not: I've been told I could use AffineTransform object, but couldn't find online a tutorial that actually explains how to use this confusing object from the beginning. Could you give me a link or explain to me how to do that with an AffineTransform object?

I would like the most 'standard' way to do this in a normal 2D game.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user3150201
  • 1,901
  • 5
  • 26
  • 29
  • This page covers a simple use of the AffineTransform class: http://www.javalobby.org/java/forums/t19387.html however it will not address your issue because you are rotating the g2d object and not the image you are drawing to it (that is a larger answer) – Jason Sperske Jan 01 '14 at 17:12
  • Rotate, draw, rotate back? – tilpner Jan 01 '14 at 17:12
  • For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Jan 01 '14 at 17:14
  • Here is an example for how to draw an image with its own AffineTransformation (rotating just the image) http://stackoverflow.com/a/4919880/16959 – Jason Sperske Jan 01 '14 at 17:15
  • I don't want to specifically rotate the g2d object, it's just that it's the only way I know. Could you link me to a page that explains how to rotate specifically an image? I'd like to know the best way to do that. – user3150201 Jan 01 '14 at 17:15

1 Answers1

1

You need to reset your graphics whenever you make changes to it because it will be used to render children and possibly other components. There are a couple of ways of doing this. The best way of doing this is generally to make a copy using Graphics.create(). However, in your case it may be easier to undo the individual changes:

g2d.rotate(Math.toRadians(-30), 50, 50);
g2d.drawImage(image1, 50, 50, this);
g2d.rotate(Math.toRadians(30), 50, 50);

g2d.rotate(Math.toRadians(50), 100, 100);
g2d.drawImage(image2, 100, 100, this);
g2d.rotate(Math.toRadians(-50), 50, 50);

Note that calling rotate, etc. is actually applying an AffineTransform to your current graphics configuration.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264