Search code examples
javarotationslick2dimage-rotation

My Slick2d Image does not rotate as expected


I have a simple image in my Slick2d based Java game and I am trying to rotate it 90 degrees. However, when using the "Image.rotate(angle)" method the image ends up moving as well as rotating. I have tried forcefully setting the centre of rotation to be the exact centre of the image but the results are the same. Here are the before and after shots. The idea is that the tank will rotate 90 degrees and remain in the same square. The centre of rotation that was forcefully set is shown by the dot after the rotation:

Before: before

After: after

The code:

    public void turn(String direction){
    if(direction.equals("right")){
        if(movableEntityImage.getRotation() != 90){
            System.out.println("Pre rotate x = " + x + " . Pre rotate y = " + y + ". width = " + width + ". height = " + height);
            System.out.println("Pre rotate rotation = " + movableEntityImage.getRotation());
            float rotX = (x + (width/2));
            float rotY = (y + (height/2));
            movableEntityImage.setCenterOfRotation(rotX, rotY);
            System.out.println("center of rotation X = " + movableEntityImage.getCenterOfRotationX() + ".center of rotation y = "+ movableEntityImage.getCenterOfRotationY());
            movableEntityImage.rotate(90);


            System.out.println("Post rotate x = " + x + " . Post rotate y = " + y);
            System.out.println("Post rotate rotation = " + movableEntityImage.getRotation());



        }

    }

And finally the console output:

The tank has been created with an x of: 50.0 and a y of: 50.0
Pre rotate x = 50.0  Pre rotate y = 50.0  width = 25.0  height = 25.0
Pre rotate rotation = 0.0
Center of rotation X = 62.5  Center of rotation y = 62.5
Post rotate rotation = 90.0

Am I missing something? Or have I gone about this in the wrong way.

Thanks, Josh


Solution

  • Solved. The problem was with the centre of rotation. It appears that when you set a centre of rotation for an image, the axis 0,0 is actually at the top left hand corner of the image and not the top left hand corner of the game container. So in my example I was setting the centre of rotation x coordinate to be the X coordinate of the image plus its width over 2, when actually I only needed to set it to be the width over 2.