Unity2D 角色生命系统及UI控制脚本编写之一(学习自用)

实现角色的踩到尖刺后被击飞(往后跳)并出现无敌模式(维持一段时间),同时生命值掉血(一共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);
            }

    }
}

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值