我需要沿着路径旋转汽车,但代码无法正常工作。它像烟花一样移动。我猜问题在于从 z 轴移动到 x 轴。我没有足够的知识来解决这个问题。救命!
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public Transform StartPoint;
public Transform[] EndPoints;
public Transform[] AngleWaypoints;
public float MoveSpeed;
private Transform TargetPoint;
//private Transform EndPoint;
private float DistanceToPoint = 0f;
private int RandomValue;
private Transform[] Waypoints;
private int wpIndex = 0;
private Quaternion lookRotation;
private Vector3 direction;
// Use this for initialization
void Start ()
{
RandomValue = Random.Range (1, EndPoints.Length);
int count = 0;
switch (RandomValue) {
case 0:
//Waypoints = StartPoint + EndPoints [RandomValue];
count = 2;
Waypoints = new Transform[count];
Waypoints [0] = StartPoint;
Waypoints [1] = EndPoints[RandomValue];
break;
case 1:
//Waypoints = StartPoint + AngleWaypoints + EndPoints[RandomValue];
count = 2 + AngleWaypoints.Length;
Waypoints = new Transform[count];
Waypoints [0] = StartPoint;
for(int i=0;i<AngleWaypoints.Length;i++){
Waypoints [i + 1] = AngleWaypoints [i];
}
Waypoints [count-1] = EndPoints[RandomValue];
break;
}
TargetPoint = Waypoints [wpIndex];
}
// Update is called once per frame
void Update ()
{
DistanceToPoint = Vector3.Distance (transform.position, TargetPoint.position);
if (DistanceToPoint > 1) {
direction = (TargetPoint.position - transform.position)/2 + transform.position;
Vector3 dir = TargetPoint.position - transform.position;
lookRotation = Quaternion.LookRotation(dir);
transform.rotation = Quaternion.Slerp (transform.rotation, lookRotation, Time.deltaTime);
Vector3 v = direction / DistanceToPoint * MoveSpeed * Time.deltaTime;
transform.Translate (v);
} else {
wpIndex++;
if (wpIndex > Waypoints.Length - 1) {
wpIndex = 0;
Destroy(this.gameObject);
}
TargetPoint = Waypoints[wpIndex];
}
}
}
我前段时间使用过这个代码并且它有效
void Update () {
if (this.isMoving){
if(Vector3.Distance(walkDestination, transform.position) > 0.2f){
float step = 0f;
step = this.speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, walkDestination, step);
Vector3 rotationDestination = this.rotateDestination;
Quaternion targetRotation = Quaternion.LookRotation(rotationDestination - transform.position, Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 6.0f);
}else{
//Arrived to destination
}
}
}