定义
参数对应起始点、终点、碰撞信息、射线长度、可碰撞的层,函数返回值为布尔;
Physics.Raycast(Vector3 origin, Vector3 direction, RaycastHit hitInfo, float distance, int LayerMask);
其中,起始点和终点参数可以封装在ray中:
//transform.forward为物体自身z轴朝向,会随物体旋转改变,Vector3.forward为固定的世界空间z轴
Ray = new Ray(transform.position,transform.forward);
Physics.Raycast(Ray, RaycastHit hitInfo,float distance, int LayerMask);
注意:碰撞的物体一定要有碰撞体,不然检测不到;
注意:碰撞的物体一定要有碰撞体,不然检测不到;
注意:碰撞的物体一定要有碰撞体,不然检测不到;
QueryTriggerInteraction.Ignore:如果勾选is trigger,就会忽略碰撞事件;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunRay : MonoBehaviour
{
public Ray ray;
[SerializeField]
private float maxDistance=100;
RaycastHit hitInfo;
public LayerMask mask;
private void Update()
{
//transform.forward为物体自身z轴朝向,会随物体旋转改变,Vector3.forward为固定的世界空间z轴
ray = new Ray(transform.position, transform.forward);
if (Physics.Raycast(ray, out hitInfo, maxDistance, mask, QueryTriggerInteraction.Ignore))
{
Debug.Log(hitInfo.collider.gameObject.name);
Debug.DrawLine(transform.position, hitInfo.point, Color.red);
}
else {
Debug.DrawLine(transform.position, transform.position+ transform.forward*100, Color.yellow);
}
}
}
一次性碰撞路径上所有物体:
hits = Physics.RaycastAll(ray,maxDistance,mask);
Debug.DrawLine(transform.position, transform.position + transform.forward * 100, Color.red);
foreach (RaycastHit hit in hits)
hit.collider.gameObject.GetComponent<Renderer>().material = highlightMat;
种树
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Placement : MonoBehaviour
{
//不设置层的话射线会被cube挡住,或者可以将cube的碰撞体关掉
public LayerMask planeLayer;
public GameObject tree;
void Update()
{
//将鼠标的位置信息从屏幕坐标系转换到ray类型;ray就是从屏幕到鼠标位置的射线
//这里操作的是cube中心点的位置,可以设置一个空物体,将两个物体归零,然后cube设为空物体的子物体,并将cube向上移动0.5个单位,脚本给空物体,这样操作的就是cube的底部中心点
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//Mathf.Infinity无限长
if (Physics.Raycast(ray, out RaycastHit hitInfo, Mathf.Infinity,planeLayer)) {
tree.transform.position = hitInfo.point;
tree.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal); //初始为向上,旋转到接触平面的法向量
}
if (Input.GetMouseButtonDown(0)) {
Instantiate(tree, hitInfo.point, Quaternion.FromToRotation(Vector3.up, hitInfo.normal));
}
}
}
其他应用
自动寻路;
降落伞(官方Demo);
点击物体显示信息等等;