Session14:受伤效果Hurt
首先为人物添加一个hurt动画,然后添加过渡条件:
新增一个hurting参数,用于判断受伤状态
写代码:
//切换动画效果
void SwitchAnimation()
{
//正在跳跃
if (animator.GetBool("jumping"))
{
Debug.Log(rb.velocity.y);
//y轴速度消失,开始下落
if(rb.velocity.y <= 0)
{
animator.SetBool("jumping", false);
animator.SetBool("falling", true);
}
}else if (isHurt)
{
animator.SetBool("hurting", true);
if (Mathf.Abs(rb.velocity.x) < 0.2f)
{
animator.SetBool("hurting", false);
isHurt = false;
}
}
else if (coll.IsTouchingLayers(ground))
{
animator.SetBool("falling", false);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
//碰到敌人时
if (collision.gameObject.tag == "Enemy")
{
if (animator.GetBool("falling"))
{
Destroy(collision.gameObject);
}
else if(transform.position.x < collision.gameObject.transform.position.x)
{
isHurt = true;
rb.velocity = new Vector2(-10, rb.velocity.y);
}
else if(transform.position.x > collision.gameObject.transform.position.x)
{
isHurt = true;
rb.velocity = new Vector2(10, rb.velocity.y);
}
}
}
这样写了之后可能发现碰到敌人后人物并不会被弹开,这是因为movement在一直在执行,所以需要更改Movement的作用条件
void Update()
{
if(!isHurt)
{
Movement();
}
SwitchAnimation();
}
isHurt是一个bool类型的变量,默认值为false,只有isHurt为false时人物才可以移动,当碰到敌人时,isHurt变为true,人物无法移动。