请写一个基于A*寻路的自定义BehaviorDesigner action, 这个action可以让NPC追赶目标,但是不会撞上障碍物,而是会自行规避。命名为Seek2D NPC是个2D俯视角四方向人物,有上下左右四个方向。现在NPC身上挂了一个animation controller 叫做Man ,Man 是一个包含了四方向行走动画的混合器,由bool参数IsMoving控制切换,由InputX和InputY控制方向,现在要求以移动中控制切换动画,并使动画方向正确.
时间: 2023-04-10 12:02:57 浏览: 70
以下是基于A*寻路的自定义BehaviorDesigner action的代码:
using UnityEngine;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;
using System.Collections.Generic;
public class Seek2D : Action
{
public SharedGameObject target;
public float speed = 5f;
public float stoppingDistance = 1f;
public LayerMask obstacleMask;
private Animator animator;
private Vector2 direction;
private bool isMoving;
public override void OnStart()
{
animator = GetComponent<Animator>();
isMoving = false;
}
public override TaskStatus OnUpdate()
{
if (target.Value == null)
{
return TaskStatus.Failure;
}
Vector2 targetPosition = target.Value.transform.position;
Vector2 currentPosition = transform.position;
List<Node> path = AStar.FindPath(currentPosition, targetPosition, obstacleMask);
if (path != null && path.Count > 0)
{
Node nextNode = path[0];
if (Vector2.Distance(currentPosition, nextNode.position) > stoppingDistance)
{
direction = (nextNode.position - currentPosition).normalized;
transform.Translate(direction * speed * Time.deltaTime, Space.World);
if (!isMoving)
{
isMoving = true;
animator.SetBool("IsMoving", true);
}
if (direction.x > 0)
{
animator.SetFloat("InputX", 1f);
animator.SetFloat("InputY", 0f);
}
else if (direction.x < 0)
{
animator.SetFloat("InputX", -1f);
animator.SetFloat("InputY", 0f);
}
else if (direction.y > 0)
{
animator.SetFloat("InputX", 0f);
animator.SetFloat("InputY", 1f);
}
else if (direction.y < 0)
{
animator.SetFloat("InputX", 0f);
animator.SetFloat("InputY", -1f);
}
}
else
{
if (isMoving)
{
isMoving = false;
animator.SetBool("IsMoving", false);
}
}
return TaskStatus.Running;
}
else
{
if (isMoving)
{
isMoving = false;
animator.SetBool("IsMoving", false);
}
return TaskStatus.Failure;
}
}
}
该代码实现了一个基于A*寻路的自定义BehaviorDesigner action,可以让NPC追赶目标,但是不会撞上障碍物,而是会自行规避。该action命名为Seek2D,NPC是个2D俯视角四方向人物,有上下左右四个方向。现在NPC身上挂了一个animation controller叫做Man,Man是一个包含了四方向行走动画的混合器,由bool参数IsMoving控制切换,由InputX和InputY控制方向,现在要求以移动中控制切换动画,并使动画方向正确。