漫游—》按照自设的路径进行漫游

using UnityEngine;

using System.Collections;

using System.Collections.Generic;

public class Roam : MonoBehaviour
{

public Transform wayRoot;
public GameObject camRoot;
public List<Vector3> wayPoints = new List<Vector3>();
MoveMode mm = MoveMode.move;
int wayIndex=0;
float rotProgress = 0;
public float rotateSpeed = 2f;
Quaternion qTarget;
Quaternion lastQ;//相机
public float moveSpeed = 2.2f;
bool isNeedContrlRotation = false;

void Awake()
{
  InitWayPoints();
  camRoot.transform.position = wayPoints[0];
  CaculateRoteData(0);
  camRoot.transform.localEulerAngles = new Vector3(0, -Quaternion.Angle(lastQ, qTarget), 0);
}

void Update()
{

  if (wayPoints.Count < 2)
  Debug.LogError("漫游的路径点数设置小于2");
  switch (mm)
  {
  case MoveMode.rotate://先转到下一个点
  if (isNeedContrlRotation)
  {
    camRoot.transform.rotation = Quaternion.Lerp(lastQ, qTarget, rotProgress);
    rotProgress += Time.deltaTime * rotateSpeed;
    if (rotProgress >= 1)
    {
      mm = MoveMode.move;//转完了,开始移动
    }
  }
  break;
  case MoveMode.move://开始移动
  float nextPointDist = 0;
  if (wayIndex < wayPoints.Count - 1)//没有到最后一个点
  {
    nextPointDist = Vector3.Distance(camRoot.transform.position, wayPoints[wayIndex + 1]);
    Vector3 dir = (wayPoints[wayIndex + 1] - wayPoints[wayIndex]).normalized;
    camRoot.transform.position += Time.deltaTime * dir * moveSpeed;
  }

  if (wayIndex == wayPoints.Count - 1)
  {
    nextPointDist = Vector3.Distance(camRoot.transform.position, wayPoints[0]);
    Vector3 dir = (wayPoints[0] - wayPoints[wayIndex]).normalized;
    camRoot.transform.position += Time.deltaTime * dir * moveSpeed;
  }

  if (nextPointDist < 0.1f)//换到下一个点
  {
    mm = MoveMode.rotate;
    isNeedContrlRotation = true;
    rotProgress = 0;
    wayIndex++;
    if (wayIndex >= wayPoints.Count)
    {
      wayIndex = 0;
      camRoot.transform.position = wayPoints[0];
    }
    CaculateRoteData(wayIndex);
  }
  break;
  }
}

void CaculateRoteData(int index)
{
  lastQ = camRoot.transform.rotation;
  Vector3 dir = Vector3.zero;
  if (index == wayPoints.Count - 1)
  {
    dir = wayPoints[0] - wayPoints[index];
  }
  else
  {
    dir = wayPoints[index + 1] - wayPoints[index];
  }
  qTarget = Quaternion.LookRotation(dir);
}

void InitWayPoints()
{
  if (wayRoot != null && wayRoot.childCount > 0)
  {
    for (int i = 0; i < wayRoot.childCount; i++)
    {
      wayPoints.Add(wayRoot.GetChild(i).position);
    }
  }
}

public enum MoveMode
{
  move,
  rotate
}

void OnDrawGizmos()
{
  if (wayRoot != null && wayRoot.childCount > 0)
  {
  int c = wayRoot.childCount;
  for (int i = 0; i < c - 1; i++)
  {
  Debug.DrawLine(wayRoot.GetChild(i).position, wayRoot.GetChild(i + 1).position, Color.green);
  }
  Debug.DrawLine(wayRoot.GetChild(wayRoot.childCount - 1).position, wayRoot.GetChild(0).position, Color.green);
}
}
}

原文地址:https://www.cnblogs.com/Study088/p/7161419.html