我正在创建一个在 java swing 中实现 boids 的程序。为了避免 boid 立即捕捉到它们想要的位置,我将角速度和加速度限制在静态Constants
类中定义的值。public static final double maxTurningSpeed = 1d; // radians per second
,public static final double maxAngularAcceleration = 1d; // radians per second squared
问题是,当我使用这段代码时,一些小动物会有非常不寻常的行为,比如旋转而不是被吸引到goalAngle
而不是遵循平滑的路径。当 时goalAngle == angle
,boids 似乎随机开始和停止旋转,直到它们获得一个新目标,此时大多数都处于无限循环中。
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;
}
任何指导表示赞赏