Interaction

2025. 3. 5. 23:37·Game Engine/Unity
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;

public class Interaction : MonoBehaviour
{
    public float checkRate = 0.05f;
    private float lastCheckTime;
    public float maxCheckDistance;
    public LayerMask layerMask;

    public GameObject curInteractGameObject;
    private IInteractable curInteractable;

    public TextMeshProUGUI promptText;
    private Camera camera;

    void Start()
    {
        camera = Camera.main;
    }

    // Update is called once per frame
    void Update()
    {
        if(Time.time - lastCheckTime > checkRate)
        {
            lastCheckTime = Time.time;

            Ray ray = camera.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2));
            RaycastHit hit;

            if(Physics.Raycast(ray, out hit, maxCheckDistance, layerMask))
            {
                if(hit.collider.gameObject != curInteractGameObject)
                {
                    curInteractGameObject = hit.collider.gameObject;
                    curInteractable = hit.collider.GetComponent<IInteractable>();
                    SetPromptText();
                }
            }
            else
            {
                curInteractGameObject = null;
                curInteractable = null;
                promptText.gameObject.SetActive(false);
            }
        }
    }

    private void SetPromptText()
    {
        promptText.gameObject.SetActive(true);
        promptText.text = curInteractable.GetInteractPrompt();
    }

    public void OnInteractInput(InputAction.CallbackContext context)
    {
        if(context.phase == InputActionPhase.Started && curInteractable != null)
        {
            curInteractable.OnInteract();
            curInteractGameObject = null;
            curInteractable = null;
            promptText.gameObject.SetActive(false);
        }
    }
}

'Game Engine > Unity' 카테고리의 다른 글

[Unity] 카메라 전환하는 코드  (0) 2025.03.10
방어코드 생성  (0) 2025.03.06
[Unity] Tutorial code  (0) 2025.02.26
코루틴 사용법  (0) 2025.02.25
[Unity] 2D 무한 맵 생성  (0) 2025.02.24
'Game Engine/Unity' 카테고리의 다른 글
  • [Unity] 카메라 전환하는 코드
  • 방어코드 생성
  • [Unity] Tutorial code
  • 코루틴 사용법
Xenawn
Xenawn
제넌 게임개발 블로그
  • Xenawn
    Xenawn
    Xenawn
  • 전체
    오늘
    어제
    • 분류 전체보기 (77)
      • Language (24)
        • C++ (4)
        • C# (20)
      • Game Engine (32)
        • Unity (19)
        • Unity API (1)
        • Game Project (12)
      • Git (2)
      • Algorithm (9)
        • BOJ [C++] (8)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    카메라 움직임
    프레임
    스파르타내일배움캠프 #스파르타내일배움캠프til
    C++
    POTION
    객체
    Unity
    배열
    BOJ
    블랙잭
    클래스
    CPP
    1181
    프로퍼티
    게임개발
    headbob
    내일배움캠프
    리스트
    걸음fps
    string format
    문자열 보간
    FizzBuzz
    유니티
    FPS
    백준
    포션
    fps cam
    알고리즘
    c#
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Xenawn
Interaction
상단으로

티스토리툴바