How to automatically rotate turrets towards enemy direction continously?

I have a turret placed as a game-object ,i have set the target as enemy in inspector,but somehow the turrets just point towards my enemy but are not continuously rotating on z axis.what is the problem,any help thanx…!!

Here is my code

 using UnityEngine;
 using System.Collections;

 public class TurretScript: MonoBehaviour
 { 
  public Transform target;

   void Update()
   {

    Vector3 tarPos = new Vector3(target.position.x, target.position.y, 10);
    Vector3 lookPos = Camera.main.ScreenToWorldPoint(tarPos);
    lookPos = lookPos - transform.position;
    float angle = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);

   }
 }

transform.LookAt(target);
this should work i guess

Try transform.LookAt(tarPos) instead of all that rotation shennnigans :slight_smile:

delete line 15 and use this instead:

float speedOfRotation = 0.1f;

transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.AngleAxis(angle, Vector3.forward), speedOfRotation);

http://unity3d.com/learn/tutorials/modules/beginner/scripting/look-at

using UnityEngine;
using System.Collections;

public class CameraLookAt : MonoBehaviour
{
    public Transform target;
    
    void Update ()
    {
        transform.LookAt(target);
    }
}

I guess this is in 2D? Try:

Vector3 toTarget = target.position - transform.position;
float angle = Mathf.Atan2(toTarget.y, toTarget.x) * Mathf.RadToDeg;
transform.rotation = Quaternion.Euler(0, 0, angle);

Does this link give you what you’re asking for?