Raycasting은 광선을 쏴서 충돌 여부와 충돌 정보를 확인하는 기능입니다. 광선이 충돌하면 충돌 지점과 객체에 대한 정보를 반환하며, 이를 활용해 다양한 게임 로직을 구현할 수 있습니다.
광선 발사:
Physics.Raycast를 사용하면 특정 범위 내에서 충돌한 객체를 감지할 수 있습니다.bool 값으로 반환되며, 충돌한 객체의 정보는 RaycastHit 구조체에 저장됩니다.충돌 정보:
Raycast) 또는 모든 충돌 객체 배열(RaycastAll)로 얻을 수 있습니다.Debug.DrawRay:
Vector3 look = transform.TransformDirection(Vector3.forward); // 로컬 Forward를 월드 Forward로 변환
RaycastHit hit;
if (Physics.Raycast(transform.position + Vector3.up, look, out hit, 10))
{
Debug.Log($"Raycast 충돌 @ {hit.collider.gameObject.name}!");
}
코드 분석:
1. TransformDirection 함수:
Physics.Raycast 인자:
transform.position + Vector3.up).Vector3.up을 더한 이유: 객체의 Pivot(기준점)이 발에 위치했기 때문에, 광선을 약간 위에서 발사하기 위해.look).RaycastHit 변수.10).RaycastHit 구조체:
Debug.Log:
Vector3 look = transform.TransformDirection(Vector3.forward);
RaycastHit[] hits = Physics.RaycastAll(transform.position + Vector3.up, look, 10);
foreach (RaycastHit hit in hits)
{
Debug.Log($"Raycast 충돌 @ {hit.collider.gameObject.name}!");
}
코드 분석:
1. Physics.RaycastAll 함수:
RaycastHit 배열입니다.foreach 루프:
적용 사례:
if (Input.GetMouseButtonDown(0)) // 마우스 좌클릭
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // 클릭한 위치를 기준으로 Ray 생성
Debug.DrawRay(Camera.main.transform.position, ray.direction * 100.0f, Color.red, 1.0f); // Ray 시각화
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100.0f))
{
Debug.Log($"Raycast Camera 충돌 @ {hit.collider.gameObject.name}!");
}
}
코드 분석:
1. Input.GetMouseButtonDown(0):
ScreenPointToRay:
Debug.DrawRay:
Physics.Raycast:
int mask = (1 << 8) | (1 << 9); // 8번, 9번 레이어만 선택
if (Physics.Raycast(ray, out hit, 100.0f, mask))
{
Debug.Log($"Raycast Camera 충돌 @ {hit.collider.gameObject.name}!");
}
코드 분석:
1. (1 << 8):
00000001 → 00010000.| (OR) 연산:
mask를 Physics.Raycast에 전달:
레이어 마스크 사용:
LayerMask를 활용하여 불필요한 객체를 Raycast 연산에서 제외.Raycast 길이 제한:
충돌 조건 최소화:
Screen 좌표계:
(0, 0), 오른쪽 위가 (Screen.width, Screen.height).Viewport 좌표계:
(0, 0), 오른쪽 위가 (1, 1).World 좌표계:
Vector3 mousePos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane));
분석:
1. Input.mousePosition:
ScreenToWorldPoint:nearClipPlane)로 설정.캐릭터와 장애물 감지:
클릭 이벤트 처리:
투사체 경로 확인: