아래 코드 적용하면 왼쪽 게임화면 클릭시 오른쪽에 클릭한 위치로 카메라부터 시작되는 선이 그려짐.
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
Ray ray;
void Update()
{
if(Input.GetMouseButtonDown(0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
}
Debug.DrawRay(ray.origin, ray.direction * 100);
}
}
- 다른 방법
Ray를 직접 생성하는 대신, Unity의 Physics.Raycast를 사용하여 레이를 발사하고 그 결과를 처리할 수 있습니다.
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.Log("Hit: " + hit.collider.name);
// 여기에 피격된 물체에 대한 추가 로직 작성 가능
}
}
}
카메라나 다른 오브젝트의 Transform 방향을 기준으로 레이를 발사하는 방법입니다.
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 direction = transform.forward; // 오브젝트가 향하는 방향
Ray ray = new Ray(transform.position, direction);
Debug.DrawRay(ray.origin, ray.direction * 100, Color.red);
}
}
만약 화면상의 특정 지점이나 특정 오브젝트를 향해 레이를 쏘고 싶다면, 직접 그 목적지를 지정할 수도 있습니다.
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 destination = new Vector3(0, 0, 10); // 특정 위치
Ray ray = new Ray(transform.position, destination - transform.position);
Debug.DrawRay(ray.origin, ray.direction * 100, Color.blue);
}
}
유니티 캐릭터 내비게이션 이동 및 공격 기본 세팅 (0) | 2024.09.19 |
---|---|
유니티 마우스 클릭 위치로 캐릭터 이동하기, 카메라가 캐릭터 따라다니기 (1) | 2024.09.18 |
유니티 적 몬스터 이동, 공격, 사망 설정하기 (1) | 2024.09.16 |
유니티 아이템,총알 습득하기 (0) | 2024.09.16 |
유니티 List, 오류 및 해결 (1) | 2024.09.16 |