欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

unity3D创建路径点,进行物体移动(塔防游戏)

程序员文章站 2022-03-31 21:07:53
...

public class way_point : MonoBehaviour {

//定义一个静态位置数组
public static Transform[] positions;

void Awake()
{
    positions = new Transform[transform.childCount];

    for (int i = 0; i < positions.Length; i++)
    {
        positions[i] = transform.GetChild(i);

    }
}

}

public class enemy_move : MonoBehaviour {

public int movespeed = 5;
public Transform[] positions;
private int index = 0;

void Start () {
    positions = way_point.positions;
}

// Update is called once per frame
void Update () {
    Move();
}
void Move()
{
    if (index > positions.Length - 1)
    {
        return;
    }

    //将得到的方向化为单位1
    transform.Translate((positions[index].position - transform.position).normalized * Time.deltaTime * movespeed);

    if (Vector3.Distance(positions[index].position,transform.position) < 0.2f)
    {
        index++;
    }
}

}