?在開發(fā)中 有個需求,射線要檢測所有穿過的物體。
代碼如下:
?文章來源地址http://www.zghlxwxcb.cn/news/detail-633093.html
using UnityEngine;
public class HitCollider : MonoBehaviour
{
public float raycastDistance = Mathf.Infinity;
// Update is called once per frame
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//new Ray(transform.position, transform.forward); // 從當前物體出發(fā),沿著其正前方發(fā)射一條射線
RaycastHit[]
hits = new RaycastHit[Physics.RaycastAll(ray, raycastDistance)
.Length]; // 使用Physics.RaycastAll獲取所有被射線擊中的物體,并存儲在hits數(shù)組中
for (int i = 0; i < hits.Length; i++)
{
hits[i] = Physics.RaycastAll(ray, raycastDistance)[i]; // 將射線檢測的結果賦值給hits數(shù)組
Debug.Log("Hit " + i + " object: " + hits[i].collider.gameObject.name); // 輸出被擊中的物體名稱
}
}
}
運行結果
文章來源:http://www.zghlxwxcb.cn/news/detail-633093.html
?
到了這里,關于Unity 中檢測射線穿過的所有的物體的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!