본문 바로가기
개발/C#

유니티 C# 바라보는 방향 상호작용 간단 구현 Raycast 충돌 감지

by SPNK 2023. 12. 18.
반응형
  • 코드 구현
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float raycastDistance = 3f; //인식할 수 있는 범위

    RaycastHit hit;
    Ray ray;

    void Update()
    {
        Debug.DrawLine(ray.origin, ray.origin + ray.direction * raycastDistance, Color.red); //씬에서 내가 보고있는 방향을 표시

        ray = new Ray(transform.position, transform.forward); //보고있는 방향으로 살펴보기

        //ray = Camera.main.ScreenPointToRay(Input.mousePosition); //마우스로 살펴보기

        if (Input.GetKeyDown(KeyCode.E)) //키보드 E를 눌렀을 때
        {
            if (Physics.Raycast(ray, out hit, raycastDistance)) //인식할 수 있는 범위 안에서 물체 확인
            {
                GameObject hitObject = hit.collider.gameObject; //주변 물체의 정보를 가져옵니다.

                if (hitObject != null) //물체가 있을 경우
                {
                    UIManager.instance.ShowCanvasText(hitObject.tag);
                }
            }
        }
    }
}

 

  • UI 처리
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class UIManager : MonoBehaviour
{
    public static UIManager instance;

    public GameObject Background;
    public TMP_Text CanvasText;


    private void Awake()
    {
        instance = this;

        Background.SetActive(false);
        CanvasText.text = "";
    }

    public void ShowCanvasText(string str) //캔버스에 정보를 표시합니다
    {
        Background.SetActive(true); //흰색 바탕을 켭니다

        if (str == "Chair")
        {
            CanvasText.text = "의자입니다";
        }
        else if(str == "Window")
        {
            CanvasText.text = "창문입니다";
        }
        else if (str == "Desk")
        {
            CanvasText.text = "책상입니다";
        }
        else
        {
            CanvasText.text = "태그가 설정되지 않았습니다.";
        }

        Invoke("DisableBackground", 1.0f); //1초 뒤에 흰색 바탕을 끕니다
    }

    void DisableBackground()
    {
        Background.SetActive(false);
    }
}
반응형

댓글