[Unity] Raycast

ChangJin·2024년 2월 19일
0
post-thumbnail

공식문서를 참고해보면...

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


# Raycast - 레이캐스트를 쉽게 말하면 레이저를 쏜다고 생각하면 됩니다. 모든 물체를 뚫는 레이저도 있고 뚫지 않고 막히는 레이저도 있습니다. 이 레이저에 충돌된 물체들을 감지해서 감지된 물체를 선택하거나 파괴하거나 이동하거나 회전할 수 있습니다. 게임에서 정말 많이 쓰이는 개념입니다.

Physics.Raycast

  • ray가 한 Collider와 충돌했으면 true, 그렇지 않으면 false를 반환합니다.

  • 플레이어의 정면으로 ray를 쏘고 어떤 물체가 있는지 판단할 수 있습니다

    • 바닥에 떨어진 무기를 잡는 행위에서 쓰입니다.
  • Physics.Raycast 예시입니다.

using UnityEngine;

// C# example.

public class ExampleClass : MonoBehaviour
{
    // See Order of Execution for Event Functions for information on FixedUpdate() and Update() related to physics queries
    void FixedUpdate()
    {
        // Bit shift the index of the layer (8) to get a bit mask
        int layerMask = 1 << 8;

        // This would cast rays only against colliders in layer 8.
        // But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
        layerMask = ~layerMask;

        RaycastHit hit;
        // Does the ray intersect any objects excluding the player layer
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
        {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
            Debug.Log("Did Hit");
        }
        else
        {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
            Debug.Log("Did not Hit");
        }
    }
}


Physics.RaycastAll

  • Physics.Raycast가 물체를 뚫지 못하는 레이저라면 Physics.RaycastAll을 물체를 전부 통과해서 계속 직진하는 레이저라고 생각하면 됩니다.

  • ray의 시작과 끝 사이에 있는 모든 물체를 배열에 담아 반환합니다.

  • Physics.RaycastAll 예시입니다.

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;
            }
        }
    }
}
profile
게임 프로그래머

0개의 댓글