javaangleboids

Calculate which way to turn a boid to get to an object in Java


tl;dr: I have angle x and angle y in radians; Which way do I need to turn angle x to match angle y?

I have a boid with an angle which desires to point towards a goalAngle (angles are in radians). However the boid cannot turn at a speed greater than defined in Constants.maxTurningSpeed (multiplied by timePassed - how long it has been since the last physics update). If this speed is exceeded then it should instead turn at the maximum speed in that direction. The only issue is which direction.

The following code works for most scenarios but can break when going over the 0 threshold. Any help?

if ((this.goalAngle - this.angle) % (2*Math.PI) > (Constants.maxTurningSpeed*timePassed)) { // turn left or right?
    this.angle += Constants.maxTurningSpeed*timePassed;
} else if ((this.goalAngle - this.angle) % (2*Math.PI) < -(Constants.maxTurningSpeed*timePassed)) {
    this.angle -= Constants.maxTurningSpeed*timePassed;
} else {
    this.angle = this.goalAngle;
}

Thanks


Solution

  • I found a solution online in this blog post by Paul Bloxel. This better describes the issue and solution.