Unity 射线碰撞

static bool Raycast(Vector3origin,Vector3direction, float distance = Mathf.Infinity, intlayerMask = DefaultRaycastLayers);

static bool Raycast(Vector3origin,Vector3direction,RaycastHithitInfo, float distance = Mathf.Infinity, intlayerMask = DefaultRaycastLayers);

5个参数分别是射线的起点、方向(起点和方向可以用一个Ray代替)、碰撞信息(可忽略)、射线距离(默认值无穷大),碰撞层级(默认值为DefaultRaycastLayers)


其中,RaycastHit hitInfo是获取碰撞信息的参数,调用时必须为out

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {
    void Update() {
        RaycastHit hit;
        if (Physics.Raycast(transform.position, -Vector3.up, out hit, 100.0F))
            float distanceToGround = hit.distance;
        
    }
}

Physics.DefaultRaycastLayers:除了Ignore Raycast之外的所有层级,这是使用Physics.Raycast时的默认值。

Physics.IgnoreRaycastLayer:Ignore Raycast层。

Physics.AllLayers:所有层级,当在Physics.Raycast中使用这个值时,所有的层包括Ignore Raycast也可以接收射线碰撞

如果射线的起点在碰撞器的内部,则Physics.Raycast会返回false.

Notes: This function will return false if you cast a ray from inside a sphere to the outside; this in an intended behaviour. If you move colliders from scripting or by animation, there needs to be at least one FixedUpdate executed so that the physics library can update it's data structures, before a Raycast will hit the collider at it's new position.

 

你可能感兴趣的:(Unity 射线碰撞)