【ダークソウル風ゲームを作りたい(Unity)。その10】
今回はHP表示とダメージを受けた場合の処理を実装します。
・追加したスクリプト
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace SG { public class HealthBar : MonoBehaviour //+EP9 { public Slider slider; private void Start() { slider = GetComponent<Slider>(); } public void SetMaxHealth(int maxHealth) { slider.maxValue = maxHealth; slider.value = maxHealth; } public void SetCurrentHealh(int currentHealth) { slider.value = currentHealth; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace SG { public class PlayerStats : MonoBehaviour //+EP9 { public int healthLevel = 10; public int maxHealth; public int currentHealth; public HealthBar healthBar; AnimatorHandler animatorHandler; private void Awake() { animatorHandler = GetComponentInChildren<AnimatorHandler>(); } void Start() { maxHealth = setMaxHealthFromHealthLevel(); currentHealth = maxHealth; healthBar.SetMaxHealth(maxHealth); } int setMaxHealthFromHealthLevel() { maxHealth = healthLevel * 10; return maxHealth; } public void TakeDamage(int damage) { if (currentHealth > 0) { currentHealth = currentHealth - damage; healthBar.SetCurrentHealh(currentHealth); animatorHandler.PlayTargetAnimation("Damage01", true); } if (currentHealth <= 0) { currentHealth = 0; animatorHandler.PlayTargetAnimation("Dead01", true); //HANDLE PLAYER DEATH } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace SG { public class DamagePlayer : MonoBehaviour //+EP9 { public int damage = 25; private void OnTriggerEnter(Collider other) { PlayerStats playerStats = other.GetComponent<PlayerStats>(); //タッチしたのがプレイヤーの場合、ダメージを与える if (playerStats != null) { playerStats.TakeDamage(damage); } } } }