0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

タワーデフェンスゲーム Unity 敵の機能 8/10 aボタンを押すとHPバーが減少するように実装

Last updated at Posted at 2023-04-25

概要

前回の続きです。

今回はaボタンを押すと敵のHPが減少する処理を実装します。
以下gifアニメはキーボードのaボタンを二回押したときの様子です。

HeatlhReduce.gif

次へ

開発環境

IDE:Rider
Unity:2020.3.42(LTS)
OS:Windows10

UnityEditor上の設定

HPバー

EnemyHealthContainerスクリプトをアタッチします。

image.png

実装のポイント

新規にEnemyHealthContainerクラスを作成します。
役割としては、HPバーのImageオブジェクトをEnemyObjectにアタッチされているEnemyHealthクラスに渡すことです。

EnemyHealthクラスはaボタンを押した時にHPが減る処理を追加します。
UI的にはImage.fillAmountを使ってHPの減少を表現しています。

コード部分

EnemyHealthContainer.cs
using UnityEngine;
using UnityEngine.UI;


public class EnemyHealthContainer : MonoBehaviour
{
    [SerializeField] private Image fillAmountImage;
    public Image FillAmountImage => fillAmountImage;
    

}



EnemyHealth.cs
using System.Collections;
using System.Collections.Generic;
+ using System.ComponentModel;
using UnityEngine;
+ using UnityEngine.UI;

public class EnemyHealth : MonoBehaviour
{
    // Start is called before the first frame update
    [SerializeField] private GameObject healthBarPrefab;
    [SerializeField] private Transform barPosition;

    [SerializeField] private float initialHealth = 10f;
    [SerializeField] private float maxHealth = 10f;

+    public float CurrentHealth { get; set; }
+    private Image _healthBar;
    void Start()
    {
        CreateHealthBar();
+        CurrentHealth = initialHealth;
    }

+    private void Update()
+    {
+        if (Input.GetKeyDown(KeyCode.A))
+        {
+            DealDamage(5f);
+       }
+
+        _healthBar.fillAmount = Mathf.Lerp(_healthBar.fillAmount, CurrentHealth / maxHealth, Time.deltaTime * 10f);
+    }

    private void CreateHealthBar()
    {
        GameObject newBar = Instantiate(healthBarPrefab,barPosition.position,Quaternion.identity);
        newBar.transform.SetParent(transform);
        
+        EnemyHealthContainer container = newBar.GetComponent<EnemyHealthContainer>();
+        _healthBar = container.FillAmountImage;
    }

+    public void DealDamage(float damageReceived)
+    {
+        CurrentHealth -= damageReceived;
+    }
}



参考

fillAmount

image.png

ラムダ式

image.png

Section4 16

github コミット分

章まとめ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?