# unity学习笔记—-游戏练习07

public int HP = 100;

public void LostHP(int attack)
{
HP -= attack;
if(HP＜= 0)
{
Destroy(gameObject);
}
}

Zombie中需要用到攻击力，时间间隔，计时器

//攻击力
public int AttackNumber = 30;
//时间间隔
private float AktDuration ;
//计时器
public float AktTimer = 2;

TakeDamage方法需要在zombie脚本中调用，当僵尸开始攻击时，调用当前被攻击对象身上的TakeDamage方法。

void EatUpdate()
{
AktTimer += Time.deltaTime;
if (AktTimer > AktDuration&&CurrentEatPlant !=null)
{
CurrentEatPlant.LostHP(AttackNumber);
AktTimer = 0;
}
}

private PlantManagr CurrentEatPlant;

CurrentEatPlant = collision.GetComponent<PlantManagr>();

public void TransitionEat()
{
zombieState = ZombieState.Eat;
AktTimer = 0;
}

1.僵尸的受伤处理

//血量
public int HP = 100;
public int currentHP;

currentHP = HP;

public void TakeDamage(int damage)
{
if (currentHP <= 0)
return;
this.currentHP -= damage;
if (currentHP <= 0)
{
currentHP = -1;
Died();
}
float HpPercent = currentHP * 1f / HP;
animator.SetFloat("HPPercent", HpPercent);

}

private void Died()
{
zombieState = ZombieState.Die;
GetComponent<Collider2D>().enabled = false;
Destroy(gameObject, 2);
}

2.然后为豌豆添加一个圆形碰撞器组件 Circle Collider 2D ，在BulletControl中去做检测。

public void SetAKTnumber(int AKTnumber)
{
this.AKTnumber = AKTnumber;
}

private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Zmobie")
{
Destroy(gameObject);
collision.GetComponent<ZombieControl>().TakeDamage(AKTnumber);
}
}

void Start()
{
Destroy(gameObject, 10);
}

3.在豌豆射手攻击时去设置他的攻击值

go.SetAKTnumber(AKTvalue);

public GameObject PeaBulletHitPrefab;

GameObject go= GameObject.Instantiate(PeaBulletHitPrefab, transform.position, Quaternion.identity);
Destroy(go, 1);

THE END