【Unity】关于Waypoint的寻路

创建一个名为Path的C#脚本
<span style="font-size:24px;"><span style="font-size:24px;">using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Enemy : MonoBehaviour {

    public float MoveSpeed = 3.0f;  //行走速度
    private  Vector3 Target;  //目标位置
    private float rotateSpeed = 5.0f; //旋转的速度

    public Path path; //Path脚本
    private List<Vector3> waypoints;   //列表存储waypoints
    void Awake()
    {
        waypoints = new List<Vector3>(); //定义一个waypoint
        for (int i = 0; i < path.WayPotins.Length; i++) //将Path路径的WayPoints全部数组元素存储到waypoints的列表里
        {
            waypoints.Add(path.WayPotins[i].position);
        
        }
        GetNextPoint();


    }

    void GetNextPoint()  //更新下一个waypoint
    {
        if (waypoints.Count > 0)  //如果当前waypoints里的个数大于0的情况下
        {
            Target = waypoints[0];  //Target就为waypoints的第一个元素
            waypoints.RemoveAt(0); //到达目的地后就把当前waypoint列表的第一个元素给删除掉
            //以达到更新Target位置的目的
            print("路点为:"+waypoints.Count);
        }
    }
	//Use this for initialization
	void Start() 
	{
	
	}
	
	//Update is called one per frame
	void Update() 
	{
        bool reached = MoveToPoint(Target);
        if (reached)
        {
            GetNextPoint();
        }
	}

    bool MoveToPoint(Vector3 point)  //定义一个布尔类型的移动到目标点的函数
    {
        float distance = Vector3.Distance(this.transform.position,point);
        if (distance < 0.15f) //如果当前位置与目标位子小于0.15的话,就返回true
        {
            return true;
        }

        //设置当前目标的旋转为目标减去当前位置的方向
        Quaternion wantedRot = Quaternion.LookRotation(point-this.transform.position);
        //this.transform.rotation = wantedRot;
        //控制旋转的插值运算
        this.transform.rotation = Quaternion.Slerp(this.transform.rotation, wantedRot, rotateSpeed * Time.deltaTime);


        //移动方向为单位向量
        Vector3 dir = (point - this.transform.position).normalized;
        this.transform.Translate(dir * MoveSpeed * Time.deltaTime, Space.World);
        return false;//不然就默认返回false
    }
}</span></span>



  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值