Added a little turret follow after chasing them in circles

While I was chasing around the tanks I decided to add some turret rotation.

TurretRotation

5 Likes

This is so good! How did you do it?

The code is similar to the one used in the next lecture. My model has an object that is the cannon. I was just turning it. and the code I took from this page: unity - how to rotate something to point to something else

My code
public class Targeter : NetworkBehaviour
{

   // .... Removed some parts from the standard solution .... //

    [SerializeField] private Transform turretObject = null;
    [SerializeField] private float turnSpeed = 20f;

   // .... Removed some parts from the standard solution .... //

    private void Update()
    {
        // Object might not have a turret object that can be turned
        if (turretObject != null)
        {
            // Tasrget might not be set.
            if(target != null)
            {
                // Getting the look direction to the target
                Vector3 dir = target.transform.position - turretObject.transform.position;
                Quaternion lookRotation = Quaternion.LookRotation(dir);

                // Using a lerp to turn the cannon toward the target.
                Vector3 rotation = Quaternion.Lerp(turretObject.rotation, lookRotation, Time.deltaTime * turnSpeed)
                    .eulerAngles;

                // doing the actual turn.
                turretObject.rotation = Quaternion.Euler(0f, rotation.y, 0f);
            }
            else if (Mathf.Abs(turretObject.transform.rotation.y) > Mathf.Epsilon)
            {
                // if there I no target, turn the cannon slowly back to the local zero position.
                Vector3 rotation = Quaternion.Lerp(turretObject.localRotation, Quaternion.Euler(0f, 0f, 0f), Time.deltaTime * turnSpeed).eulerAngles;
                turretObject.localRotation = Quaternion.Euler(0f, rotation.y, 0f);
            }
        }
    }

}

The main thing was to figure out to use the local rotate for the reset to the zero position.

The other thing is, you need to make the turret object a Network Transform Child so the client can see the rotation. You need to add that to your base object and add the object you care about to the Target field.

Privacy & Terms