Turret

Frocha

Member
I've been tinkering with the sample turret to limit its rotation, and somewhat succeeded with some help but now it continues to rotate from the players position unless i'm really close. If i'm far away it will barely move. Anyone have any suggestions on what i can do to fix this?

C#:
/// <summary>
        /// Clamps a rotation around a defined axis
        /// </summary>
        /// <param name="q">Quaternion to clamp</param>
        /// <param name="axis">Axis to clamp - 0 = x axis, 1 = y axis, 2 = z axis</param>
        /// <param name="minAngle">min angle</param>
        /// <param name="maxAngle">max angle</param>
        /// <returns>Clamped Quaternion</returns>
        private Quaternion ClampRotationAroundAxis(Quaternion q, int axis, float minAngle, float maxAngle)
        {
            q.x /= q.w;
            q.y /= q.w;
            q.z /= q.w;
            q.w = 1.0f;

            float angle = 2.0f * Mathf.Rad2Deg * Mathf.Atan(q[axis]);

            angle = Mathf.Clamp(angle, minAngle, maxAngle);

            q[axis] = Mathf.Tan(0.5f * Mathf.Deg2Rad * angle);

            return q;
        }
        /// <summary>
        /// Keep facing the target so the turret can fire at any time.
        /// </summary>
        public void RotateTowardsTarget()
        {
            
        var targetRotation = Quaternion.Euler(0, Quaternion.LookRotation(m_TurretHead.position - m_Target.position).eulerAngles.y, 0);

            targetRotation = ClampRotationAroundAxis(targetRotation, 1, 45f, -45f);
            
            m_TurretHead.rotation = Quaternion.Slerp(m_TurretHead.rotation, targetRotation, m_RotationSpeed * Time.deltaTime);
        }
 
If I understand correctly, you want to limit the turret's rotation so that it can't rotate beyond a certain point compared to its default rotation?

If so, then you should be altering m_TurretHead.rotation after the rotation is applied, rather than altering targetRotation. Your clamp script also looks needlessly complicated to me. You should be able to simply clamp the turret's eulerAngles with something like m_TurretHead.eulerAngles = new Vector3(m_TurretHead.eulerAngles.x, Mathf.Clamp(m_TurretHead.eulerAngles.y, 90, 270), m_TurretHead.eulerAngles.z);
 
Top