Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Here is my working piece of code to rotate an image toward a point (in my case, the mouse cursor).

float dx = newx - ploc.x;
float dy = newy - ploc.y;
float angle = (float) Math.toDegrees(Math.atan2(dy, dx));

Where ploc is the location of the image i'm rotating.

And here is the rendering code:

g.rotate(loc.x + width / 2, loc.y + height / 2, angle);
g.drawImage(frame, loc.x, loc.y);

Where loc is the location of the image and "width" and "height" are respectively the width and height of the image.

What changes are needed to make it works on a scaled context? e.g make it works with something like g.scale(sx, sy).

share|improve this question
I believe that in OpenGL you need to apply the scale after the other operations, otherwise the coordinates are scaled, and it will break rotations and translations. – Jonathan Connell Oct 7 '12 at 10:38
I'm not entirely sure if I understand you right but if you want to scale the image, I would apply the same scale to the halved width / height. Something like this: g.rotate(loc.x + (width / 2) * sx, loc.y + (height / 2)*sy, angle); – tom van green Oct 7 '12 at 11:12

First, I think it's important for you notice that what you are effectively doing is rotating the (OpenGL?) context around the center of the image by "angle" degrees. Then, with the subsequent call, you draw an image in the standard way, but being your transformation matrix changed by the rotation, you will draw a rotated image. I think it's important for you to understand this because after the call

g.rotate(loc.x + width / 2, loc.y + height / 2, angle);

all your following draw calls will be performed in the transformed context, and if you don't have this clear, it can lead to confusing draws. You can of course move back to you original matrix by applying an inverse rotation, or by performing a "push" of the matrix before the roation, and "popping" the matrix after the rotated draw.

This being said, to perform a scaled draw after the rotation it's enough that you scale your context before the draw call

g.rotate(loc.x + width / 2, loc.y + height / 2, angle);

as people have suggested. Only, remember that scaling and rotating get translated to matrix operations, therefore if you are scaling by the same amount on both axes you can perform the operations in either order, otherwise you should first rotate and then scale to have a correct result.

share|improve this answer
I scale by 2 on both axes. – nathan Oct 7 '12 at 20:04

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.