Session23:优化代码Fix code
敌人死亡的bug
现在主角把敌人踩死之后其实还会进行碰撞检测,导致爆炸动画重复播放,我们要做的就是在敌人死亡后取消碰撞体
void Death()
{
//取消碰撞体必须写在Death里,如果提前取消的话受重力影响,会边爆炸边下落
GetComponent<Collider2D>().enabled = false;
Destroy(gameObject);
}
如果组件只需使用一次,可以使用这种方法来调用组件,而无需声明。
吃cherry的bug
现在有一个问题是,当角色的移动速度过快时,角色身上的两个collider会都碰到cherry,导致score一次性+2
我们可以为cherry添加动画和动画事件来解决这个问题
public class Cherry : MonoBehaviour
{
private void Death()
{
FindObjectOfType<PlayerController>().CherryCount();
Destroy(gameObject);
}
}
下面是PlayerController中的改动:
private void OnTriggerEnter2D(Collider2D collision)
{
//吃到樱桃
if (collision.tag == "Collection")
{
collectionAudio.Play();
collision.GetComponent<Animator>().Play("isGot");
}
//碰到DeadLine
if (collision.tag == "DeadLine")
{
GetComponent<AudioSource>().enabled = false;
//延时2s
Invoke("Restart", 2f);
}
}
public void CherryCount()
{
score++;
cherryNumber.text = score.ToString();
}
Cherry的isGot动画结束调用Death()
即可
![image-20211105194501940](https://i-blog.csdnimg.cn/blog_migrate/ec33cf4e81e3d1818595b4274107a265.png)