This script is attached to the turret parent. The object that rotate on X and Y is the child Cube of the Cylinder.

The target is the Sphere.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TurretAI : MonoBehaviour
    private float turnRateRadians = 2 * Mathf.PI;

    private Transform turretTop; // the gun part that rotates

    private Transform bulletSpawnPoint;

    public GameObject target;

    void Update()


    void TargetEnemy()
        if (target != null)
            Vector3 targetDir = target.transform.position - transform.position;
            // Rotating in 2D Plane...
            //targetDir.y = 0.0f;
            //targetDir = targetDir.normalized;

            Vector3 currentDir = turretTop.forward;

            currentDir = Vector3.RotateTowards(currentDir, targetDir, turnRateRadians * Time.deltaTime, 1.0f);

            Quaternion qDir = new Quaternion();
            qDir.SetLookRotation(currentDir, Vector3.up);
            turretTop.rotation = qDir;

This is a screenshot of the parent turret that I set to be static so it will not rotate too and the script attached to it :

Parent of turret

This is a screenshot of the Cube that rotate on X and Y and should be facing the target :

Cube child that rotate

And the missels :


And last when running the game you can see the Sphere target position and the turret is facing the opposite direction. If I will drag and move the Sphere the turret will rotate to it but with the missels back instead with the missels front side :

Opposite direction

  • \$\begingroup\$ If it is facing the exact opposite direction, have you tried multiplying your direction vector by -1? \$\endgroup\$ – Weckar E. Jul 28 at 19:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.