当前位置:   article > 正文

【Unity】关于Waypoint的寻路_unity waypoint寻路

unity waypoint寻路

创建一个名为Path的C#脚本
  1. <span style="font-size:24px;"><span style="font-size:24px;">using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. public class Enemy : MonoBehaviour {
  5. public float MoveSpeed = 3.0f; //行走速度
  6. private Vector3 Target; //目标位置
  7. private float rotateSpeed = 5.0f; //旋转的速度
  8. public Path path; //Path脚本
  9. private List<Vector3> waypoints; //列表存储waypoints
  10. void Awake()
  11. {
  12. waypoints = new List<Vector3>(); //定义一个waypoint
  13. for (int i = 0; i < path.WayPotins.Length; i++) //将Path路径的WayPoints全部数组元素存储到waypoints的列表里
  14. {
  15. waypoints.Add(path.WayPotins[i].position);
  16. }
  17. GetNextPoint();
  18. }
  19. void GetNextPoint() //更新下一个waypoint
  20. {
  21. if (waypoints.Count > 0) //如果当前waypoints里的个数大于0的情况下
  22. {
  23. Target = waypoints[0]; //Target就为waypoints的第一个元素
  24. waypoints.RemoveAt(0); //到达目的地后就把当前waypoint列表的第一个元素给删除掉
  25. //以达到更新Target位置的目的
  26. print("路点为:"+waypoints.Count);
  27. }
  28. }
  29. //Use this for initialization
  30. void Start()
  31. {
  32. }
  33. //Update is called one per frame
  34. void Update()
  35. {
  36. bool reached = MoveToPoint(Target);
  37. if (reached)
  38. {
  39. GetNextPoint();
  40. }
  41. }
  42. bool MoveToPoint(Vector3 point) //定义一个布尔类型的移动到目标点的函数
  43. {
  44. float distance = Vector3.Distance(this.transform.position,point);
  45. if (distance < 0.15f) //如果当前位置与目标位子小于0.15的话,就返回true
  46. {
  47. return true;
  48. }
  49. //设置当前目标的旋转为目标减去当前位置的方向
  50. Quaternion wantedRot = Quaternion.LookRotation(point-this.transform.position);
  51. //this.transform.rotation = wantedRot;
  52. //控制旋转的插值运算
  53. this.transform.rotation = Quaternion.Slerp(this.transform.rotation, wantedRot, rotateSpeed * Time.deltaTime);
  54. //移动方向为单位向量
  55. Vector3 dir = (point - this.transform.position).normalized;
  56. this.transform.Translate(dir * MoveSpeed * Time.deltaTime, Space.World);
  57. return false;//不然就默认返回false
  58. }
  59. }</span></span>



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/462939?site
推荐阅读
相关标签
  

闽ICP备14008679号