https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
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.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;
}
}
}
}