航路点之后的物体不断旋转

时间:2014-01-20 21:07:19

标签: c# unity3d

我正在尝试让一个物体在一个设定路径中从一个点移动到另一个点,但是一旦物体到达第一个路点,它就会不断旋转而不是移动到下一个点。

这是我的代码:

public class Waypoint : MonoBehaviour {

   public Transform[] wayPoint = new Transform[9]; 
   int currentWayPoint = 0;

   float rotationSpeed = 6.0f;
   public float accelerate = 1.8f;

   // Use this for initialization
   void Start () 
   {
    wayPoint[0] = GameObject.Find("Waypoint1").transform;
    wayPoint[1] = GameObject.Find("Waypoint2").transform;
    wayPoint[2] = GameObject.Find("Waypoint3").transform;
    wayPoint[3] = GameObject.Find("Waypoint4").transform;
    wayPoint[4] = GameObject.Find("Waypoint5").transform;
    wayPoint[5] = GameObject.Find("Waypoint6").transform;
    wayPoint[6] = GameObject.Find("Waypoint7").transform;
    wayPoint[7] = GameObject.Find("Waypoint8").transform;
    wayPoint[8] = GameObject.Find("Waypoint9").transform;
   }

// Update is called once per frame
void Update () 
{
    if(currentWayPoint == 9)
    {
        Destroy(this.gameObject);
    }
    else
    {
        walk();
    }
}

void walk()
{
    Quaternion rotation = Quaternion.LookRotation(wayPoint[currentWayPoint].position - transform.position);
    transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime*rotationSpeed);

    Vector3 wayPointDirection = wayPoint[currentWayPoint].position - transform.position;
    float speedElement = Vector3.Dot(wayPointDirection.normalized, transform.forward);
    float speed = accelerate + speedElement;
    transform.Translate(0,0,Time.deltaTime*speed);
}

void OnTriggerEnter(Collider collider)
{
    if(collider.tag == "WayPoint")
        currentWayPoint++;  
}

}

1 个答案:

答案 0 :(得分:2)

当你到达时,你需要增加currentWayPoint。检查当前航路点与脚本变换之间的距离是否在设定距离内(我通常使用速度)。

if (Vector3.Distance(wayPoint[currentWayPoint].position, transform.position) < Time.deltaTime * speed)
  currentWayPoint++;

P.S。我也喜欢看到人们提高他们的3D数学技能,但Unity已经为你正在做的很多事情建立了功能。 (transform.LookAt(),然后transform.Translate(Vector3.forward)* speed * Time.deltaTime) http://docs.unity3d.com/Documentation/ScriptReference/Vector3.html http://docs.unity3d.com/Documentation/ScriptReference/Transform.html