Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
ソシャゲによくある体力管理機能のサンプル
using UnityEngine;
using System;
using System.Collections;
public class ActionPointManager : MonoBehaviour {
// 1ActionPoint回復をするのに必要な時間
const int recoveryUnitSeconds = 180;
public int point { get; private set; }
public int maxPoint { get; private set; }
double restRecoveryTime;
DateTime lastRcoveryTime;
/// <summary>
/// 初期化処理
/// </summary>
/// <param name="point">現在のポイント</param>
/// <param name="maxPoint">最大のポイント</param>
/// <param name="lastRecoveryTime">最後に回復した時間</param>
public void Init(int point, int maxPoint, DateTime lastRecoveryTime){
this.point = point;
this.maxPoint = maxPoint;
this.lastRcoveryTime = lastRecoveryTime;
}
/// <summary>
/// APを使用する
/// </summary>
/// <returns>APの使用に成功したかどうか</returns>
/// <param name="usePoint">使用するポイント</param>
public bool UseActionPoint(int usePoint){
if (point <= usePoint) {
return false;
}
if (point >= maxPoint) {
lastRcoveryTime = DateTime.Now;
}
point -= usePoint;
return true;
}
/// <summary>
/// APを全回復する
/// </summary>
public void RecoveryAllPoint(){
point = maxPoint;
}
/// <summary>
/// 次に回復する時間までのカウントダウン用ラベルを返す
/// </summary>
/// <returns>カウントダウン(59分59秒まで対応)</returns>
public string GetRestRecoveryTimeLabel(){
if (point >= maxPoint) {
return "00:00";
}
var span = TimeSpan.FromSeconds (restRecoveryTime);
return string.Format("{0:00}:{1:00}", span.Minutes, span.Seconds);
}
/// <summary>
/// 全体のポイントに対しての現在のポイントの割合を返す
/// </summary>
/// <returns>割合(0 ~ 1.0)</returns>
public float ActionPointRatio(){
if (point >= maxPoint) {
return 1f;
}
if (point == 0) {
return 0f;
}
return (float)point / maxPoint;
}
/// <summary>
/// 毎フレームAPの更新を行う
/// </summary>
void Update(){
UpdateActionPointStatus ();
}
/// <summary>
/// APの更新処理を行う
/// </summary>
void UpdateActionPointStatus(){
if (point >= maxPoint) {
return;
}
var time = DateTime.Now;
var diff = time - lastRcoveryTime;
var totalSeconds = diff.TotalSeconds;
while ( totalSeconds > recoveryUnitSeconds ) {
if (point >= maxPoint) {
break;
}
totalSeconds -= recoveryUnitSeconds;
lastRcoveryTime = lastRcoveryTime.Add (TimeSpan.FromSeconds (recoveryUnitSeconds));
point++;
}
restRecoveryTime = recoveryUnitSeconds - totalSeconds;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment