实现角色的踩到尖刺后被击飞(往后跳)并出现无敌模式(维持一段时间),同时生命值掉血(一共6滴血)
现在明确需求:
第一步,角色碰到尖刺后生命值会下降,当生命值为0时,角色消失;
第二部,设置UI界面,当碰到一次尖刺时,角色生命值减一;
第三步,角色碰到尖刺后身体变透明,出现无敌状态,无敌状态持续时间为半秒;
第四步,角色碰到尖刺后被击飞,同时出现击飞动画。
首先,放置尖刺作为陷阱,并且编写脚本DamgePlayer赋予给尖刺。
创建角色生命系统脚本命名为PlayerHealthController,声明公共变量玩家当前生命值currentHealth和完整生命值maxHealth,需要注意公共变量在unity的脚本面板中赋值。
public int currentHealth, maxHealth;
当前生命值为0,最大生命值为6。
当角色碰到尖刺后currentHealth减一,currentHealth为0时,角色消失。
public void DealDamage(){
currentHealth --;
// 当生命值为0时,玩家消失
if(currentHealth <= 0){
gameObject.SetActive(false);
}
}
SetActive就是unity的这个按钮
之后在DamgePlayer脚本中调用DealDamage函数,这里需要先在PlayerHealthController中声明静态变量,为了方便调用函数。
public static PlayerHealthController instance; // 声明静态变量
private void Awake()
{
instance = this;
}
在DamgePlayer脚本中编写函数,当角色碰到尖刺时触发函数(角色的tag必须为Player)。
void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Player"){
PlayerHealthController.instance.DealDamage();
}
}
到目前为止,DamgePlayer脚本编写完毕,以下为完整代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamgePlayer : MonoBehaviour
{
void Start()
{
}
void Update()
{
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Player"){
PlayerHealthController.instance.DealDamage();
}
}
}
角色生命系统,角色触碰到到尖刺6次后消失代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHealthController : MonoBehaviour
{
public static PlayerHealthController instance; // 声明静态变量
public int currentHealth, maxHealth; // 声明当前生命和最大生命
private void Awake()
{
instance = this;
}
void Start()
{
currentHealth = maxHealth;
}
void Update()
{
}
public void DealDamage()
{
currentHealth --;
// 当生命值为0时,玩家消失
if(currentHealth <= 0)
{
gameObject.SetActive(false);
}
}
}