Unity实现敌人固定路线寻路

一:编辑动画状态机

例如一个敌人有上下左右移动的动画,则需要编辑四种方向的动画并制作动画控制机
Unity实现敌人固定路线寻路_第1张图片
并设置状态机的参数(这里是两个float类型变量h与v)
Unity实现敌人固定路线寻路_第2张图片

 

二:编辑路径点

手动添加模拟的路径点,敌人依次遍历这些路径点去移动

 

三:编写敌人移动的方法

加载路径点,依次添加到路径点集合中(添加自身位置到第一个点和最后一个点,使其可以循环移动)
Unity实现敌人固定路线寻路_第3张图片

 

遍历路径点,依次朝下一个路径点移动并且设置状态机的数值。
Unity实现敌人固定路线寻路_第4张图片

若要实现多个敌人一开始的路线不同,则需要在一个管理类中随机生成一个路径下标数组,在敌人脚本中随机得到usingIndex列表中的数值
Unity实现敌人固定路线寻路_第5张图片

 

——————————完整代码

using UnityEngine;
using System.Collections.Generic;

public class Enemy : MonoBehaviour
{
    public float speed;//速度

    public GameObject[] ways;//路径
    private List wayPoints;//所有路径点
    private int index;//下标点

    private Vector3 startPos;//起始点

    private Rigidbody2D rigi;//刚体组件
    private Animator ani;//动画机组件

    private void Start()
    {
        ani = GetComponent();
        rigi = GetComponent();

        startPos = transform.position;

        //开始时加载一个路径点
        LoadPath(ways[Random.Range(0, 2)]);
    }

    private void FixedUpdate()
    {
        Move();
    }

    //移动
    private void Move()
    {
        if (transform.position != wayPoints[index])
        {
            Vector2 des = Vector2.MoveTowards(transform.position, wayPoints[index], speed * Time.deltaTime);
            rigi.MovePosition(des);
        }
        else
        {
            index = (index + 1) % wayPoints.Count;
        }

        //播放动画
        PlayAni();
    }

    //播放动画
    private void PlayAni()
    {
        Vector2 dir = wayPoints[index] - transform.position;
        ani.SetFloat("h", dir.x);
        ani.SetFloat("v", dir.y);
    }

    //加载路线
    private void LoadPath(GameObject go)
    {
        if (wayPoints == null)
        {
            wayPoints = new List();
        }

        wayPoints.Clear();
        foreach (Transform t in go.transform)
        {
            wayPoints.Add(t.position);
        }
        wayPoints.Insert(0, startPos);
        wayPoints.Add(startPos);
    }
}

 

你可能感兴趣的:(Unity开发实战)