Pyrox
Pyrox

Reputation: 569

LibGDX 1.5 rotating sprite around its center

I am trying to rotate a sprite around its center, but no matter what I try, I always get it rotating around a corner. I create the sprite in this way:

Pixmap pixmap = new Pixmap(64, 64, Format.RGBA8888);
pixmap.setColor(153/255f, 255/255f, 153/255f, 255/255f);
pixmap.fillTriangle(0, 0, 0, 32, 32, 16);
Texture texture = new Texture(pixmap);
triangle = new Sprite(texture);
triangle.setSize(3, 3);
triangle.setOriginCenter();
triangle.setPosition(0 - triangle.getWidth() / 2.0f, 0 - triangle.getHeight() / 2.0f);

then I rotate it every deltaTime in this way:

triangle.rotate(90 * deltaTime);

and render it like this:

batch.begin();
worldController.triangle.draw(batch);
batch.end();

I am following the example in the book "Learning LibGDX Game Development, Second edition", so I have a WorldController and a WorldRenderer. What am I missing? Shouldn't it be enough to set the sprite origin to its center and draw it? This is the behaviour I am having:

enter image description here

while I would like it to rotate "in place".

Upvotes: 4

Views: 3612

Answers (2)

Pyrox
Pyrox

Reputation: 569

Ok, I found the problem. At first I declared the pixmap with a 32x32 size and filled the triangle accordingly. Then I was messing around with it and changed the size to 64x64, but the triangle was drawn by using the old coordinates, thus occupying the bottom left "subsquare" of the whole pixmap, that's why it was rotating in that way.

Upvotes: 1

Fish
Fish

Reputation: 1697

It seems that you have missed the line

triangle.setOrigin(originX, originY);

(originX, originY) being the center coordinates of your triangle.

EDIT: The reason why your current code doesn't work is because the current center origin is (0, 0).

(I am not sure why but it appeared to be the center when I tested your code). You can add logs to your code through using

Gdx.app.log("Tag", "LogInformation");

Here is what you should do

originX = (0+32)/2;
originY = (0+32)/2;

or

originX = (lowestXValue+highestXValue)/2;
originY = (lowestYValue+heightYValue)/2;

Here is the API on Sprite, it could help you more on rotate()

Upvotes: 1

Related Questions