设备:Pico 4
1、准备工作:
创建一个XR场景
2、创建button UI效果
在Hierachy中创建button,button有两种,旧版为button组件,新版为网格button。
在Hierachy区域中,鼠标右键或者点击“+”进行控件的添加,如下图所示,选择button
选中后,如下图所示,right-x,forward-z,up-y这三个UI控件为button,在button的上一级为Canvas。
设置脚本,对于多个按钮来说,将脚本附加到Canvas,并在选中button的情况下,查看Inspector中的OnClick,将点击按钮执行的事件添加其中。
手柄映射方法
使用手柄时,对于右手按钮按键可以直接实现按钮的点击动作,下面脚本是为了测试手柄射线与UI的交互,同时测试按键中的其他按钮,下列以X按键为例。
脚本代码如下所示:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using Unity.VisualScripting;
using System;
public class ButtonBehaviourScript : MonoBehaviour
{
// Start is called before the first frame update
public InputDevice leftHandDevice;
public InputDevice rightHandDevice;
public GameObject flower2227;
public GameObject observice;
public Button xButton;
public Button yButton;
public Button zButton;
public Text hintText;
private string yName ;
private string xName ;
private string zName ;
void Start()
{
hintText.text = "Start";
leftHandDevice = InputDevices.GetDeviceAtXRNode(XRNode.LeftHand); //绑定左手手柄
rightHandDevice = InputDevices.GetDeviceAtXRNode(XRNode.RightHand); //绑定右手手柄
yName = yButton.gameObject.name;
xName = xButton.gameObject.name;
zName = zButton.gameObject.name;
//xButton.onClick.AddListener(rightXOnClikck);
//yButton.onClick.AddListener(upYOnClikck);
//zButton.onClick.AddListener(forwardZOnClikck);
}
// Update is called once per frame
void Update()
{
// hintText.text = Time.captureFramerate.ToString();
}
public void OnPointerEnter(PointerEventData eventData)
{
//按钮处于高亮状态
hintText.text = "OnPointerEnter";
rayButtonOnClick(eventData);
}
private void rayButtonOnClick(PointerEventData eventData)
{
// 获取x键是否被按下
bool primaryValue;
if (leftHandDevice.TryGetFeatureValue(CommonUsages.primaryButton, out primaryValue) && primaryValue)
{
ToRoute(eventData.pointerEnter.name);
}
//if (rightHandDevice.TryGetFeatureValue(CommonUsages.primaryButton, out primaryValue) && primaryValue)
//{
// ToRoute(eventData.pointerEnter.name);
//}
}
private void ToRoute(string eventName)
{
hintText.text = eventName ;
if (eventName == yName)
{
upYOnClikck();
}
else if(eventName == xName)
{
rightXOnClikck();
}
else if (eventName == zName)
{
forwardZOnClikck();
}
}
public void upYOnClikck()
{
//沿y轴旋转90度
Rotate(Vector3.right, 90);
}
public void rightXOnClikck()
{
//沿x轴旋转90度
Rotate(Vector3.up, 90);
}
public void forwardZOnClikck()
{
//沿z轴旋转90度
Rotate(Vector3.forward, 90);
}
private void Rotate(Vector3 axis, float angle)
{
flower2227.transform.Rotate(axis, angle, Space.Self); // 使用自身坐标系进行旋转
observice.transform.Rotate(axis, angle, Space.Self); // 使用自身坐标系进行旋转
}
}