I recently developed a piece of code to manage object rotation in a THREE.js environment. Although the issue is not specific to 3D.
My goal is to have my object (referred to as 'this') rotate by 0.25 radians each time a function is called, until its rotation ('this.clientRotation') matches the target rotation defined in 'this.targetRotation'. The following code snippet represents the contents of an update() function that is continuously invoked during the rendering loop.
In order to prevent oscillation when nearing the target rotation, I had to confirm whether the absolute difference between the current and target rotations was greater than the rotation amount for each call (0.25).
I also needed to check if the rotation difference in radians exceeded 180 degrees, in which case the most efficient turn would be in the opposite direction.
An additional check was required to ensure that the updated rotation remained within -PI and +PI (0-360 degrees).
// Move only if there is a significant difference between target and current rotations
// Rotations range from -PI to +PI
this.rotationSpeed = 0.25;
var absDiff = Math.abs(this.clientRotation - this.targetRotation);
if(absDiff > this.rotationSpeed){
if(absDiff < Math.PI){
// Less than 180 degrees, turn towards the target
if(this.targetRotation > this.clientRotation) this.clientRotation += this.rotationSpeed;
if(this.targetRotation < this.clientRotation) this.clientRotation -= this.rotationSpeed;
} else {
// More than 180 degrees, it's shorter to turn the other way
if(this.targetRotation > this.clientRotation) this.clientRotation -= this.rotationSpeed;
if(this.targetRotation < this.clientRotation) this.clientRotation += this.rotationSpeed;
}
// Reset rotation to stay within 0-360 degree range
if(this.clientRotation > Math.PI) this.clientRotation -= Math.PI*2;
if(this.clientRotation < -Math.PI) this.clientRotation += Math.PI*2;
}
The code functions as intended, but it may be overly complex. Are there more optimized approaches to achieving this standard rotation behavior?