유니티 콜라이더 시각화 - yuniti kollaideo sigaghwa

백지부터 시작하는 이세계 코딩 생활

Raycast

콜라이더 (collider) 와의 충돌 감지를 확인할 수 있게 해주는 bool type 함수.
Ray를 쐈을 때, Collider 에 접촉( 충돌 )하면 Ray를 날린 Object 로 반환된다. 이때 RaycastHit을 통해 접촉한 Object의 정보를 반환 받아볼 수 있다. Collider가 없다면 충돌 감지를 할 수 없다.
Ray는 Collider의 종류를 상관하지 않고 Collider의 정보를 반환한다. 따라서 특정 Object의 정보만 필요할 경우 LayerMask를 통해 구현한다.

Physics 클래스의 내장 함수이다. 따라서 Raycast를 사용하기 위해선 Physics.Raycasy(...) 로 시작한다.
RaycastHit 을 선언해주고 함께 사용해야 한다.

사용하는 방법 : 
bool isHit = Physics.Raycast(원점, 방향, 충돌반환(out hit), 레이어 마스크(판별));

public void CheckTarget()
    {        
            Vector3 direction = enemy.Value.transform.position - transform.position;
            Vector3 startPos = transform.position;
            Vector3 endPos = enemy.Value.transform.position - transform.position;

            startPos.y = 0.5f;
            endPos.y = 0.5f;

            float dist = Vector3.Distance(transform.position, enemy.Value.transform.position);           

            RaycastHit hit;
            bool isHit = Physics.Raycast(startPos, direction, out hit, dist, targetLayer);
            /* Physics.Raycast(원점, 방향, 충돌반환(out hit), 거리, 레이어 마스크(판별));
            */
            
            if (isHit && hit.transform.gameObject.layer == LayerMask.NameToLayer("ENEMY"))
            {
                // Methode
            }           
        }       
           
    }

유니티 콜라이더 시각화 - yuniti kollaideo sigaghwa
Unity Raycast 정보, Physics 메타데이터에서.

Raycast를 사용하는 형식은 위 사진과 같이 여러가지가 방법이 존재한다.

RaycastHit

Raycast를 통해, 충돌여부 정보를 담아서 반환해주는 구조체.

유니티 콜라이더 시각화 - yuniti kollaideo sigaghwa
Unity RaycastHit 메타데이터에서, RaycastHit 프로퍼티들
LayerMask

Layer의 사전적 의미는 "" 이다. 
특정 Object의 Collider 에 대해서만 접촉 (충돌) 판정을 하기 위해 사용한다.

cf. Another Raycast

DrawRay :

Debug 클래스의 내장함수이다. (하위) 따라서 Debug.DrawRay( ... ) 처럼 사용할 수 있다.
Ray의 시각화를 가능하게 해주는 함수이다. 매 프레임 마다 호출된다.

public void DrawGizmoRay()
    {             
            Vector3 direction = enemy.Value.transform.position - transform.position;
            Vector3 startPos = transform.position;
            Vector3 endPos = enemy.Value.transform.position - transform.position;
            startPos.y = 0.5f;
            endPos.y = 0.5f;

            RaycastHit hit;
            bool isHit = Physics.Raycast(startPos, endPos, out hit, dist, targetLayer);
            if (isHit && hit.transform.gameObject.layer == LayerMask.NameToLayer("ENEMY"))
            {
                Debug.DrawRay(startPos, direction, Color.green);
                //Debug.DrawRay(Ray시작위치, 방향, Ray 색상);
            }
            else
            {
                Debug.DrawRay(startPos, direction, Color.red);
            }
    }
    
    
    cf.
    float rayTime = 1.0f;
    Debug.DrawRay(startPos, direction, Color.green, rayTime);
    // 해당 시간(rayTime)동안만 Ray가 표시 되었다가 사라진다.

RaycastAll :

단일 Object가 아닌 Ray와 접촉하는 모든 Collider들의 정보들을 반환한다.
Ray 와 Collider 가 접촉 (충돌)이 발생하면 해당 Collider들의 정보를 배열형식으로 담아온다.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    void Update()
    {
        RaycastHit[] hits;
        hits = Physics.RaycastAll(transform.position, transform.forward, 100.0F);

        for (int i = 0; i < hits.Length; i++)
        {
            RaycastHit hit = hits[i];
            Renderer rend = hit.transform.GetComponent<Renderer>();

            if (rend)
            {
                // Change the material of all hit colliders
                // to use a transparent shader.
                rend.material.shader = Shader.Find("Transparent/Diffuse");
                Color tempColor = rend.material.color;
                tempColor.a = 0.3F;
                rend.material.color = tempColor;
            }
        }
    }
}

cf.
Renderer :  오브젝트가 스크린에 나타내도록 해주는 클래스.
    void Start()
    {
        rend = GetComponent<Renderer>();
        rend.enabled = true;
    }

Ref. About Raycast

ssabi.tistory.com/29

[Unity3D] 레이캐스트(Raycast)

레이캐스트(Raycast) 레이캐스트는 광선을 쏘는 것을 의미합니다. 여기서는 레이를 쏜다 라고 표현하겠습니다. 레이캐스트를 사용하면 광선에 충돌되는 콜라이더(Collider)에 대한 거리, 위치 등의

ssabi.tistory.com

유니티 콜라이더 시각화 - yuniti kollaideo sigaghwa

chameleonstudio.tistory.com/63

유니티 레이캐스트 Raycast 충돌 / Ray의 모든 것

해당 티스토리 페이지는 필자가 유니티 C# 개발을 하면서 학습한 내용들을 기록하고 공유하는 페이지입니다 ! - 틀린 부분이 있거나, 수정된 부분이 있다면 댓글로 알려주세요 ! - 해당 내용을 공

chameleonstudio.tistory.com

유니티 콜라이더 시각화 - yuniti kollaideo sigaghwa

docs.unity3d.com/kr/530/ScriptReference/RaycastHit.html

docs.unity3d.com/ScriptReference/Physics.Raycast.html

Unity - 스크립팅 API: RaycastHit

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. 닫기

docs.unity3d.com

Unity - Scripting API: Physics.Raycast

Description Casts a ray, from point origin, in direction direction, of length maxDistance, against all colliders in the Scene. You may optionally provide a LayerMask, to filter out any Colliders you aren't interested in generating collisions with. Specifyi

docs.unity3d.com

유니티 콜라이더 시각화 - yuniti kollaideo sigaghwa

blog.naver.com/PostView.nhn?blogId=happybaby56&logNo=221370502930

[유니티] RaycastHit 구조체

RaycastHit 은 Raycast 메서드 사용시에 반환받는 충돌정보를 담고 있다.​다음은 RaycastHit 구조체...

blog.naver.com

유니티 콜라이더 시각화 - yuniti kollaideo sigaghwa
Ref. About struct

godnr149.tistory.com/77