已经设置完角色的ui界面后,要对角色设置进入无敌模式。
在PlayerHealthController脚本种设置变量
public float invincibleLenght; // 声明玩家无敌时间变量
private float invincibleCounter; // 声明玩家无敌计数器
在脚本种设置变量为1。
当角色触碰到尖刺时,无敌时间开始从1慢慢变到0
void Update(){
if(invincibleCounter > 0){
invincibleCounter -= Time.deltaTime;
}
}
编写函数,把无敌长度赋予给计时器,当计时器小于0时,如果角色的生命值减一,那么角色的无敌计时器等于1。
public void DealDamage(){
currentHealth --;
// 当生命值为0时,玩家消失
if(currentHealth <= 0){
gameObject.SetActive(false);
}
else{
invincibleCounter = invincibleLenght;
}
}
再设置一个限定条件,如果无敌计时器不等于0的时候,那么角色的生命值不会减一。这里设置if语句。
public void DealDamage(){
if(invincibleCounter <= 0)
{
currentHealth --;
// 当生命值为0时,玩家消失
if(currentHealth <= 0){
gameObject.SetActive(false);
}
else{
invincibleCounter = invincibleLenght;
}
}
}
之后给角色颜色设置透明度。
theSR.color = new Color(theSR.color.r, theSR.color.g, theSR.color.b, 0.5f);
首先设置变量
private SpriteRenderer theSR; // 声明玩家渲染变量
这是一个私有变量,所以在脚本先对变量获取
void Start()
{
currentHealth = maxHealth;
theSR = GetComponent<SpriteRenderer>();
}
在update中,如果角色的无敌计时器小于0,那么角色一定是不透明的。
void Update()
{
if(invincibleCounter > 0){
invincibleCounter -= Time.deltaTime;
if(invincibleCounter <= 0){
theSR.color = new Color(theSR.color.r, theSR.color.g, theSR.color.b, 1f);
}
}
}
之后调用ui界面
UIController.instance.UpdateHealthDisplay();
完整代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHealthController : MonoBehaviour
{
public static PlayerHealthController instance; // 声明静态变量
public int currentHealth, maxHealth; // 声明当前生命和最大生命
public float invincibleLenght; // 声明玩家无敌时间变量
private float invincibleCounter; // 声明玩家无敌计数器
private SpriteRenderer theSR; // 声明玩家渲染变量
private void Awake()
{
instance = this;
}
void Start()
{
currentHealth = maxHealth;
theSR = GetComponent<SpriteRenderer>();
}
void Update()
{
if(invincibleCounter > 0){
invincibleCounter -= Time.deltaTime;
if(invincibleCounter <= 0){
theSR.color = new Color(theSR.color.r, theSR.color.g, theSR.color.b, 1f);
}
}
}
public void DealDamage(){
if(invincibleCounter <= 0)
{
currentHealth --;
// 当生命值为0时,玩家消失
if(currentHealth <= 0){
gameObject.SetActive(false);
}
else{
invincibleCounter = invincibleLenght;
theSR.color = new Color(theSR.color.r, theSR.color.g, theSR.color.b, 0.5f);
}
// 调用静态变量函数
UIController.instance.UpdateHealthDisplay();
}
}
}