If I understand correctly, LibGDX is rotating an image with the use of the addActions method:
this.addAction( parallel(rotateBy(360, 0.5f), moveTo(320, 100, 0.5f)));
The thing is, it is being rotated by the point=(0,0) of the image.
Here’s my question:
Is there a way to rotate an image by the center point of the object? Something like pinning it in the middle and then turning it like a wheel in a car?
Both rotateBy and rotateTo methods turn it by the (0,0) point of the image itself.
You have to properly set the “origin” of you actor. You can read from the Actor API that the origin is relative to the position and is used for scale and rotation.
So, calculate your middle point, and set origin to middle point.
Actor a; .... a.setOrigin(a.getWidth()/2, a.getHeight()/2);
The easiest way is to translate the object so the 0,0 point is the centre, rotate it, then translate it back into position. I’m not familiar with libGDX, but there should be a method for aggregating the three transforms, meaning you apply only the one aggregated transform to your object. Keep in mind the order you aggregate the transforms, makes a difference.
A much more complicated way that gives exactly the same result involves calculating the amount of offset created by the rotate and translating the image back to its origin. Don’t do it this way. Combining three simple transforms is the way to go and one of the best reasons for using transforms.
Looking at the API the Actor object has a translate() method. Use this to shift your image so the 0,0 point is in the centre. In psuedocode;
x = this.getX(); y = this.getY(); cx = this.getWidth() * .5; cy = this.getHeight() * .5; this.translate(-(x+cx), -(y+cy)); // move so 0,0 is the centre of the Actor object this.rotate(thisMuch); // rotate the Actor this.translate((x+cx), (y+cy)); // move it back to its original location
This will result in your object rotating on its centre point, on the spot. It looks convoluted, but its pretty efficient in practise, more so if you are able to work direct with the matrices (transforms) that will be driving these methods.
Here is the simple way how can you rotate an actor in libgdx.
First, you need to set the origin:
Now you can rotate clockwise and anticlockwise, according to your need:
The easiest and shortest way I found for setting the origin is to call:
Actor a; ... a.setOrigin(Align.center);