Unityでダメージを受けたキャラのHPバーの作り方を紹介します!
1.先ずはUnity開いて、今回もは2Dオブジェクトで作成して名前はHealthBarにします。
2.開いたら、HierarchyでCanvasを追加してから空オブジェクトを作って、座標Resetして、名前はHealthBarにします、右クリックして、UI>imageをそのHealthBarの子供にして、名前はHealthにします。imageのSourceImageに素材5をアタッチして、ImageTypeはFilledで、FillMethodはHorizontalして、SetNativeSizeをクリック。
3.また、HealthBarの下でHealthと同じImageを作って、名前はBGにします。今回は素材4をSourceImageにアタッチしてから、直接SetNativeSizeをクリックしてください。
4.Healthをコピーして、名前はHealthFadeにします、Colorだけ不透明度を本来の半分にします。
5.GameManagerを作ります、座標Resetして、二つのコードをアタッチします。図のように:
画面をクリックすれば以下のような効果ができます!
コード以下:
HealthBarCTRL
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthBarCTRL : MonoBehaviour
{
public Image health_image;
public Image health_fade;
private void Update()
{
health_image.fillAmount = HealthPointCTRL.health_point / 100f;
health_fade.fillAmount = HealthPointCTRL.fade_health_point / 100f;
}
}
HealthPointCTRL
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthPointCTRL : MonoBehaviour
{
public static float health_point, fade_health_point;
float fade_Timer = 0;
public float fade_Time=1f;
Coroutine damage_Coroutine = null;
private void Awake()
{
health_point = 100f;
fade_health_point = 100f;
}
private void Update()
{
if(Input.GetMouseButtonDown(0))
{
fade_Timer = 0;
Damage_Once(10);
}
else if(Input.GetMouseButtonDown(1))
{
if(damage_Coroutine!=null)
{
StopCoroutine(damage_Coroutine);
damage_Coroutine = StartCoroutine(Damage_Over_Time(5, 2));
}
else
{
damage_Coroutine = StartCoroutine(Damage_Over_Time(5, 2));
}
fade_Timer += Time.deltaTime;
if(fade_health_point>health_point&&fade_Timer>fade_Time)
{
fade_health_point = Mathf.Lerp(fade_health_point, health_point, Time.deltaTime * 2);
}
}
}
public void Damage_Once(float damage)
{
health_point -= damage;
}
public IEnumerator Damage_Over_Time(float damage, float duration)
{
float timer = 0;
while(health_point>=0&&timer<=duration)
{
health_point -= damage * Time.deltaTime;
timer += Time.deltaTime;
yield return null;
}
}
}
ビリビリ動画から運んできました。自分のものではありません。もし権利侵害したら、連絡してください、削除します。