unity2D敌人在x轴和y轴移动追踪玩家不可斜角追踪自动躲避障碍物并且输出方向
时间: 2023-06-19 21:07:46 浏览: 40
可以使用Unity中的NavMesh Agent组件来实现敌人自动躲避障碍物,并且只能沿着x轴和y轴移动追踪玩家的功能。
首先,为敌人添加NavMesh Agent组件。然后,创建一个NavMesh,将敌人的移动区域限制在NavMesh范围内。接下来,使用NavMesh Agent的SetDestination()方法来设置敌人的目标位置为玩家的位置。
为了只能沿着x轴和y轴移动,可以在敌人的移动方向上保持一个轴的速度为0。例如,如果敌人正在向右移动,那么在y轴上保持速度为0。
为了实现自动躲避障碍物功能,可以使用NavMesh Agent的Obstacle Avoidance(避障)属性,设置为High(高),这将使敌人自动躲避NavMesh上的障碍物。
最后,可以使用Vector3.Angle()方法来计算敌人当前的移动方向,并将其输出方向。
示例代码如下:
```csharp
using UnityEngine;
using UnityEngine.AI;
public class EnemyController : MonoBehaviour
{
public Transform player;
public float speed = 5f;
public float ySpeed = 0f;
private NavMeshAgent agent;
private Vector3 targetPos;
void Start()
{
agent = GetComponent<NavMeshAgent>();
agent.obstacleAvoidanceType = ObstacleAvoidanceType.High;
}
void Update()
{
targetPos = new Vector3(player.position.x, transform.position.y, player.position.z);
agent.SetDestination(targetPos);
Vector3 moveDir = agent.velocity.normalized;
moveDir.y = ySpeed;
transform.position += moveDir * speed * Time.deltaTime;
if (moveDir.magnitude > 0)
{
float angle = Mathf.Atan2(moveDir.z, moveDir.x) * Mathf.Rad2Deg;
Debug.Log("Move direction: " + angle);
}
}
}
```