Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

1vdlrwnsv1 님의 블로그

유니티 체력바 만들기, 보스 만들기 본문

Unity

유니티 체력바 만들기, 보스 만들기

1vdlrwnsv1 2025. 2. 25. 14:05

일단 먼저 빈 체력 이미지를 만들자

다음은 체력이 꽉찬 상태의 이미지를 넣자

inspector 창에서 Image컴포넌트의 ImageType을 Filled, Fill Method를 Horizontal, Fill Amount 막대 조절을 통해 어떻게 줄어드는지 볼 수 있음

그리고 대충 체력창 가운데에 텍스트 하나 넣어두고 이제 스크립트를 짜보자

 

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

public class BossHealthBar : MonoBehaviour
{
    [SerializeField] private Image fillHealthBar;
    [SerializeField] private Text healthText;
    [SerializeField] private bool isShowHpNum = true; //체크시 체력 텍스트 표시
    [SerializeField] private bool isHealthAnim = true; //체크시 감소 애니메이션 출력

    private Boss _boss;
    private float currentFill;

    public float fullHealth = 200f;

    // Start is called before the first frame update
    void Start()
    {
        _boss = FindAnyObjectByType<Boss>();

        currentFill = 1f;
        UpdateHealthBar();

    }

    // Update is called once per frame
    void Update()
    {
        if(_boss == null) return;
        UpdateHealthBar();
    }
    private void UpdateHealthBar()
    {
        float healthPer = _boss.bossHp / fullHealth;
        if(isHealthAnim)
        {
            currentFill = Mathf.Lerp(currentFill, healthPer, Time.deltaTime * 5);//서서히 감소
        }else
        {
            currentFill = healthPer;
        }

        fillHealthBar.fillAmount = currentFill;
        healthText.text = $"{(int)_boss.bossHp} / {(int)fullHealth}";
        healthText.enabled = isShowHpNum;
    }
}

 

 

보스를 또 만들어보자 

보스가 공격할 때 잠깐 데미지 콜라이더가 켜지게 그 때마다 그 안에 있는 플레이어에게 데미지를 입힐것

원하는 위치에 데미지 영역을 만들고 애니메이션을 수정하여 원하는 프레임에 데미지 영역이 켜지고 꺼짐

 

이제 DamageArea스크립트를 만들어서 켜지고 꺼질때마다 이 영역 안에 있는 Player태그를 가진 오브젝트가 있다면 그 플레이어의 체력을 10 깎아보자

 

감지를 못해서 일단 플레이어 감지만 구현해보자

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DamageArea : MonoBehaviour
{
    public float damage = 10f; // 데미지 값
    public float checkRadius = 2f; // 검사할 반경 (씬에서 확인 가능)

    void OnEnable()
    {
        Debug.Log("DamageArea 활성화됨!");

        // 현재 DamageArea의 위치를 기준으로 반경 안에 있는 모든 콜라이더 검색
        Collider[] colliders = Physics.OverlapSphere(transform.position, checkRadius);

        foreach (Collider collider in colliders)
        {
            if (collider.CompareTag("Player"))
            {
                Debug.Log("DamageArea 활성화 시 플레이어가 영역 안에 있음!");

                PlayerMovement pm = collider.GetComponent<PlayerMovement>();
                if (pm != null)
                {
                    Debug.Log("플레이어의 체력 감소 전: " + pm.playerHp);
                    pm.TakeDamage(damage);
                    Debug.Log("플레이어의 체력 감소 후: " + pm.playerHp);
                }
                else
                {
                    Debug.LogError("PlayerMovement 컴포넌트를 찾을 수 없음!");
                }
                return; // 플레이어를 찾으면 더 이상 반복할 필요 없음
            }
        }

        Debug.Log("DamageArea 활성화 시 플레이어가 없음.");
    }

    // ✅ 기즈모(Gizmos)로 반경을 표시 (씬에서 시각적으로 확인 가능)
    void OnDrawGizmos()
    {
        Gizmos.color = Color.red; // 색상 설정 (빨간색)
        Gizmos.DrawWireSphere(transform.position, checkRadius); // 반경을 원으로 그리기
    }
}

감지를 못한다 내일 알아보자

'Unity' 카테고리의 다른 글

유니티 슬롯머신 개발 중 문제 & 보스 문제 수정  (0) 2025.02.28