参考文献:
部分内容由千峰教育(莫新宇)听课笔记及Scripting API总结file:///D:/myUnity/Editor/Data/Documentation/en/ScriptReference/Physics.RaycastAll.html
Physics.RaycastAll
Parameters 参数
ray | The starting point and direction of the ray. 射线的出发点及方向 |
maxDistance | The max distance the rayhit is allowed to be from the start of the ray. 射线从点发出后所能达到的最大距离 |
layerMask | A Layer mask that is used to selectively ignore colliders when casting a ray. 当透射射线时一个层掩饰器被用来选择去忽略碰撞体 |
queryTriggerInteraction | Specifies whether this query should hit Triggers. 指定该射线是否会命中触发器 |
Description
Casts a ray through the scene and returns all hits. Note that order is not guaranteed.
透射出一条射线返回场景中所有触碰的物体
See Also: Raycast.
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; } } } }
Notes: Raycasts will not detect colliders for which the raycast origin is inside the collider.
public static RaycastHit[] RaycastAll(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layermask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
Parameters
origin | The starting point of the ray in world coordinates. |
direction | The direction of the ray. |
maxDistance | The max distance the rayhit is allowed to be from the start of the ray. |
layermask | A Layer mask that is used to selectively ignore colliders when casting a ray. |
queryTriggerInteraction | Specifies whether this query should hit Triggers. |
范例代码
using UnityEngine;
public class RayDemo : MonoBehaviour {
// Update is called once per frame
private RaycastHit[] hits;
void Update()
{
hits = Physics.RaycastAll(transform.position, transform.forward, 100.0F);
Debug.DrawLine(transform.position, transform.forward*100, Color.red);
for (int i = 0; i < hits.Length; i++)
{
RaycastHit hit = hits[i];
Debug.Log("碰撞点为:"+ hit.point);
Vector3 tempPos = hit.transform.position;
GameObject temObj=new GameObject("point");
temObj.transform.position = tempPos;
temObj.AddComponent<MeshRenderer>().material.color = Color.red;
}
}
}