标签:unity3d
关于API看一下链接
http://game.ceeger.com/Script/Physics/Physics.Raycast.html
? static function Raycast (origin : Vector3, direction : Vector3, out hitInfo : RaycastHit, distance : float = Mathf.Infinity, layerMask : int = kDefaultRaycastLayers) : bool
1.注意:如果从一个球型体的内部到外部用光线投射,返回为假
2.layerMask层的选择和屏蔽
首先 看第一个 如果一个点在碰撞体内部,向外部射,
先写一个脚本
using UnityEngine; using System.Collections; public class Demo2 : MonoBehaviour { public float XStartPos = 0f; public float YStartPos = 0f; public float ZStartPos = 0f; public float XEndPos = 0f; public float YEndPos = 0f; public float ZEndPos = 0f; private Vector3 startPos; private Vector3 endPos; private Vector3 direction; private float distance; // Use this for initialization void Start () { startPos = new Vector3 (XStartPos, YStartPos, ZStartPos); endPos = new Vector3 (XEndPos, YEndPos, ZEndPos); direction = (endPos - startPos).normalized; distance = Vector3.Distance (startPos, endPos); } // Update is called once per frame void Update () { Debug.DrawLine (startPos, endPos, Color.red); RaycastHit hit; if (!Physics.Raycast (startPos, direction, out hit, distance)) { Debug.Log ("false"); } else { Debug.Log ("yes " + hit.collider.name); } } }
再建一个cube2,startPos依然在cube1内,但endPos在cube2内,运行结果表明 yes cube2
也就是说 射线由内部向外部射 是不识别自己的碰撞体,但是识别其他的碰撞体。
第二个问题关于射线层的选择和屏蔽
修改一下脚本
using UnityEngine; using System.Collections; public class Demo3 : MonoBehaviour { public float XStartPos = 0f; public float YStartPos = 0f; public float ZStartPos = 0f; public float XEndPos = 0f; public float YEndPos = 0f; public float ZEndPos = 0f; private Vector3 startPos; private Vector3 endPos; private Vector3 direction; private float distance; // Use this for initialization void Start () { startPos = new Vector3 (XStartPos, YStartPos, ZStartPos); endPos = new Vector3 (XEndPos, YEndPos, ZEndPos); direction = (endPos - startPos).normalized; distance = Vector3.Distance (startPos, endPos); } // Update is called once per frame void Update () { Debug.DrawLine (startPos, endPos, Color.red); RaycastHit hit; LayerMask l = 1 << LayerMask.NameToLayer("cube1"); if (Physics.Raycast (startPos, direction, out hit, distance, l)) { Debug.Log ("yes " + hit.collider.name); } else { Debug.Log ("false"); } } }
自行比对
只与cube1层碰撞
Physics.Raycast (startPos, direction, out hit, distance, l)与除cube1层以外的层碰撞
Physics.Raycast (startPos, direction, out hit, distance, ~l)
Physics.Raycast (startPos, direction, out hit, distance, 1 << LayerMask.NameToLayer("cube2") | 1 << LayerMask.NameToLayer("cube3"))
Physics.Raycast (startPos, direction, out hit, distance,~(1 << LayerMask.NameToLayer("cube2") | 1 << LayerMask.NameToLayer("cube3")))
标签:unity3d
原文地址:http://blog.csdn.net/lihuozhiling0101/article/details/41347041