Unity 设置固定移动路线

说明:Cinemachine是Unity推出的摄像机管理官方解决方案,致力于帮助开发者高效的实现游戏中的相机系统。而Cinemachine中的CinemachineSmoothPath可以用来设计固定路线移动方案。

一、导入Cinemachine包
Unity 设置固定移动路线_第1张图片
可以导入Cinemachine的demo来学习一下
Unity 设置固定移动路线_第2张图片

二、添加移动轨道
Unity 设置固定移动路线_第3张图片
Unity 设置固定移动路线_第4张图片

三、简单的移动逻辑(cube沿设计的路线移动)

using Cinemachine;
using UnityEngine;
using static Cinemachine.CinemachineBrain;
using static Cinemachine.CinemachinePathBase;
using static Cinemachine.CinemachineSmoothPath;

public class CinemachineMove : MonoBehaviour
{
    public GameObject track;
    public Waypoint[] point;

    public CinemachineSmoothPath m_Path;
    public PositionUnits m_type = PositionUnits.Distance;
    public UpdateMethod m_method = UpdateMethod.SmartUpdate;
    public float m_Speed = 5;
    float m_Position = 0;
    
    void Start()
    {
        point = m_Path.m_Waypoints;
    }

    void FixedUpdate()
    {
        if (m_method == UpdateMethod.FixedUpdate)
            SetCartPosition(m_Position + m_Speed * Time.deltaTime);
    }

    void Update()
    {
        float speed = Application.isPlaying ? m_Speed : 0;
        if (m_method == UpdateMethod.SmartUpdate)
            SetCartPosition(m_Position + speed * Time.deltaTime);
    }

    void LateUpdate()
    {
        if (!Application.isPlaying)
            SetCartPosition(m_Position);
        else if (m_method == UpdateMethod.LateUpdate)
            SetCartPosition(m_Position + m_Speed * Time.deltaTime);
    }

    void SetCartPosition(float distanceAlongPath)
    {
        m_Position = m_Path.StandardizeUnit(distanceAlongPath, m_type);
        transform.position = m_Path.EvaluatePositionAtUnit(m_Position, m_type);
        transform.rotation = m_Path.EvaluateOrientationAtUnit(m_Position, m_type);
    }

    //float pos = 0;
    //void Update()
    //{
        //pos += Time.deltaTime;
        if(pos > path.PathLength)
        //{
            //transform.position = m_Path.EvaluatePosition(pos);
            //transform.localEulerAngles = m_Path.EvaluateTangent(pos);
        //}
    //}

    //float time = 0;
    //void Update()
    //{
        //time += Time.deltaTime;
        //if(time >= point.Length)
        //{
        //    time = 0;
        //}

        //int index = Mathf.FloorToInt(time);
        //transform.position = point[index].position;
    //}
}

你可能感兴趣的:(Unity,基础,unity,c#)