- Home /
Question by
Qriva · Mar 09 at 12:43 AM ·
rotationquaterniontargettowards
Rotate towards target around axis with limits
Hello, I want to create script that rotates object around any given axis, towards target, but without allowing it to exceed certain angles. The closest reference would be turret on the battleship - it rotates relative to the hull, but in certain allowed angles (cannot turn 360). So far I came up with something like this, but I want my code to be the most performant as possible, so my question is: can this be done better?
Actually I made also other version using Vector3.RotateTowards and it looks like a bit faster, but angle limits must be the same in both directions (it can't be Vector2(-10, 30) for example).
// First rotate on given axis, in this case base.transform.right
Vector3 diff = (target.position - transform.position);
Vector3 targetProjection = Vector3.ProjectOnPlane(diff, base.transform.right);
Quaternion targetRotation = Quaternion.LookRotation(targetProjection, base.transform.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime);
// Clamp to local limits
Vector3 eulerAngles = transform.localRotation.eulerAngles;
// Euler angles are 0 .. 360, so "remap" to -180 .. 180
if (eulerAngles.x > 180f)
{
eulerAngles.x -= 360f;
}
transform.localRotation = Quaternion.Euler(Mathf.Clamp(eulerAngles.x, -10f, 10f), 0, 0);
Comment