项目02《游戏-12-开发》Unity3D
基于 项目02《游戏-11-开发》Unity3D ,
任务:实现场景怪物自动巡航 ,
首先在场景中创建小球命名为路径点WayPoint0,
取消小球的碰撞器Collider,
再复制两个改名为WayPoint1 和 WayPoint2 ,
在WayPoint0路径点0右键创建空父物体命名为PathA路径A,
将其他路径点0-2(3个路径点)拖拽至PathA作为子物体,
创建脚本WayPoint.cs:
双击脚本WayPoint.cs修改代码:
using UnityEngine;
public class Waypoint : MonoBehaviour{
public Transform[] waypointArray;
public float speed = 0.1f;
public int currentIndex = 0;
void Start(){
Transform path = GameObject.Find("PathA").transform;
if (path != null){
waypointArray = new Transform[path.childCount];
for (int i = 0; i < waypointArray.Length; i++)
waypointArray[i] = path.GetChild(i);
}
else
Debug.LogError("查找路径点父物体失败,仔细检查父物体名字");
}
void Update(){
Vector3 direction = waypointArray[currentIndex].position - transform.position;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), 1f);
transform.Translate(Vector3.forward * speed);
if (direction.sqrMagnitude < 1f){
currentIndex++;
if (currentIndex > waypointArray.Length - 1)
currentIndex = 0;
}
}
}
将导航脚本挂载在敌人怪物上,并添加三个路径点框选。将PathA路径的三个路径点拖拽进框选注意路径顺序,
最后将路径点的材质取消,关闭路径点的场景显示,
运行即可实现怪物自动导航自动了,
End.