[유니티] 체력표시 Health Bar

안녕하세요 UnityBeginner입니다.
이번에는 캐릭터의 체력을 표시는 간단한 방법중 하나를 소개하겠습니다.


씬뷰



키 값을 입력받아 캐릭터를 이동하며 좌측땅은 체력이 차는 힐존,
우측땅은 체력이 소모되는 포이즌존으로 구성했습니다.



하이어라키 하위계층구조



플레이어 오브젝트 안에 Canvas UI Image로 체력바를 구성하였습니다.

각각의 오브젝트에 대해 설명드리면

HealthBar : 빈 오브젝트

Board : 체력바의 테두리가 되는 검정이미지 입니다.
Background : 체력이 소모되었을대의 바탕색인 빨간이미지입니다.
BarSprite : 현재 남아있는 체력을 표시하는 초록색 이미지입니다.
※ Image Type을 Filled로 변경하고 Fill Method를 Horizontal로 변경합니다.

HealZone : 체력이 회복되는 지형입니다.
PoisonGround : 체력이 소모되는 지형입니다.

위와 같이 오브젝트를 구성하고 이미지 컴포넌트의Fill Amount 크기를 
제어하면 체력이 회복되거나 소모되는 시각적인 표현을 구사할 수 있습니다.


스크립트


 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    public float health = 100;
    public float speed;
    public Image barSprite;
    
    void Update()
    {
        PlayerMovement();        
    }

    // 충돌체를 검사gkrh tag명으로 분기처리
    private void OnTriggerStay(Collider col) {
        if (col.tag == "Heal") {
            HealZone(1f);
        } else if (col.tag == "Poison") {
            PoisonZone(1f);
        }
    }
    
    // 체력 회복
    public void HealZone(float heal) {
        if(health < 100) {
            health += heal;
            barSprite.fillAmount = health / 100f;
        }
    }

    // 체력소모
    public void PoisonZone(float damage) {
        if (health > 0) {
            health -= damage;
            barSprite.fillAmount = health / 100f;
        }
    }

    // 캐릭터 이동
    public void PlayerMovement() {

        if (Input.GetKey(KeyCode.W)) {
            transform.position += Vector3.forward * Time.deltaTime * speed;
        }

        if (Input.GetKey(KeyCode.S)) {
            transform.position += Vector3.back * Time.deltaTime * speed;
        }

        if (Input.GetKey(KeyCode.A)) {
            transform.position += Vector3.left * Time.deltaTime * speed;
        }

        if (Input.GetKey(KeyCode.D)) {
            transform.position += Vector3.right * Time.deltaTime * speed;
        }
    }

플레이어 오브젝트가 HealZone으로 진입한 경우 
fillAmount양을 1에 가깝게 증가시키며 PoisonZone으로 진입한 경우
fillAmount양을 0에 가깝게 감소시켜 시각적으로 체력변화를 표현합니다.

결과화면


댓글