Unity-VR中使用手柄点击UI
拓展BaseInputModule
使用鼠标模拟VR设备操作
using UnityEngine.EventSystems;
using UnityEngine;
namespace Framework.VR
{
/// <summary>
///按下鼠标左键,手柄Z轴方向获取UI对象,通知对象被点击
/// </summary>
public class VRInputModule : BaseInputModule
{
[SerializeField] Camera eventCamra;//画布使用的事件相机
[SerializeField] Transform hand;//手柄变换
public override void Process()
{
if (input.GetMouseButtonDown(0))//模拟VR设备按下
{
eventCamra.transform.position = hand.position;
eventCamra.transform.rotation = hand.rotation;
PointerEventData eventData = new PointerEventData(eventSystem);
eventData.position = new Vector2(eventCamra.pixelWidth, eventCamra.pixelHeight) * 0.5f;
eventSystem.RaycastAll(eventData, m_RaycastResultCache);//检测
eventData.pointerCurrentRaycast = FindFirstRaycast(m_RaycastResultCache);
m_RaycastResultCache.Clear();
ExecuteEvents.ExecuteHierarchy(eventData.pointerCurrentRaycast.gameObject,
eventData, ExecuteEvents.pointerDownHandler);//通知点击
}
}
}
}
测试脚本:点击图片,图片改变颜色
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
/// <summary>
///图片改变颜色
/// </summary>
[RequireComponent(typeof(Image))]
public class TestClick : MonoBehaviour, IPointerDownHandler
{
Image image;
Color color;
private void Awake()
{
image = GetComponent<Image>();
color = image.color;
}
public void OnPointerDown(PointerEventData eventData)
{
color.r = Random.Range(0f, 1f);
color.g = Random.Range(0f, 1f);
color.b = Random.Range(0f, 1f);
image.color = color;
}
}
场景设置
- 新建相机命名为EventCamera,禁用相机组件
- 新建Canvas设置为World Space模式,设置事件相机为上述相机
- 新建Image添加TestClick脚本
- 新建立方体命名为VR Hand
- EventSystem禁用Standalone Input Module组件,添加VRInputModule脚本
- VRInputModule脚本设置事件相机和VR Hand
运行
移动立方体遮挡图片,按下鼠标左键,图片改变颜色;
移动立方体远离图片,按下鼠标左键,图片颜色无变化。