unity2D敌人在x轴和y轴移动追踪玩家不可斜角追踪自动躲避障碍物并且输出方向
时间: 2023-06-19 13:07:30 浏览: 45
首先,你需要一个能够移动的敌人和一个能够移动的玩家,以及一些障碍物。然后,你需要编写一些代码来让敌人追踪玩家并且自动躲避障碍物。
以下是一个简单的实现方法:
1. 创建一个敌人和一个玩家对象,并将它们放在场景中。
2. 在敌人对象上添加一个脚本来控制它的移动。这个脚本应该包含以下内容:
- 一个变量来存储玩家的位置。
- 一个变量来存储敌人的移动速度。
- 一个方法来更新敌人的位置,使其朝向玩家并且自动躲避障碍物。
3. 在玩家对象上添加一个脚本来控制它的移动。这个脚本应该包含以下内容:
- 一个变量来存储玩家的移动速度。
- 一个方法来更新玩家的位置,使其朝向玩家输入的方向。
4. 在场景中添加一些障碍物。这些障碍物应该有一个碰撞器组件,以便敌人可以检测到它们。
5. 在敌人的移动脚本中,使用 Physics2D.Raycast() 方法来检测敌人与障碍物之间是否有任何障碍物。如果有,敌人应该自动躲避障碍物,以避免与它们碰撞。
6. 在敌人的移动脚本中,使用 Vector2.MoveTowards() 方法来更新敌人的位置,使其朝向玩家并且自动躲避障碍物。
7. 在玩家的移动脚本中,使用 Input.GetAxisRaw() 方法来获取玩家输入的方向,并使用 Vector2.MoveTowards() 方法来更新玩家的位置,以便它朝向玩家输入的方向移动。
8. 在敌人的移动脚本中,使用 Vector2.Angle() 方法来计算敌人与玩家之间的角度,并检查其是否小于45度或大于315度。如果是,则敌人只能在x轴或y轴上移动。否则,敌人可以在斜角上移动。
9. 在敌人的移动脚本中,使用 Mathf.Sign() 方法来确定敌人应该朝哪个方向移动。如果敌人在x轴上,则应该使用玩家的x坐标来确定方向。如果敌人在y轴上,则应该使用玩家的y坐标来确定方向。
10. 在敌人的移动脚本中,使用 Debug.DrawLine() 方法来绘制一条线,以便你可以查看敌人与障碍物之间的距离和角度。
下面是一个示例代码来实现上述功能:
```csharp
using UnityEngine;
public class EnemyController : MonoBehaviour
{
public float speed = 5f;
public Transform player;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
Vector2 direction = player.position - transform.position;
float angle = Vector2.Angle(direction, Vector2.right);
if (angle < 45f || angle > 315f)
{
rb.velocity = new Vector2(Mathf.Sign(direction.x) * speed, 0f);
}
else if (angle > 135f && angle < 225f)
{
rb.velocity = new Vector2(0f, Mathf.Sign(direction.y) * speed);
}
else
{
if (Mathf.Abs(direction.x) > Mathf.Abs(direction.y))
{
rb.velocity = new Vector2(Mathf.Sign(direction.x) * speed, 0f);
}
else
{
rb.velocity = new Vector2(0f, Mathf.Sign(direction.y) * speed);
}
}
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, Mathf.Infinity);
if (hit.collider != null && hit.collider.CompareTag("Obstacle"))
{
Debug.DrawLine(transform.position, hit.point, Color.red);
Vector2 normal = hit.normal;
Vector2 steer = Vector2.Reflect(direction.normalized, normal).normalized;
rb.velocity = steer * speed;
}
else
{
Debug.DrawLine(transform.position, transform.position + direction.normalized * 3f, Color.green);
}
}
}
```
```csharp
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 5f;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
if (horizontal != 0f || vertical != 0f)
{
Vector2 direction = new Vector2(horizontal, vertical).normalized;
rb.velocity = direction * speed;
}
else
{
rb.velocity = Vector2.zero;
}
}
}
```
希望这可以帮助你开始实现你的游戏。