Related Posts Plugin for WordPress, Blogger...

3-11 Regenerating Energy Over Time

今天要來介紹一個小功能,讓Energy隨著時間慢慢回復。本章直接貼上程式碼,只要在Energy.cs的Update中加個條件式判斷,並再增加兩行程式碼即可完成功能。


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using RPG.CameraUI;

namespace RPG.Character{
 public class Energy : MonoBehaviour {

  [SerializeField] RawImage energyBarRawImage;
  [SerializeField] float maxEnergyPoints = 100f;
  [SerializeField] float regenPointPerSecond = 1f;

  float currentEnergyPoints;

  void Start () {
   currentEnergyPoints = maxEnergyPoints;
  }

  void Update(){
   if (currentEnergyPoints < maxEnergyPoints) {
    AddEnergyPoint ();
    UpdateEnergyBar ();
   }
  }

  private void AddEnergyPoint(){
   // 每秒自動恢復能量,由於Update是每個Frame都會執行,故須使用deltaTime取得Frame的間隔時間
   float pointsToAdd = regenPointPerSecond * Time.deltaTime;
   currentEnergyPoints = Mathf.Clamp (currentEnergyPoints + pointsToAdd, 0, maxEnergyPoints);
  }

  public bool IsEnergyAvailable(float amount){
   return amount <= currentEnergyPoints;
  }

  // 消耗的魔力由SpecialAbilityConfig決定,傳到amount
  public void ConsumeEnergy(float amount){
   float newEnergyPoint = currentEnergyPoints - amount;
   currentEnergyPoints = Mathf.Clamp (newEnergyPoint, 0, maxEnergyPoints);
   UpdateEnergyBar ();
  }

  void UpdateEnergyBar(){
   float xValue = -(EnergyAsPersent() / 2f) - 0.5f;
   energyBarRawImage.uvRect = new Rect(xValue, 0f, 0.5f, 1f);
  }

  float EnergyAsPersent(){
   return currentEnergyPoints / maxEnergyPoints;
  }
 }
}

留言