Unity UI-버튼-애니메이션, Play씬에서 HpBar 생성
2023. 8. 25.

Transition-Animation>AutoGenerateAnimation으로 애니메이션 생성

Animation-Animation창을 열어 버튼을 선택한 후 Highlighted 탭을 선택한다.녹화버튼 눌러서 애니메이션 만들기

버튼 위로 (Roll Over)시 살짝 커지는 애니메이션

네비게이션은 버튼이 여러 개일 경우 키보드로 포커스를 어떻게 이동시킬 것인가에 대한 속성이다.

 

TextMeshPro에서 FontAsset을 넣고싶으면 window-textmeshpro-font asset creator를 선택해 생성해준다.

폰트 에셋을 집어넣고 확인해 보았다.

Play 씬에서 Hp게이지를 생성해보았다.

캔버스에 HpBar를 위한 새 이미지 추가. 태그를 Hp_bar로.

코드수정

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour
{
    public Vector3 cameraPosition;

    private Vector3 moveDir;
    private Vector3 aPosition;
    private Animation anim;

    //delegate 선언
    public delegate void PlayerDieHandler();//타입 정의
    //event
    public static event PlayerDieHandler OnPlayerDie;//대리자 타입의 변수 정의
    
    [SerializeField]private float moveSpeed = 1f;
    [SerializeField] private float turnSpeed =80f;
    //data----------------------------------------------
    private readonly float initHp = 100.0f;//초기 생명값
    public float currHp;//현재 체력

    private Image hpBar;//Hpbar를 연결할 변수

    IEnumerator Start()
    {
        this.hpBar = GameObject.FindGameObjectWithTag("Hp_bar")?.GetComponent<Image>();//hp 초기화

        this.currHp = this.initHp;//체력 초기화
        this.DisplayHealth();
        this.anim = GetComponent<Animation>();
        anim.Play("Idle");//시작 시 Idle

        this.turnSpeed = 0.0f;
        yield return new WaitForSeconds(0.3f);
        this.turnSpeed = 80.0f;
    }
    private void Update()
    {
      
        //키보드 이동
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        float r = Input.GetAxis("Mouse X");//마우스를 왼쪽으로 움직이면 음수, 오른쪽 양수 반환
        moveDir = (Vector3.forward * v) + Vector3.right * h;
        this.transform.Translate(moveDir.normalized * this.moveSpeed * Time.deltaTime);//이동
        //   Debug.LogFormat("{0} , {1}", moveDir, moveDir.normalized);
        //  DrawArrow.ForDebug(this.transform.position, moveDir, 5f, Color.red);
        Vector3 angle = Vector3.up * turnSpeed * Time.deltaTime * r;
       // Vector3 angle2 = Vector3.up * turnSpeed * r;//Time.deltaTime을 빼보았다.
      //  Debug.LogFormat("angle2:{0},r:{1}",angle2,r );
        this.transform.Rotate(angle);//Vector3.up을 축으로 회전
        PlayAnim(h,v);

        
    }
    
    private void OnDrawGizmos()
    {
        DrawArrow.ForGizmo(this.transform.position, this.transform.forward , Color.red);
        Gizmos.color = Color.white;
        GizmosExtensions.DrawWireArc(this.transform.position, this.transform.forward, 360, 1);
        DrawArrow.ForGizmo(this.transform.position, -this.transform.forward * 3, Color.yellow);
        this.aPosition = this.transform.position + (-this.transform.forward * 3);//a지점의 위치
        DrawArrow.ForGizmo(this.aPosition, Vector3.up * 2, Color.green);//카메라의 위치를 의미한다.
        this.cameraPosition = this.aPosition+ (Vector3.up*2);
    }
    private void PlayAnim(float h,float v)//키보드 입력값을 기준으로 애니메이션 play
    {
        if (v >= 0.1f)//x축 : 전,후
        {
            anim.CrossFade("RunF", 0.25f);//전진
        }
        else if (v <= -0.1f)
        {
            anim.CrossFade("RunB", 0.25f);//후진
        }
        else if (h >= 0.1f)//z축 : 좌, 우
        {
            anim.CrossFade("RunR", 0.25f);
        }
        else if (h <= -0.1f)
        {
            anim.CrossFade("RunL", 0.25f);
        }
        else
        {
            anim.CrossFade("Idle", 0.25f);//정지 시 Idle
        }
    }

    private void OnTriggerEnter(Collider coll)
    {
        if(this.currHp >= 0.0f && coll.CompareTag("Punch"))
        {
                Debug.Log(coll.tag);
                this.currHp -= 10.0f;
                this.DisplayHealth();
            
            if(this.currHp < 0.0f)
            {
                PlayerDie();
            }
        }

    }
    private void PlayerDie()
    {
        Debug.Log("Player Die!!");
        //GameObject[] arrMonstersGo = GameObject.FindGameObjectsWithTag("Monster");
        ////monster 태그를 가진 모든 게임 오브젝트를 찾아옴
        //foreach(GameObject monster in arrMonstersGo)
        //{
        //    monster.SendMessage("OnPlayerDie",SendMessageOptions.DontRequireReceiver);
        //}
        OnPlayerDie();//Player 사망 이벤트 발생(Notification)- 대리자 호출
    }

    private void DisplayHealth()
    {
        this.hpBar.fillAmount = this.currHp / this.initHp;
    }
}
myoskin