24.02.29 TIL - Unity : 버튼 입력 동안 UI 게이지 충전 구현

JJwoo·2024년 3월 1일

Input Action, rigid body 기반 이동 사용

전체코드

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

public class Player : MonoBehaviour
{
    private Vector2 moveDirection;
    [SerializeField] private float moveForce = 10f;
    private SpriteRenderer spriteRenderer;
    private Rigidbody2D rb;
    
    
    [SerializeField] private Slider interactionSlider; // 상호작용 슬라이더 참조
    private bool isInteracting; // 상호작용 중인지 여부를 추적하는 플래그
    private Coroutine interactionCoroutine; // 상호작용 코루틴 참조

    void Start()
    {
        spriteRenderer = GetComponentInChildren<SpriteRenderer>();
        rb = GetComponent<Rigidbody2D>();
        interactionSlider.gameObject.SetActive(false); // 슬라이더 off
    }

    void FixedUpdate()
    {
        MoveCharacter(moveDirection);
    }

    private void MoveCharacter(Vector2 direction)
    {
        rb.AddForce(direction * moveForce);

        if (direction.x > 0)
        {
            spriteRenderer.flipX = false;
        }
        else if (direction.x < 0)
        {
            spriteRenderer.flipX = true;
        }
    }

    public void OnMove(InputAction.CallbackContext context)
    {
        moveDirection = context.ReadValue<Vector2>();
    }

    public void OnInteraction(InputAction.CallbackContext context) 
    // OnInteraction에 해당 되는 키를 누르면 게이지 충전 로직이 작동
    {
        if (context.started)
        {
            interactionSlider.gameObject.SetActive(true);
            interactionCoroutine = StartCoroutine(FillSliderOverTime(2.0f)); // 코루틴 시작
        }
        else if (context.canceled)
        {
            interactionSlider.gameObject.SetActive(false);
            if (interactionCoroutine != null)
            {
                StopCoroutine(interactionCoroutine); // 코루틴 중지
            }
            interactionSlider.value = 0; // 슬라이더 값 초기화
        }
    }

    private IEnumerator FillSliderOverTime(float duration)
    {
        float time = 0;
        while (time < duration)
        {
            time += Time.deltaTime;
            interactionSlider.value = time / duration;
            yield return null;
        }
        Debug.Log("충전 완료, 아이템 획득 이미지, 인벤토리 획득 로직 구현 예정");
        interactionSlider.gameObject.SetActive(false);  // 충전 완료시 슬라이더 숨김
		interactionSlider.value = 0; // 슬라이더 값 초기화
    }
}
  • context.started는 버튼 입력이 시작될 때 true가 되며, context.canceled는 버튼 입력이 끝날 때 true가 됨.

  • 버튼이 눌릴 때 Coroutine을 시작하여 슬라이더를 채우고, 버튼에서 손을 떼면 Coroutine을 중지하고 슬라이더를 false

  • FillSliderOverTime 코루틴은 주어진 시간(초) 동안 슬라이더의 value를 0에서 1까지(최대값) 채우며, 꽉 차면 설정한 디버그 로그를 출력한다.

  • 충전 완료 시 키를 떼지 않으면 슬라이더(게이지)가 사라지지 않기에,
    충전이 완료 될 때 슬라이더를 숨기고, 슬라이더 값을 초기화 해주었다.

profile
개발 모코코

0개의 댓글