当我们使用射线投射检测到碰撞时,可以从RaycastHit中获取射线投射返回的信息,其中normal变量表示碰撞物体表面的法线向量:
代码语言:javascript复制using UnityEngine;
public class Example : MonoBehaviour
{
private void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
bool flag = Physics.Raycast(ray, out RaycastHit hit);
if (flag)
{
//法线信息
Debug.Log(hit.normal);
}
}
}
Unity圣典中的介绍:
例如子弹击中物体时,会在物体表面生成一个弹孔,该弹孔的朝向可以通过normal法线向量进行设置,同样,击中物体时产生的溅射粒子特效的朝向也需要根据该法线信息进行设置。
我们通过鼠标点击来模拟上面的效果,从鼠标位置发出一条射线进行检测,点击鼠标时在碰撞点生成一个弹孔及溅射粒子特效,代码如下:
代码语言:javascript复制using UnityEngine;
using UnityEditor;
public class Example : MonoBehaviour
{
[SerializeField] private GameObject decal;
[SerializeField] private GameObject effect;
private bool flag;
private RaycastHit hit;
private void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
flag = Physics.Raycast(ray, out hit);
if (flag)
{
if (Input.GetMouseButtonDown(0))
{
var decalInstance = Instantiate(decal);
decalInstance.transform.position = hit.point hit.normal * .02f;
decalInstance.transform.forward = hit.normal;
var effectInstance = Instantiate(effect);
effectInstance.transform.position = hit.point hit.normal * .02f;
effectInstance.transform.forward = hit.normal;
}
}
}
private void OnDrawGizmos()
{
Handles.color = Color.cyan;
if (flag)
{
Handles.DrawLine(hit.point, hit.point hit.normal);
}
}
}