TIL
20240205 TIL
[폴른]
2024. 2. 5. 21:25
Today I Learned :
Input System : 마우스 & Raycast
private void OnMouseClick(InputValue input)
{
RaycastHit2D hit = Physics2D.GetRayIntersection(camera.ScreenPointToRay(Mouse.current.position.ReadValue()));
if (hit.collider != null)
{
// 충돌한 대상 가져오기
GameObject collidedObject = hit.collider.gameObject;
// 여기서 collidedObject를 사용하여 원하는 작업 수행
Debug.Log("Collided with: " + collidedObject.name);
}
}
클릭한 포지션에서 Raycast 실행. 충돌체 감지한 후 작업 수행
Physics.Raycast와 Physics2D.GetRayIntersection은 Unity의 3D 및 2D 물리 시스템에서 각각 사용되는 Raycast 메서드입니다.
- Physics.Raycast:
- Physics.Raycast는 3D 물리 시스템에서 사용되며, 3D 공간에서 Ray가 충돌한 지점을 검출하는 데에 쓰입니다.
- 사용 예시: Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask);
- out hit을 통해 충돌 정보를 얻을 수 있습니다.
- Physics2D.GetRayIntersection:
- Physics2D.GetRayIntersection은 2D 물리 시스템에서 사용되며, 2D 공간에서 Ray가 충돌한 지점을 검출하는 데에 사용됩니다.
- 사용 예시: Physics2D.GetRayIntersection(ray, Mathf.Infinity, layerMask);
- 반환 값으로 RaycastHit2D를 얻을 수 있습니다.
주된 차이점은 주로 3D 공간과 2D 공간에서의 사용이며, 반환되는 데이터 형식이 다릅니다. Physics.Raycast는 RaycastHit을 반환하고, Physics2D.GetRayIntersection은 RaycastHit2D를 반환합니다.
// 3D에서의 예시
Ray ray = new Ray(origin, direction);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask))
{
// 3D에서의 충돌 처리
}
// 2D에서의 예시
RaycastHit2D hit2D = Physics2D.GetRayIntersection(ray, Mathf.Infinity, layerMask);
if (hit2D.collider != null)
{
// 2D에서의 충돌 처리
}
참고 영상
https://www.youtube.com/watch?v=mRkFj8J7y_I