代码GazeController,实现击中物体时UI的变化,挂载到Camera(eye)上(因为从眼睛这发出射线)
using UnityEngine;
using UnityEngine.UI;
public class GazeController : MonoBehaviour {
//设置canvas位置、朝向
public Canvas reticleCanvas;
//设置准星填充效果等
public Image reticleImage;
//被击中的物体
private GameObject target;
//准星初始位置
private Vector3 originPos;
//准星初始缩放:当看远处时变大,看近处时变小
private Vector3 originScale;
//倒计时时间
private float countDownTime = 3;
//逝去时间(当前时间)
private float nowTime = 0;
void Start () {
reticleImage.fillAmount = 0;
originPos = reticleCanvas.transform.localPosition;
originScale = reticleCanvas.transform.localScale;
}
void Update () {
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
if(Physics.Raycast(ray,out hit, 100))
{
//将准星放到碰撞点上
reticleCanvas.transform.position = hit.point;
reticleCanvas.transform.localScale = originScale * hit.distance;
//让准星的法线方向和被击中的物体法线方向一致
reticleCanvas.transform.forward = hit.normal;
//视线初次进入处理
if (hit.transform.gameObject != target)
{
//视线凝视的上一个物体,完成退出操作
if (target != null)
{
VRGazeItem oldItem = target.GetComponent<VRGazeItem>();
if (oldItem)
{
oldItem.OnGazeOut();
}
}
//视线正处于的物体
target = hit.transform.gameObject;
VRGazeItem newItem = target.GetComponent<VRGazeItem>();
if (newItem)
{
newItem.OnGazeIn();
}
}
//视线长久停留处理
else
{
nowTime += Time.deltaTime;
//正在读秒时间
if (countDownTime > nowTime)
{
reticleImage.fillAmount = nowTime / countDownTime;
}
//达到激活条件
else
{
VRGazeItem gazeFireItem = target.GetComponent<VRGazeItem>();
if (gazeFireItem)
{
gazeFireItem.OnGazeFire(hit);
}
nowTime = 0;
}
}
}
else
{
reticleCanvas.transform.localPosition = originPos;
reticleCanvas.transform.localScale = originScale;
//在未击中时,准星法线方向和摄像机视线方向一致
reticleCanvas.transform.forward = Camera.main.transform.forward;
reticleImage.fillAmount = 0;
}
}
}
该代码挂载到被击中的物体上,实现该物体被击中时的效果
与该代码配套的是两个material:HighlightMat和NormalMat,实现3D物体被凝视时材质的变换
using UnityEngine;
using UnityEngine.EventSystems;
public class VRGazeItem : MonoBehaviour {
public Material highlightMat;
public Material normalMat;
//视线进入
public void OnGazeIn()
{
if (gameObject.tag == "gazeUI")
{
//VR场景中UI实现鼠标移入效果
ExecuteEvents.Execute(gameObject, new PointerEventData(EventSystem.current), ExecuteEvents.pointerEnterHandler);
}else if (gameObject.tag == "gazeObj")
{
gameObject.GetComponent<Renderer>().material = highlightMat;
}
}
//视线移出
public void OnGazeOut()
{
if (gameObject.tag == "gazeUI")
{
//VR场景中UI实现鼠标移出入效果
ExecuteEvents.Execute(gameObject, new PointerEventData(EventSystem.current), ExecuteEvents.pointerExitHandler);
}
else if (gameObject.tag == "gazeObj")
{
gameObject.GetComponent<Renderer>().material = normalMat;
}
}
//凝视处理函数
public void OnGazeFire(RaycastHit hit)
{
if (gameObject.tag == "gazeUI")
{
gameObject.SetActive(false);
}
else if (gameObject.tag == "gazeObj")
{
gameObject.GetComponent<Rigidbody>().AddForceAtPosition(hit.point.normalized * 100, hit.point);
}
}
}
转载https://blog.csdn.net/weixin_38239050/article/details/81229751