- Home /
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
Answer by Mike 3 · May 25, 2010 at 03:45 PM
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); }
$$anonymous$$ake sure you're clipping off the right axis (Try them all just in case)
I'm also having troubles. When I just set the rotation to face the target, it works fine.
var offset = myTarget.position - transform.position;
offset.z = 0;
transform.rotation= Quaternion.LookRotation(offset);
However, when I try to use the Quaternion.Slerp as suggested to smooth the turning, they start spinning around on all axis again... Thoughts