반응형
SMALL
UI slider 제작 연습을하던중 이전에 배웠던 캐릭터의 좌표와 UI(Canvas) 상의 좌표간의 동기화 작업을 연습할겸 간단하게 구조는 잡지 않고 만들어보았다.
우선 메인카메라 한대(Screen Space - Overlay) 일 경우 RectTransformUtility.WorldToScreenPoint 메서드를 이용하여 월드 좌표를 스크린 좌표로 변경하여 적용하였고 캐릭터가 이동하여도 그대로 따라올수 있도록 메스드를 작성하고 추가로 spcae바를 누르면 데미지가 들어와 실시간으로 캐릭터의 hp 바와 hp숫자에 동기화 될수 있도록 해보았다.
단순 구현을 위해 구조를 잡지 않고 하나의 스크립트에 하려니 오히려 마음에 들지 않는 시기가 온듯하다 ㅎㅎ;;
다음엔 좀더 채계적인 구조로 만드는걸 연습해야겠다.
코드
using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class UIHealthBarTest : MonoBehaviour
{
public GameObject enenmy;
public GameObject hpBar;
private Slider hpBarSlider;
private TMP_Text hpBarText;
private Vector3 EPos;
private float speed = 10.0f;
void Start()
{
this.enenmy = Instantiate(this.enenmy);
this.hpBar = Instantiate(this.hpBar, this.transform);
this.hpBarSlider = hpBar.transform.GetComponentInChildren<Slider>();
this.hpBarText = hpBar.transform.GetComponentInChildren<TMP_Text>();
Transform hpPoint = enenmy.transform.GetChild(0).GetComponent<Transform>();
Vector2 hpPointlocation = RectTransformUtility.WorldToScreenPoint(Camera.main, hpPoint.position);
hpBar.transform.position = hpPointlocation;
}
private void Update()
{
float dir = Input.GetAxisRaw("Horizontal");
float dir2 = Input.GetAxisRaw("Vertical");
this.EPos = new Vector3(dir, dir2, 0);
this.enenmy.transform.Translate(EPos * speed * Time.deltaTime);
this.UpdateHpBarPos();
//Debug.Log(this.hpBarSlider);
if (Input.GetKeyDown(KeyCode.Space)) { this.Attack(10); }
}
public void UpdateHpBarPos()
{
Transform hpPoint = enenmy.transform.GetChild(0).GetComponent<Transform>();
Vector2 hpPointlocation = RectTransformUtility.WorldToScreenPoint(Camera.main, hpPoint.position);
hpBar.transform.position = hpPointlocation;
}
public void Attack(float damage)
{
this.hpBarSlider.value -= damage;
this.hpBarText.text = (Convert.ToInt32(this.hpBarText.text) - damage).ToString();
}
}반응형
LIST
'유니티 엔진 클라이언트 > 개인공부' 카테고리의 다른 글
| [유니티] VrCity 오브젝트 위치로 이동 & VR City 마무리 (1) | 2023.02.24 |
|---|---|
| [유니티] VRCity 3D virtual 팝업 & 코루틴이용 & RayCast & 비트연산자 & Quaternion.Lerp사용 캐릭터 회전 (0) | 2023.02.23 |
| [유니티] 미션 데이터 직렬화 복습 (0) | 2023.02.15 |
| [유니티] UI 스크롤 기능 구현 및 변하지 않는데이터 직렬화 역직렬화 (0) | 2023.02.13 |
| [유니티] 종스크롤 2D 슈터 제작 (2) | 2023.02.10 |