我创建了一个应该遵循特定路径的脚本。这是我的剧本。但是当我运行我的脚本时没有任何反应。实际上胶囊应该朝向路径持有者的子对象移动。我尝试过使用Vector3.movetoward但没有任何反应
using System.Collections.Generic;
using UnityEngine;
public class Guard : MonoBehaviour {
public Transform pathholder;
private Vector3 startposition;
private Vector3 previousposition;
private float waittime=1.5f;
private Vector3[] waypoints;
Vector3 playerinitialposition;
void Start () {
Vector3[] waypoints = new Vector3[pathholder.childCount];
for (int x = 0; x < pathholder.childCount; x++) {
waypoints [x] = pathholder.GetChild (x).position;
}
startposition = pathholder.GetChild (0).position;
previousposition = startposition;
playerinitialposition = new Vector3 (startposition.x, this.transform.position.y, startposition.z);
this.transform.position = playerinitialposition;
StartCoroutine(Followpath(waypoints));
}
void Update () {
}
void OnDrawGizmos(){
foreach (Transform waypoint in pathholder) {
Gizmos.DrawSphere (waypoint.transform.position,1f);
Gizmos.DrawLine (previousposition, waypoint.position);
previousposition = waypoint.position;
}
}
IEnumerator Followpath ( Vector3[] waypoints){
int lengthinindex = 1;
Vector3 targetdestination = waypoints[lengthinindex];
while (true) {
Vector3.MoveTowards (this.transform.position, targetdestination, 5f * Time.deltaTime);
if (this.transform.position == targetdestination) {
lengthinindex = (lengthinindex + 1) % waypoints.Length;
targetdestination = waypoints [lengthinindex];
yield return new WaitForSeconds (waittime);
}
}
yield return null;
}
}
答案 0 :(得分:1)
您需要将MoveTowards
返回的值指定给转换
transform.position = Vector3.MoveTowards (this.transform.position, targetdestination, 5f * Time.deltaTime);
您每次都使用MoveTowards
计算新位置,但从不将其分配到对象的实际位置。 MoveTowards Documentation.