using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WayPoints : MonoBehaviour
{
//此脚本挂在waypoints
public static Transform[] positions;/获取所有位置点的transform组件,组成一个数组
private void Awake()
{
positions = new Transform[transform.childCount];//创建数组
for(int i = 0; i < positions.Length; i++)//初始化数组
{
positions[i] = transform.GetChild(i);
}
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
此脚本挂在移动的物体身上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enermy : MonoBehaviour
{
private Transform[] positions;//Transform[] 存放位置点transform
public float speed=10;//初始化移动的速度为10
private int index = 0;//定义数组下标
// Start is called before the first frame update
void Start()
{
positions = WayPoints.positions;//拿到设置的位置点
}
// Update is called once per frame
void Update()
{
Move();
}
void Move()
{
if (index > positions.Length - 1) return;//当跑到最后一个点的时候报数组越界异常
transform.Translate((positions[index].position - transform.position).normalized * Time.deltaTime * speed);//朝位置点移动
//认为物体的位置和位置点的位置的距离小于0.2的时候,到达位置点,让index++
if (Vector3.Distance(positions[index].position,transform.position)<0.2)
{
index++;
}
}
}