unity自带寻路系统实现击退效果(Nav Mesh Agent)
示例代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class demoAI : MonoBehaviour
{
private NavMeshAgent gam;
public bool isMove;
private float backDistanceIndex;
private float backDistance;//持续长度
private float backSpeed;//步长
// Start is called before the first frame update
void Start()
{
gam = GetComponent<NavMeshAgent>();
}
//backDistances:持续长度,backSpeeds:每次步长
public void back(float backDistances, float backSpeeds)
{
backDistance = backDistances;
backSpeed = backSpeeds;
isMove = true;//开始后退
}
// Update is called once per frame
void Update()
{
if (isMove)
{
if (backDistanceIndex < backDistance)
{
backDistanceIndex += backSpeed;
Vector3 a = transform.forward.normalized * -backSpeed;
gam.Move(a);
//移动中
}
else
{
isMove = false;
backDistanceIndex = 0;
//停止后退,初始化状态
}
}
}
}
调用示例
back(1,0.01f);