Unity 里有两种射线,
- 一个不可以穿透物体的射线
Physics.Raycast
,如下图,射线被胶囊体挡住。
- 一个可以穿透物体的射线
Physics.RaycastAll
,该方法可以检测所有射线碰撞的物体
两种方法分别写了一个例子。
Physics.Raycast
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayTest : MonoBehaviour
{
// Start is called before the first frame update
private RaycastHit raytest;
private Ray a;
void Start()
{
}
private void Update()
{
a = new Ray(transform.position,transform.forward);
int b = LayerMask.GetMask("test","test1");
int c = (1 << 9) | (1 << 10);
Debug.Log("b::::::::"+b+",,,,,c::::::"+c);
if(Physics.Raycast(a,out raytest,200,b)){
Debug.Log(raytest.point);
Debug.Log(raytest.transform.name);
}
Debug.DrawLine(transform.position,raytest.point,Color.magenta);
}
}
Physics.RaycastAll
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayTestAll : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Ray ray = new Ray(transform.position,transform.forward);
RaycastHit[] rays = Physics.RaycastAll(ray, 100);
foreach (var VARIABLE in rays)
{
Debug.Log(VARIABLE.transform.name);
}
Debug.DrawLine(transform.position,transform.forward*100,Color.red);
}
}