AR——作業與練習

1、 圖片識別與建模

下載並使用Vuforia

到官網註冊賬號,註冊完成後轉到Develop頁面:

註冊一個License Key:

創建數據庫:

向數據庫中加入Target:

加入成功後查看圖片及相關信息:

將創建好的數據庫unity package文件下載到本地。

打開Unity,在PlayerSetting中下載Vuforia的擴展包

下載完成後重啓Unity,並向項目中添加AR Camera,並刪去原來的Main Camera

將之前註冊的License Key複製到相應的項下面,然後將下載的數據庫package文件導入項目中

新建一個Image Target,將Image Target Behaviour中Type設置爲Predefined,然後匹配相應的數據庫和Target

向Image Target中加入一個子對象Cube,然後運行項目,在攝像頭範圍內設置好目標圖片並調整合適的角度,就可以看到生成了一個AR的立方體:

2、 虛擬按鍵小遊戲

新建一個Virtual Button組件,並添加一個子對象plane使得按鈕可見

調整按鈕大小和位置:

寫一個簡單的腳本,然後掛載到Image Target組件上:

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

public class ButtonEvent : MonoBehaviour, IVirtualButtonEventHandler
{
    public VirtualButtonBehaviour[] vbs;
    public GameObject cube;
    public GameObject button;
    public int index;
    public Color[] colors;

    void initColors()
    {
        colors = new Color[5];
        colors[0] = Color.gray;
        colors[1] = Color.red;
        colors[2] = Color.yellow;
        colors[3] = Color.blue;
        colors[4] = Color.green;
    }

    void Start()
    {
        vbs = GetComponentsInChildren<VirtualButtonBehaviour>();
        for (int i = 0; i < vbs.Length; i++)
        {
            vbs[i].RegisterEventHandler(this);
        }
        initColors();
        index = 0;
    }


    public void OnButtonPressed(VirtualButtonBehaviour vb)
    {
        index++;
        if (index == 4)
            index = 0;
        button.GetComponent<MeshRenderer>().material.color = Color.red;
        cube.GetComponent<Renderer>().material.color = colors[index];

    }

    public void OnButtonReleased(VirtualButtonBehaviour vb)
    {
        button.GetComponent<MeshRenderer>().material.color = Color.white;
    }

}


該腳本實現了點擊按鈕改變立方體顏色的功能,在Start中對變量進行初始化,並且獲取到vitrualButton的相關屬性,對IVuforiaButtonEventHandler接口進行實現,以對虛擬按鈕的按下與釋放事件進行監聽並處理,掛載到ImageTarget下並對變量進行指定。當檢測到按鈕被按下時,改變按鈕顏色爲紅色,並且相應改變立方體顏色;當按鈕被釋放時,恢復按鈕顏色爲白色。

運行效果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章