플레이어(Player)를 이동시켜 적(enemy)과 부딪혔을 때, 가로 혹은 세로로 된 체력바(HealthBar)가 점점 감소하는 방법을 알아봅니다. UI의 Image 옵션인 Image Type, Fill Method, Fill Origin, Fill Amount등을 이용하여 가로 및 세로 체력바를 만들어 봅니다. 유니티 2D게임 개발(Unity & C#)
#체력바만들기구현 #HealthBar #FillAmount
[HealthGauge.cs]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthGauge : MonoBehaviour
{
Image healthBar;
float maxHealth = 100f;
public static float health;
// Start is called before the first frame update
void Start()
{
healthBar = GetComponent<Image>();
health = maxHealth;
}
// Update is called once per frame
void Update()
{
healthBar.fillAmount = health / maxHealth;
}
}
[PlayerMove.cs]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
float moveX, moveY;
public float speed = 5.0f;
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
moveX = Input.GetAxis("Horizontal");
moveY = Input.GetAxis("Vertical");
rb.velocity = new Vector2(moveX * speed, moveY * speed);
}
}
[Enemy.cs]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D collision)
{
HealthGauge.health -= 10f;
}
}
댓글