问题产生背景:我们有的时候,需要实现射线与3D UI之间的碰撞,当射线碰撞到3D UI之后(将Canvas设置为World Space),调整到合适的位置。使用LineRender表示射线的直观显示,使用一把枪结合第一人称控制器。当射线瞄准UI的时候,UI添加高亮边框。点击鼠标左键,调用按钮对应的函数。
(1)首先,搭建场景,最终如下所示
(2)简要说明:给Button添加Mask组件,设置对应的边框,开始的时候enable为false。当射线指向的时候,enable为true。枪口添加ray对象,作为射线的起点,并且为ray添加LineRender组件
调整必要的参数,设置Use World Space为false。
(3)给Button添加一个BoxCollider组件,调整大小正好包括Button即可
(4)新建脚本,控制射线以及碰撞,代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class GraphicDetect : MonoBehaviour
{
public Transform origin; //射线起点
public Button startBtn; //开始按钮
public LineRenderer line;
Vector3 endPoint; //LineRender结束点
// Start is called before the first frame update
void Start()
{
startBtn.onClick.AddListener(delegate ()
{
Debug.Log("Game Start");
});
endPoint = line.GetPosition(1);
}
// Update is called once per frame
void Update()
{
// Physics
RaycastHit hit;
//需要设置射线检测层
if (Physics.Raycast(origin.position, origin.forward, out hit,50))
{
if (hit.collider.gameObject.layer == LayerMask.NameToLayer("UI"))
{
//将轮廓组件显示
startBtn.gameObject.GetComponent<Outline>().enabled = true;
//将世界坐标转换为Local
line.SetPosition(1,line.transform.InverseTransformPoint( hit.point));
if (Input.GetMouseButtonDown(0))
{
//自动执行按钮对应的回调函数
ExecuteEvents.Execute<IPointerClickHandler>(startBtn.gameObject,
new PointerEventData(EventSystem.current),
ExecuteEvents.pointerClickHandler);
}
}
}
else {
startBtn.gameObject.GetComponent<Outline>().enabled = false;
line.SetPosition(1,endPoint);
}
}
}
(5)给该脚本必要的组件赋值,结合第一人称控制器。当枪口移动并且射线指向Button的时候,会触发按钮对应的函数并且显示边框。显示按钮的边框可以使用Shader进行实现,我这里为了演示方便,直接用的Outline。