Session17:消灭敌人的效果
制作老鹰
首先我们为游戏再添加一个敌人————老鹰,创建的方式和之前相同,这里只贴一下代码部分:
public class Enemy_Eagle : MonoBehaviour
{
private Rigidbody2D rb;
private Collider2D coll;
private Animator anim;
public Transform top, bottom;
public float speed;
private float topY, bottomY;
private bool moveUp = true;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
coll = GetComponent<Collider2D>();
anim = GetComponent<Animator>();
transform.DetachChildren();
topY = top.position.y;
bottomY = bottom.position.y;
Destroy(top.gameObject);
Destroy(bottom.gameObject);
}
// Update is called once per frame
void Update()
{
Movement();
}
void Movement()
{
if(moveUp)
{
rb.velocity = new Vector2(rb.velocity.x, speed);
if (transform.position.y > topY)
moveUp = false;
}
else
{
rb.velocity = new Vector2(rb.velocity.x, -speed);
if (transform.position.y < bottomY)
moveUp = true;
}
}
}
和青蛙不同的就是青蛙是左右跳,而老鹰是上下飞的。
敌人死亡效果
下面我们就来制作敌人被消灭的效果
首先依然是添加动画:
设置状态机过渡
这里要用到一个新的参数:trigger,一旦触发就执行death
然后写代码:
我们要在主角下落踩到敌人的时候触发death动画,也就是要在PlayerController里调用Enemy_Frog的函数,所以需要创建一个Enemy_Frog的实例:
private void OnCollisionEnter2D(Collision2D collision)
{
//碰到敌人时
if (collision.gameObject.tag == "Enemy")
{
//创建Frog实例
Enemy_Frog frog = collision.gameObject.GetComponent<Enemy_Frog>();
if (animator.GetBool("falling"))
{
//这里将原先销毁碰撞体改成了调用frog的函数
frog.JumpOn();
rb.velocity = new Vector2(rb.velocity.x, 5);
}
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);
}
}
}
然后在Enemy_Frog里加入函数
void Death()
{
Destroy(gameObject);
}
public void JumpOn()
{
animator.SetTrigger("death");
}
将Death()
设为death的event
当主角踩到frog时,先触发death的动画,然后再执行Death()
销毁物体。
这样可以完成单个敌人的死亡效果,但是每多一种敌人的类型,就要重新写了,其实我们可以创建一个Enemy的父类,让所有的敌人都继承它
public class Enemy : MonoBehaviour
{
//protected 子类和父类共享
protected Animator animator;
protected virtual void Start()
{
animator = GetComponent<Animator>();
}
void Death()
{
Destroy(gameObject);
}
public void JumpOn()
{
animator.SetTrigger("death");
}
}
然后在子类的Start中调用父类的Start
protected override void Start()
{
base.Start();
rb = GetComponent<Rigidbody2D>();
transform.DetachChildren();
topY = top.position.y;
bottomY = bottom.position.y;
Destroy(top.gameObject);
Destroy(bottom.gameObject);
}
PlayerController的代码也就改成了:
private void OnCollisionEnter2D(Collision2D collision)
{
//碰到敌人时
if (collision.gameObject.tag == "Enemy")
{
Enemy enemy = collision.gameObject.GetComponent<Enemy>();
if (animator.GetBool("falling"))
{
enemy.JumpOn();
rb.velocity = new Vector2(rb.velocity.x, 5);
}
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);
}
}
}