- Home /
Efficient Rotation with Different Rotation Rates on Each Axis
I am currently developing the AI behavior for a 3D space simulation game. The first behavior I am attempting to implement is for an NPC to rotate towards a target.
Note: Each axis the ship can rotate on (pitch, yaw, and roll) has a set rotation rate. As such, I am not sure if it is possible to implement this using Quaternion.RotateTowards(). I am currently rotating incrementally to face the target as shown in the code below:
private void LookAtTarget()
{
// Find the Target Rotation to Look At
Vector3 targetRotation = Quaternion.LookRotation(target.transform.position - this.transform.position, Vector3.up).eulerAngles;
Vector3 currentRotation = this.transform.rotation.eulerAngles;
Vector3 rotationIncrement = Vector3.zero; // Our Vector3 to Store the Rotational Increment
// Get Pitch Increment Amount
GetRotationIncrementOnAxis(currentRotation.x, targetRotation.x, pitchRate, ref rotationIncrement.x);
// Get Yaw Increment Amount
GetRotationIncrementOnAxis(currentRotation.y, targetRotation.y, yawRate, ref rotationIncrement.y);
// Get Roll Increment Amount
GetRotationIncrementOnAxis(currentRotation.z, targetRotation.z, rollRate, ref rotationIncrement.z);
// Apply Rotation Increment to our Current Rotation
this.transform.rotation = Quaternion.Euler(currentRotation + rotationIncrement);
}
/**
* Helper method for LookAtTarget() for getting the rotation increment on a specific axis
*/
private void GetRotationIncrementOnAxis(float currentRotation, float targetRotation, float rate, ref float rotationIncrement)
{
// Determine the Direction to Rotate
float sign = Mathf.Sign(targetRotation - currentRotation) * -Mathf.Sign(Mathf.Abs(targetRotation - currentRotation) - 180);
// Apply Rotation Rate and Frame Time
rotationIncrement = sign * rate * frameTime;
// Adjust Rotation Increment if it is Greater than the Difference between our Target and Current Rotations
if (Mathf.Abs(targetRotation - currentRotation) < Mathf.Abs(rotationIncrement))
{
rotationIncrement = targetRotation - currentRotation;
}
}
This code achieves the desired behavior. However, it proves to be inefficient when the rotation rate of a specific axis is very low. For instance, one ship has the given rotation rates below:
Pitch: 60
Roll: 45
Yaw: 20
In this case, it would be much more effective to pitch and roll to face the target. How could I find the fasted way to rotate towards the target when each axis has a different rotation rate?
Thank you in advance for any advice or resources you can provide!