Java boid rotation limiting

118 views Asked by At

I'm creating a program which implements boids in java swing. To avoid boids snapping to their desired location instantly, I am limiting the angular velocity and acceleration to values defined in the static Constants class. public static final double maxTurningSpeed = 1d; // radians per second , public static final double maxAngularAcceleration = 1d; // radians per second squared

Image of boids

The issue is that when I use this code, some boids have very unusual behaviour suc as spinning rather than being attracted to the goalAngle and not following a smooth path. When goalAngle == angle, the boids seem to randomly start and stop spinning until they get a new goal, by which point most are in infinite loops.

    public void alterCourse(double timePassed) {
        // if the distance (rad) to the goal Angle > max turning speed, angle += turningspeed, else ange = goal angle
        
        double newAngularVelocity =  Math.abs(goalAngle-angle);
        
        if (Math.abs(newAngularVelocity-angularVelocity) > Constants.maxAngularAcceleration) {
            // if Planned acceleration > the max acceleration
            this.angle += (angularVelocity+Constants.maxAngularAcceleration)
                    * (goalAngle-angle < 0 ? 1 : -1); // negative if  the difference between the angle > 0
            this.angle %= (2 * Math.PI);
        }
        
        if (newAngularVelocity > Constants.maxTurningSpeed*timePassed) {
            this.angle = this.goalAngle % (2 * Math.PI);
        } else if ((angle+goalAngle) % (Math.PI*2) > Math.PI) { // Left/Right turn
            this.angle += Constants.maxTurningSpeed*timePassed;
        } else {
            this.angle -= Constants.maxTurningSpeed*timePassed;
        }

        angularVelocity = newAngularVelocity;
    }

Any guidance appreciated

0

There are 0 answers