2017年11月27日 星期一

擴增實境的虛擬按鈕(Augmented Reality Virtual Buttons)

什麼也可以用軟體來虛構出按鈕,真是超強的,超省的作法連按鈕的費用都可省掉。仔細看下面的影片,虛構出兩個按鈕,用手指輕按虛擬按鈕,就可以切換3D的角色。



下載原始程式: Download Whole Project files of VirtualButtons (the result to test it) (*.rar file)

打開VirtualButtons專案,在Project視窗下,選擇Assets目錄下,選擇VirtualNuttonResult,如下圖右下角的紅色方塊,在左上角的方塊上有btnLeft和btnRight兩個按鈕物件。在兩個按鈕上方,可以看到model1和model2兩個角色。


在點選btnLeft物件後,在下圖右方可以看到這個物件內嵌一個Virtual Button Behaiour.cs程式,並且在右邊可以看到有Name和Sensitivity Setting兩個屬性,請特別留意Name。


接下來,請點選ImageTarget物件,在右下方您可以看到VirtualButtonEventHandler.cs腳本程式,這是用來處理按鈕事件的程式。


VirtualButtonEventHandler.cs程式列表如下:


using UnityEngine;
using System.Collections.Generic;
using Vuforia;

public class VirtualButtonEventHandler : MonoBehaviour, IVirtualButtonEventHandler {

    // Private fields to store the models
    private GameObject model_1;
    private GameObject model_2;
private GameObject btn_1;
private GameObject btn_2;
    /// Called when the scene is loaded
    void Start() {

        // Search for all Children from this ImageTarget with type VirtualButtonBehaviour
        VirtualButtonBehaviour[] vbs = GetComponentsInChildren(); //取得所有虛擬按鈕的物件
        for (int i = 0; i < vbs.Length; ++i) {
            // Register with the virtual buttons TrackableBehaviour
            vbs[i].RegisterEventHandler(this);//註冊事件處理程序
        }

        // Find the models based on the names in the Hierarchy
model_1 = transform.Find("model1").gameObject;//取得3D模型物件
model_2 = transform.Find("model2").gameObject;

btn_1 = transform.Find("hs1").gameObject; //取得按鈕上的特效物件,用特效物件來表示按鈕可以被按下
btn_2 = transform.Find("hs2").gameObject;
        // We don't want to show Jin during the startup
model_1.SetActive(false);
model_2.SetActive(false);
btn_1.SetActive(true);
btn_2.SetActive(true);
    }

    ///



    /// Called when the virtual button has just been pressed:
    ///
    public void OnButtonPressed(VirtualButtonAbstractBehaviour vb) {
//Debug.Log(vb.VirtualButtonName);
Debug.Log("Button pressed!");
     
switch(vb.VirtualButtonName) { //判斷按下那一個按鈕
case "btnLeft":
btn_1.SetActive(false);
btn_2.SetActive(true);
model_1.SetActive(false);
model_2.SetActive(true);
                    break;
case "btnRight":
btn_1.SetActive(true);
btn_2.SetActive(false);
model_1.SetActive(true);
model_2.SetActive(false);
           break;
         //   default:
         //       throw new UnityException("Button not supported: " + vb.VirtualButtonName);
         //           break;
        }
     
    }

    /// Called when the virtual button has just been released:
    public void OnButtonReleased(VirtualButtonAbstractBehaviour vb) {
Debug.Log("Button released!");
}
}



1 則留言: