【Steam VR 2.0】4.UIElement+Collider碰触交互UGUI Button

目前没有一个比简洁的,可以和UGUI交互的方式

因此,先写一个应急用的,可以使用手柄点击到UGUI按钮的功能

之后再继续完善(或者等VRTK更新4.0)

本篇的功能是,在按钮上放collider并且,手柄碰触到按钮,可以触发按钮事件(仅应急用,为后续更新射线版做准备)

操作按钮

首先搭建场景

创建一个可传送的场景,

然后创建一个UGUI的Button,

Canvas设置成word,reset一下,然后宽高设置为1

按钮的Recttransform,拉小,这里尽量不要缩放,因为之后要在button上放collider,缩放会影响collider

接着按钮下方的文字,可以缩放到0.01,一般适用

然后再button上添加碰撞体,调节好大小,勾选isTrigger。再添加Interactable组件

接下来参考示例场景中与UI的交互,主要的脚本是UIElement

(不过里面的按键提示很讨厌,打开UIElement,将其注释掉)

//-------------------------------------------------
protected virtual void OnHandHoverBegin( Hand hand )
{
	currentHand = hand;
	InputModule.instance.HoverBegin( gameObject );
	//ControllerButtonHints.ShowButtonHint( hand, hand.uiInteractAction);
}


//-------------------------------------------------
protected virtual void OnHandHoverEnd( Hand hand )
{
	InputModule.instance.HoverEnd( gameObject );
	//ControllerButtonHints.HideButtonHint( hand, hand.uiInteractAction);
	currentHand = null;
}


//-------------------------------------------------
protected virtual void HandHoverUpdate( Hand hand )
{
	if ( hand.uiInteractAction != null && hand.uiInteractAction.GetStateDown(hand.handType) )
	{
		InputModule.instance.Submit( gameObject );
		//ControllerButtonHints.HideButtonHint( hand, hand.uiInteractAction);
	}
}

接下来我们创建一个脚本命名为MyUIElement,并写入如下代码

using UnityEngine;
using Valve.VR.InteractionSystem;


public class MyUIElement : UIElement
{
    protected override void Awake() {
        base.Awake();
    }

    protected override void OnHandHoverBegin(Hand hand) {
        base.OnHandHoverBegin(hand);
        Debug.Log("Hover Begin");
    }

    protected override void OnHandHoverEnd(Hand hand) {
        base.OnHandHoverEnd(hand);
        Debug.Log("Hover End");
    }

    protected override void HandHoverUpdate(Hand hand) {
        base.HandHoverUpdate(hand);
        Debug.Log("Hovering");
    }

    protected override void OnButtonClick() {
        base.OnButtonClick();

        Debug.Log("Click");

}

按钮上参数 

功能完成。

简单的扩展

为OnButtonClick添加一个事件

public event Action buttonClick;

在OnButtonClick中调用它

就可以任意为其添加监听了

private void Start() {
    buttonClick += OnButtonCilckAdd;
}


public void OnButtonCilckAdd() {
    Debug.Log("Add");
}

运行结果 

-

猜你喜欢

转载自blog.csdn.net/u011643463/article/details/107505333