- Home /
NPC flying towards me!!!
I am following a tutorial by BergZergArcade [][1]
and I have definitely copied out the script correctly, but instead of using a cube, I am using an NPC model. The NPC turns towards me, but if it gets too close, it rotates so that is is leaning backwards, and also, it lifts off the ground too! I have made it a rigidbody with no luck, because it still flies and rotates awkwardly. Here is the code BergZergArcade used:
using UnityEngine;
using System.Collections;
public class EnemyAi : MonoBehaviour {
public Transform target;
public int moveSpeed;
public int rotationSpeed;
private Transform myTransform;
void Awake()
{
myTransform = transform;
}
// Use this for initialization
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
}
// Update is called once per frame
void Update ()
{
Debug.DrawLine(target.position, myTransform.position, Color.clear);
//Look At Target
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
//Move Towards Target
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
I considered posting on the video, but the last comment was posted a month ago, and that's too long for me too wait. [1]: http://www.youtube.com/watch?v=pqDtPKLgbBE
Answer by fafase · Oct 29, 2013 at 11:39 AM
Don't worry this is a classic error.
You are using Transform to move the object. As a result, when it gets too close, your character may be bigger so the Slerp makes it look up to you, then the forward is now goign upwards and your guy is lifting up.
First, you should use a Character Controller. This way your guy will not go flying. Second you should only rotate the y axis, x and z remain the same.
You could check this one : http://unitygems.com/basic-ai-character/
How do I lock the axis, because the freeze position has no effect?
Sorry to keep posting, but I Put a character controller on the NPC, and he stays on the ground now, but he still rotates backwards.
I have looked again, but I still can't find it. What is it I need to do?