0
\$\begingroup\$

I'm currently trying to rotate a sprite around its own axis to make it "face" the mouse, but I'm having weird results. This is my code:

public void turnTowards(Vector2 direction)
{
    turnTowards(direction.x, direction.y);
}

public void turnTowards(float x, float y)
{
    this.facing.set(x, y);
    float angle = MathUtils.atan2(facing.y, facing.x);
    angle = angle * (180f/MathUtils.PI);
    turn(angle);
}

//Turns the ship away from the given position in world space.
public void turnAway(Vector2 direction)
{
    turnAway(direction.x, direction.y);
}

//Turns the ship away from the given position.
public void turnAway(float x, float y)
{
    this.facing.set(-x, -y);
    float angle = MathUtils.atan2(facing.y, facing.x);
    angle = angle * (180f/MathUtils.PI);
    turn(angle);
}

// This rotates the ship sprite towards the specified angle by a given turn speed.
// For more info on LibGdx's Sprite.rotate() read this:
//      https://gamedev.stackexchange.com/questions/88317/sprite-rotation-libgdx
public void turn(float angle)
{
    updateDelta();
    //sprite.rotate(angle);
    Gdx.app.log("ShipTurning Debug", "Ship angle is " + angle);
    sprite.setOrigin(position.x, position.y);
    sprite.setRotation(angle);
}

And here are my results (note: I had to zoom out on the star system scene to keep the ships in sight):

enter image description here

enter image description here

enter image description here

As you can see, the sprites are being rotated/orbited, but I'm just trying to change the orientation at which they are facing. Their position should not be moving remotely as drastically as it is. They're basically orbiting around their original position, instead of rotating their orientation. How can I change their orientation so that it faces the mouse (the mouse's unprojected/world coordinates are being fed to the turnTowards function, for some reference).

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Okay, I figured it out. Sprite.setRotation and Sprite.rotate rotate around the sprite's origin, which by default is its position, so the sprite is rotating around that position in my images. When you call Sprite.setOrigin(sprite.getWidth()/2f, sprite.getHeight()/2f) you're setting its rotation origin to be its center. Thus, you get the desired behavior.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .