Finding the shorter turning direction towards a target

Posted by A.B. on Game Development See other posts from Game Development or by A.B.
Published on 2013-06-28T19:46:24Z Indexed on 2013/06/28 22:29 UTC
Read the original article Hit count: 284

Filed under:
|

I'm trying to implement a type of movement where the object gradually faces the target. The problem I've run into is figuring out which turning direction is faster. The following code works until the object's orientation crosses the -PI or PI threshold, at which point it will start turning into the opposite direction

void moveToPoint(sf::Vector2f destination) {
    if (destination == position) return;

    auto distance = distanceBetweenPoints(position, destination);
    auto direction = angleBetweenPoints(position, destination);

    /// Decides whether incrementing or decrementing orientation is faster
    /// the next line is the problem
    if (atan2(sin(direction - rotation), cos(direction - rotation)) > 0 ) {
        /// Increment rotation
        rotation += rotation_speed;
    } else {
        /// Decrement rotation
        rotation -= rotation_speed;
    }

    if (distance < movement_speed) {
        position = destination;
    } else {
        position.x = position.x + movement_speed*cos(rotation);
        position.y = position.y + movement_speed*sin(rotation);
    }
    updateGraphics();
}

'rotation' and 'rotation_speed' are implemented as custom data type for radians which cannot have values lower than -PI and greater than PI. Any excess or deficit "wraps around". For example, -3.2 becomes ~3.08.

© Game Development or respective owner

Related posts about movement

Related posts about rotation