쫑가 과정

2d RayCast 기본 본문

Unity2D/이론

2d RayCast 기본

쫑가 2022. 1. 20. 20:46

https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html

 

Unity - Scripting API: Physics2D.Raycast

A raycast is conceptually like a laser beam that is fired from a point in space along a particular direction. Any object making contact with the beam can be detected and reported. This function returns a RaycastHit object with a reference to the Collider t

docs.unity3d.com

public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);
장면의 충돌기(Collider)에 대해 광선(ray)을 발사한다.
RaycastHit2D로 캐스트 결과가 반환된다.

https://docs.unity3d.com/ScriptReference/RaycastHit2D.html

 

Unity - Scripting API: RaycastHit2D

Success! Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable. Close

docs.unity3d.com

Physics2D.Raycast에 의해 감지된 객체에 대해 정보는 RaycastHit2D 로 반환된다.

centroid 캐스트를 수행하는 데 사용되는 기본체의 중심.
collider
광선에 충돌한 collider.
distance
광선 원점에서 충돌 지점까지의 거리.
fraction 적중이 발생한 광선을 따른 거리의 비율.
normal
광선이 닿는 표면의 nomal 벡터.
point
광선이 충돌기의 표면에 닿는 세계 공간(world space)의 지점.
rigidbody
적중된 개체에 연결된 Rigidbody2D.
transform
적중된 개체의 transform.

 

예시1) 방향에 있는 오브젝트 감지하기.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    public Vector2 direction;

    void Update()
    {
        //Cast a ray in the direction specified in the inspector.
        RaycastHit2D hit = Physics2D.Raycast(this.gameObject.transform.position, direction, 10.0f);

        //If something was hit.
        if (hit.collider != null)
        {
            Transform objectHit = hit.transform;

            //Display the name of the parent of the object hit.
            Debug.Log(objectHit.parent.name);
        }
    }
}

예시2) 마우스 클릭한 오브젝트 탐지하기

public class ExampleClass : MonoBehaviour
{
	void Update()
	{
		//If the left mouse button is clicked.
		if (Input.GetMouseButtonDown(0))
		{
			//Get the mouse position on the screen and send a raycast into the game world from that position.
			Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
			RaycastHit2D hit = Physics2D.Raycast(worldPoint,Vector2.zero);

			//If something was hit, the RaycastHit2D.collider will not be null.
			if ( hit.collider != null )
			{
				Debug.Log( hit.collider.name );
			}
		}
	}
}

 

Comments