2d follow script

hi i just started a 2d side scrolling shooter and i have a enemy that has a gun the points a the player. at first i just used LookAt but i wanted to have some dampening in the rotation so i used this code

function Update () {
var target = transform.root.gameObject.GetComponent("AI").target;
var rotate = Quaternion.LookRotation(target.position - transform.position);

transform.rotation = Quaternion.Slerp(transform.rotation, rotate, Time.deltaTime * smooth); 
}

but i get this weird error ware if i move to close it starts to rotate so that its not in 2d. please help

The easiest way is to just set one axis to 0 in the vector you pass to LookRotation.

If your game is constrained to the XY plane, that axis will be Z, etc.

Example:

function Update () {
var target = transform.root.gameObject.GetComponent("AI").target;
var offset = target.position - transform.position;
offset.z = 0;
var rotate = Quaternion.LookRotation(offset);

transform.rotation = Quaternion.Slerp(transform.rotation, rotate, Time.deltaTime * smooth); 
}