0

I have a problem with rotating image in a fixed position with Graphcis2D and AffineTransform.

The idea is to rotate an image according to body's rotation.

The rotation is happening correctly as the rotation angle of the image matches the angle of the body's rotation. However, as the rotation takes place, the image is not drawn to the same position as the body should be drawn. The code of the method painting the picture is the following:

public void paintPicture(Graphics g, Body body) {

    Graphics2D g2 = (Graphics2D) g;

    Vector2f[] vertices = ((Box) body.getShape()).getPoints(body.getPosition(), body.getRotation());

    Vector2f topLeftCorner = vertices[0];

    AffineTransform oldTransform = g2.getTransform();

    AffineTransform at = new AffineTransform();

    at.rotate(body.getRotation());

    g2.setTransform(at);

    g2.drawImage(this.img, (int) topLeftCorner.x, (int) topLeftCorner.y, null);

    g2.setTransform(oldTransform);
}

Any ideas what might cause the movement of the image instead of drawing it according to the coordinates (topLeftCorner.x, topLeftCorner.y)?

1 Answer 1

0

You need to first translate you object so the anchor point (the point around which you want it to rotate) is at the origin, perform your rotation, then translate it back. So if you want to rotate around the point (50, 75), you'd do the following:

at.translate (-50, -75);
at.rotate (body.getRotation());
at.translate (50, 75);

I'm assuming that your AffineTransform class can accumulate transformations. If not, you'll need 3 different transforms.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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