- Home /
My following enemy AI tilt back as they get near.
I am making a game while I learn and I have a simple script where AI "zombies" spawn and make their way towards me. Everything is working just how it should so far except as they get close to me they begin to tilt backwards until they are flat once they reach me. This is the code I am using for the AI. Can anyone tell me why they are tilting backwards because I am stumped so far.
public Transform target;
public float moveSpeed;
public float rotationSpeed;
private float distance;
private Transform myTransform;
void Awake ()
{
myTransform = transform;
}
// Use this for initialization
void Start ()
{
GameObject follow = GameObject.FindGameObjectWithTag ("Player");
target = follow.transform;
distance = 1.5f;
}
// Update is called once per frame
void Update ()
{
Debug.DrawLine (target.position, myTransform.position);
//Look at target
myTransform.rotation = Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
if (Vector3.Distance (target.position, myTransform.position) > distance)
{
//Move towards target
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
Answer by robertbu · Mar 16, 2014 at 03:47 AM
My guess is that your enemies are shorter than your player, or at least the pivot point of your enemies is below the level of the pivot point on the player. You can fix it by replacing line 28 with:
Vector3 dir = target.position - myTransform.position;
dir.y = 0.0;
myTransform.rotation = Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation(dir), rotationSpeed * Time.deltaTime);
This removed the 'y' component of the direction to look, so your object will not look up or down. This code assumes that your game is setup so that your objects are moving on the XZ plane.
That fixed it. I actually found that solution while looking earlier. It didn't work then. Not sure what changed, but thank you.
Thanks, You have a brilliant $$anonymous$$d. May God bless u!
Your answer
![](https://koobas.hobune.stream/wayback/20220613140341im_/https://answers.unity.com/themes/thub/images/avi.jpg)