Unity Manual之Physics.Raycast射线投射

Unity Manual之Physics.Raycast射线投射

1、C# ⇒ public static bool Raycast(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers);



当光线投射与任何碰撞器交叉时为真,否则为假。

在场景中投下可与所有碰撞器碰撞的一条光线。

using UnityEngine;
using System.Collections;
 
public class ExampleClass : MonoBehaviour {
    void Update() {
        Vector3 fwd = transform.TransformDirection(Vector3.forward);
        if (Physics.Raycast(transform.position, fwd, 10))
            print("There is something in front of the object!");
 
    }
}

注意:如果射线从碰撞体的内部或者背面打,Raycast不检测碰撞。如果你用脚本或动画移动碰撞器,需要至少一个在FixedUpdate执行,因为物理库能更新它的数据结构,因此一条射线在它的新位置之前打到碰撞器。


2、C# ⇒ public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers);

Unity Manual之Physics.Raycast射线投射_第1张图片

using UnityEngine;
using System.Collections;
 
public class ExampleClass : MonoBehaviour {
    void Update() {
        RaycastHit hit;
        if (Physics.Raycast(transform.position, -Vector3.up, out hit))
            float distanceToGround = hit.distance;
 
    }
}

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


3、C# ⇒ public static bool Raycast(Ray ray, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers);

Unity Manual之Physics.Raycast射线投射_第2张图片

using UnityEngine;
using System.Collections;
 
public class ExampleClass : MonoBehaviour {
    void Update() {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, 100))
            print("Hit something");
 
    }
}

4、C# ⇒ public static bool Raycast(Ray ray, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers);



using UnityEngine;
using System.Collections;
 
public class ExampleClass : MonoBehaviour {
    void Update() {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 100))
            Debug.DrawLine(ray.origin, hit.point);
 
    }
}

==================================================================================
结束。

你可能感兴趣的:(Unity Manual之Physics.Raycast射线投射)