一、动画状态机设置
死亡和受伤动画都是可以在AnyState过渡的,所以我们如图设置
死亡动画设置
AnyState——>Death过渡条件和其他设置:
参数我们设置一个Bool类型的isDeath,同时不设置退出时间,和把Can Transition to self给取消
注:Can Transition to self是指动画过渡自我,勾选会使对象一直循环播放动画,由于我们是死亡动画~,当然不希望一直播放死亡动画啦~
动画本身的LoopTime也要取消循环播放
从子状态退出到父状态的条件GroundState——>BaseState
受伤动画设置
同死亡设置差不多,我们可以采用Trigger类型来触发,方便他自己结束,同时附加一个条件,当isDeath = true时过渡到别的状态
到AirState和GroundState的过渡条件,我们可以根据之前的isGround来过渡
我们回到GroundState中,设置退出子状态的条件(AirState同理)
这样我们的动画设置就okk啦~
二、脚本实现
由于死亡和受伤会涉及到血量和伤害,我们需要设置相应的变量和碰撞检测(这个我们可以留到下篇在聊聊~)
血量脚本(挂载到PlayerGameObject上面):
public float currentHealth; // 当前血量
public float maxHealth; // 上限血量
// 受到伤害的方法
public void Hurt(float damage)
{
currentHealth -= damage;
if(currentHealth <= 0)
{
Debug.Log("you die!!");
animator.SetBool("isDeath",true); // 动画执行
}else
{
Debug.Log("you are hurting");
animator.SetBool("isDeath", false);
animator.SetTrigger("isHurt");
}
}
伤害脚本(挂载到Collider上面):
public float damage;
/// <summary>
/// 攻击碰撞的检测
/// </summary>
/// <param name="collision"></param>
private void OnTriggerEnter2D(Collider2D collision)
{
// 获取PlayerGameObject对象
Player player = collision.GetComponent<Player>();
if (player != null)
{
// 获取对象下面的HealthSystem组件
HealthSystem healthSystem = player.GetComponent<HealthSystem>();
if (healthSystem != null)
{
// 在这里使用 healthSystem 组件,调用Hurt伤害方法
healthSystem.Hurt(damage);
}
}
}
玩家脚本(挂载到PlayerGameObject上面):
HealthSystem healthSystem;
// Awake函数通常用于在游戏对象被激活之前进行初始化操作
// 我们可以在这个脚本生命周期函数中初始化一下初始值(比Start()早执行)
void Awake()
{
healthSystem = GetComponent<HealthSystem>();
healthSystem.currentHealth = health;
healthSystem.maxHealth = health;
}
void Update()
{
health = healthSystem.currentHealth;
}
好啦~基本的脚本就是这样啦(应该没有遗漏吧~)