简体   繁体   中英

How to rotate actor using the shortest direction in libgdx, scene2d?

When I want to rotate an actor using the RotateToAction , eg from 0 degrees to 300 degrees, the actor rotates 300 degrees (duh), but the same could be achieved with counterclockwise rotation of 60 degrees, which is what I want.

If I use the RotateByAction and set the angle to negative 60 degrees, I get a negative rotation value for my actor, which is also not what I want.

So how to use either action to rotate my actor to a certain angle, always using the shortest rotation and maintain a positive rotation value between 0 and 360?

It isn't exactly clear what you mean by "maintain a positive rotation value". If you want to rotate the actor to 270 degrees, the shortest rotation that can be performed is -90 degrees. A counterclockwise rotation is inherently negative...

Assuming you only want to specify a degree value between 0 and 360, and have the actor figure out whether to rotate clockwise or counter-clockwise, you could try writing your own action. How about something like this?

public class MyRotateAction extends Action {
    private Actor actor;
    private int finalDegrees;

    public MyRotateAction(Actor actor, int finalDegrees) {
        this.actor = actor;
        this.finalDegrees = finalDegrees;
    }

    @Override
    public boolean act(float delta) {
        if (finalDegrees - actor.getRotation() > 180) { //perform negative rotation
            actor.addAction(rotateBy(actor.getRotation() - finalDegrees));
        } else { //perform positive rotation
            actor.addAction(rotateBy(finalDegrees - actor.getRotation());
        }
    }
}

Try keeping your actors angle with a value between 0 and 360, it makes everything easier depending on the game:

float a = actor.getRotation();
if(a > 360) 
    a -= 360;
if(a < 0) 
    a += 360;
actor.setRotation(a);

Find the nearest angle value to rotate to that is less or equal to 180° away from your actors angle, for example:

float degrees = angle_to_rotate_to;
float a = actor.getRotation();

if(degrees-a < 180) degrees += 360;
if(degrees-a > 180) degrees -= 360;

Alternatively if you do not want to restrain your actors angle to 0 and 360:

float degrees = angle_to_rotate_to;
float a = actor.getRotation();
while (degrees-a < 180) degrees += 360;
while (degrees-a > 180) degrees -= 360;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM