Unity2D 敌人二阶段状态转换动画及代码详解
Unity2D 敌人二阶段状态转换动画及代码详解
假设我们有一个敌人,它有两个状态:'普通状态' 和 '愤怒状态'。在 '普通状态' 下,敌人会缓慢移动并发射子弹。在 '愤怒状态' 下,敌人会快速移动并发射更多的子弹。
一、创建动画状态机
首先,我们需要创建两个动画状态机:一个用于 '普通状态',一个用于 '愤怒状态'。在每个状态机中,我们需要添加一个过渡状态,以便在敌人的状态发生变化时进行平滑的过渡。
二、触发状态转换
在 '普通状态' 下,我们可以添加一个触发器,当玩家的距离小于一定距离时,触发状态转换到 '愤怒状态'。在 '愤怒状态' 下,我们可以添加一个计时器,当过了一定时间后,触发状态转换回 '普通状态'。
三、示例代码
public class Enemy : MonoBehaviour
{
public float normalSpeed = 2f;
public float angrySpeed = 4f;
public float bulletSpeed = 5f;
public float bulletDelay = 1f;
public float angryTime = 5f;
public float angryDistance = 10f;
private bool isAngry = false;
private float bulletTimer = 0f;
private Animator animator;
private Rigidbody2D rb;
private void Start()
{
animator = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
if (isAngry)
{
rb.velocity = transform.right * angrySpeed;
bulletTimer += Time.deltaTime;
if (bulletTimer >= bulletDelay)
{
Shoot();
bulletTimer = 0f;
}
}
else
{
rb.velocity = transform.right * normalSpeed;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player") && !isAngry)
{
animator.SetTrigger("Angry");
isAngry = true;
bulletTimer = 0f;
Invoke("SetNormal", angryTime);
}
}
private void SetNormal()
{
animator.SetTrigger("Normal");
isAngry = false;
}
private void Shoot()
{
// 发射子弹的代码
}
}
在上述代码中,我们使用了 Animator 组件来控制敌人的状态转换。在 Update 函数中,我们根据当前状态来设置敌人的速度和子弹发射频率。在 OnTriggerEnter2D 函数中,我们使用触发器来检测玩家是否在 '愤怒状态' 下进入敌人的范围内,并触发状态转换。在 SetNormal 函数中,我们使用 Invoke 函数来延迟一定时间后触发状态转换回 '普通状态'。
四、总结
希望这个例子能够帮助你设计敌人的状态转换动画和代码。通过合理的设计,你可以创建出更具挑战性和趣味性的敌人,提升游戏体验。
原文地址: https://www.cveoy.top/t/topic/jrLq 著作权归作者所有。请勿转载和采集!