Physics.Raycast 射线投射
public static bool Raycast(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
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;
public class ExampleClass : MonoBehaviour {
void Update() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, 100))
print("Hit something");
}
}
Physics.CapsuleCast 胶囊投射
public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
胶囊是由radius半径与point1和point2位置的两个球形成胶囊的两端定义。返回胶囊沿direction方向碰到的第一个碰撞器。这通常用于投射不需足够的精度,因为你要找出一个特定大小的物体,如人物,能移动到某处而不在途中碰撞到任何东西。
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void Update() {
RaycastHit hit;
CharacterController charContr = GetComponent<CharacterController>();
Vector3 p1 = transform.position + charContr.center + Vector3.up * -charContr.height * 0.5F;
Vector3 p2 = p1 + Vector3.up * charContr.height;
float distanceToObstacle = 0;
// Cast character controller shape 10 meters forward to see if it is about to hit anything.
if (Physics.CapsuleCast(p1, p2, charContr.radius, transform.forward, out hit, 10))
distanceToObstacle = hit.distance;
}