#3 에임위에 있는 오브젝트 이름 출력 [Raycast] (6/6)
게임 진행식 타워 선택 및 기타 기능을 구현하기위해
에임 위에 있는 오브젝트 이름을 출력하는 것을 만들어 보겠습니다.
먼저 canvas에 에임 모양을 추가해 줍시다.
scripts폴더에 Ray 스크립트를 만들고
아래 코드를 작성합니다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ray : MonoBehaviour
{
private RaycastHit hit;
void Start()
{
}
void Update()
{
Raycast();
}
void Raycast()
{
if (Physics.Raycast(this.transform.position, transform.forward, out hit))
{
Debug.Log("hit point : " + hit.point + ", distance : " + hit.distance + ", name : " + hit.collider.name);
Debug.DrawRay(this.transform.position, transform.forward * 1000f, Color.red);
}
else {
Debug.DrawRay(this.transform.position, transform.forward * 1000f, Color.red);
}
}
}
먼저 변수 hit을 생성,
if문에서 ray를 현재 카메라의 좌표(시점의 중앙)에서 transform.forward 앞으로 쏘았을때 맞으면
콘솔창에 위치, 거리 오브젝트 이름을 출력합니다.
그리고 씬 창에서 잘 되나 확인하기위해 레이를 쏴 줍니다.
영상
다음번에는 적이동을 구현하겠습니다.