NPC不会在玩家的某个距离停下来

时间:2016-09-26 13:54:37

标签: c# unity3d

我有一个跟随我的玩家的NPC,但是当它离玩家一定距离时我不能让它停下来。这一直令我感到沮丧,因为网上没有任何内容可以做到这一点。

他们碰撞​​并互相撞击!

这是我移动NPC的代码:

using UnityEngine;
using System.Collections;

public class AI : MonoBehaviour {
public Transform target;
public int moveSpeed = 5;
public int rotationSpeed = 2;
public Transform myTransform;

void Awake ()
{
    myTransform = transform;
}

void Start ()
{
    target = GameObject.FindWithTag ("Player").transform;
}

void Update ()
{
    myTransform.rotation = Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * moveSpeed * Time.deltaTime);
    myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;

}
}

1 个答案:

答案 0 :(得分:1)

如果距离很远,您只需要应用移动代码。如果它足够接近,则不应用移动代码。即更新应该是:

Vector3 Distance = target.position - myTransform.position;
if(Distance.sqrMagnitude>minDistance*minDistance)
{
    myTransform.rotation = Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * moveSpeed * Time.deltaTime);
    myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}