AR開發(fā)實(shí)戰(zhàn)Vuforia項(xiàng)目之神偷奶爸(自定義識(shí)別)

一、主要框架

二、關(guān)鍵腳本

UDTTest

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

public class UDTTest : MonoBehaviour, IUserDefinedTargetEventHandler {

    UserDefinedTargetBuildingBehaviour mTargetBuildingBehaviour;


    //把按鈕隱藏
    public GameObject btn;

    //定義協(xié)程掃描利用時(shí)間
    public float timeScan;

    // Use this for initialization
    void Start() {

        mTargetBuildingBehaviour = GetComponent<UserDefinedTargetBuildingBehaviour>();
        if (mTargetBuildingBehaviour)
        {
            mTargetBuildingBehaviour.RegisterEventHandler(this);
            Debug.Log("Registering User Defined Target event handler.");
        }

       // timeScan = 30f;
    }




    ObjectTracker mObjectTracker;
    // 新定義的數(shù)據(jù)集添加到DataSet里
    DataSet mBuiltDataSet;
    public void OnInitialized()
    {

        mObjectTracker = TrackerManager.Instance.GetTracker<ObjectTracker>();
        if (mObjectTracker != null)
        {
            mBuiltDataSet = mObjectTracker.CreateDataSet();
            mObjectTracker.ActivateDataSet(mBuiltDataSet);
        }
        // throw new NotImplementedException();
    }


    ImageTargetBuilder.FrameQuality mFrameQuality = ImageTargetBuilder.FrameQuality.FRAME_QUALITY_NONE;
    public void OnFrameQualityChanged(ImageTargetBuilder.FrameQuality frameQuality)
    {
        mFrameQuality = frameQuality;
        if (mFrameQuality == ImageTargetBuilder.FrameQuality.FRAME_QUALITY_LOW)
        {
            Debug.Log("Low camera image quality");
        }
        //throw new NotImplementedException();
    }


    int mTargetCounter;
    //聲明一個(gè)公開的ImageTargetBehaviour然后在Unity中賦值
    public ImageTargetBehaviour ImageTargetTemplate;

    public void OnNewTrackableSource(TrackableSource trackableSource)
    {
        //throw new NotImplementedException();
        mTargetCounter++;
        // Deactivates the dataset first
        mObjectTracker.DeactivateDataSet(mBuiltDataSet);

        // Destroy the oldest target if the dataset is full or the dataset
        // already contains five user-defined targets.
        if (mBuiltDataSet.HasReachedTrackableLimit() || mBuiltDataSet.GetTrackables().Count() >= 5)
        {
            IEnumerable<Trackable> trackables = mBuiltDataSet.GetTrackables();
            Trackable oldest = null;
            foreach (Trackable trackable in trackables)
            {
                if (oldest == null || trackable.ID < oldest.ID)
                    oldest = trackable;
            }

            if (oldest != null)
            {
                Debug.Log("Destroying oldest trackable in UDT dataset: " + oldest.Name);
                mBuiltDataSet.Destroy(oldest, true);
            }
        }

        // Get predefined trackable and instantiate it
        ImageTargetBehaviour imageTargetCopy = (ImageTargetBehaviour)Instantiate(ImageTargetTemplate);
        imageTargetCopy.gameObject.name = "UserDefinedTarget-" + mTargetCounter;

        // Add the duplicated trackable to the data set and activate it
        mBuiltDataSet.CreateTrackable(trackableSource, imageTargetCopy.gameObject);

        // Activate the dataset again
        mObjectTracker.ActivateDataSet(mBuiltDataSet);
    }


    public void BuildNewTarget()
    {
        mTargetBuildingBehaviour.BuildNewTarget("test", 10);

        Debug.Log("發(fā)送方法前:--------------");
        // gameObject.SendMessage("RandonGo");
        GameObject.Find("ImageTarget").SendMessage("RandonGo");
        Debug.Log("發(fā)送方法后:、、、、、、、、、、、、、、、、、");

        //按下 按鈕隱藏
      //  btn.SetActive(false);
        
        //開啟協(xié)程;
        StartCoroutine("FadeGameObject");

    }

    // Update is called once per frame
    void Update() {

    }


    /// <summary>
    /// 隱藏按鈕的協(xié)程
    /// </summary>
    /// <returns></returns>
    IEnumerator FadeGameObject() {

        //只能啟用20s,然后隱藏按鈕 不能再用
        yield return new  WaitForSeconds(timeScan);
        btn.SetActive(false);

    }
}

DefaultTrackableEventHandler

/*==============================================================================
Copyright (c) 2010-2014 Qualcomm Connected Experiences, Inc.
All Rights Reserved.
Confidential and Proprietary - Protected under copyright and other laws.
==============================================================================*/

using UnityEngine;
using UnityEngine.UI;

namespace Vuforia
{
    /// <summary>
    /// A custom handler that implements the ITrackableEventHandler interface.
    /// </summary>
    public class DefaultTrackableEventHandler : MonoBehaviour,
                                                ITrackableEventHandler
    {
        //添加聲音組件
        public AudioSource audio;
        //添加背景聲效
        public AudioSource audioBg;



        //定義標(biāo)志位 用來保存分?jǐn)?shù)

        private bool isTouch = false;


        //定義分?jǐn)?shù)
        private float nowScore=0;
        private float highScore;

        //text 持有引用
        public Text scoreText;

        //定義一個(gè)標(biāo)志位判斷是否可以播放寶物的聲音
        private bool playMusic = true;
       

        #region PRIVATE_MEMBER_VARIABLES
 
        private TrackableBehaviour mTrackableBehaviour;
    
        #endregion // PRIVATE_MEMBER_VARIABLES



        #region UNTIY_MONOBEHAVIOUR_METHODS
    
        void Start()
        {
            mTrackableBehaviour = GetComponent<TrackableBehaviour>();
            if (mTrackableBehaviour)
            {
                mTrackableBehaviour.RegisterTrackableEventHandler(this);
            }
        }

        #endregion // UNTIY_MONOBEHAVIOUR_METHODS

        void Update() {

            if (isTouch)
            {
                if (Input.GetMouseButtonDown(0))
                {
                    //累加分?jǐn)?shù)
                    nowScore++;
                    //存貯分?jǐn)?shù)
                    PlayerPrefs.SetFloat("score", nowScore);
                    //獲取分?jǐn)?shù)
                    highScore = PlayerPrefs.GetFloat("score");
                    if (highScore < nowScore)
                    {
                        highScore = nowScore;
                    }
                    scoreText.text= " nowScore  :" + nowScore + "  " + "highScore :" + highScore;

                    //點(diǎn)心消失
                   // OnTrackingLost();
                }
               

            }
            //執(zhí)行此方法才能改變bool值;
           // NotPlayMusic();
        }

        #region PUBLIC_METHODS

        /// <summary>
        /// Implementation of the ITrackableEventHandler function called when the
        /// tracking state changes.
        /// </summary>
        public void OnTrackableStateChanged(
                                        TrackableBehaviour.Status previousStatus,
                                        TrackableBehaviour.Status newStatus)
        {
            if (newStatus == TrackableBehaviour.Status.DETECTED ||
                newStatus == TrackableBehaviour.Status.TRACKED ||
                newStatus == TrackableBehaviour.Status.EXTENDED_TRACKED)
            {
                OnTrackingFound();
                
              
            }
            else
            {
                OnTrackingLost();
      

            }
        }

        #endregion // PUBLIC_METHODS



        #region PRIVATE_METHODS


        private void OnTrackingFound()
        {
            Renderer[] rendererComponents = GetComponentsInChildren<Renderer>(true);
            Collider[] colliderComponents = GetComponentsInChildren<Collider>(true);

            // Enable rendering:
            foreach (Renderer component in rendererComponents)
            {
                component.enabled = true;
            }

            // Enable colliders:
            foreach (Collider component in colliderComponents)
            {
                component.enabled = true;
            }

            //背景音樂暫停
            if (audioBg.isPlaying)
            {
                audioBg.PlayDelayed(2f);
            }

            //音樂播放  滿足條件才播放;
            if (!audio.isPlaying)
            {
                audio.Play();
                //播放一次就不要再播了;
               // playMusic = false;

            }
           
            //發(fā)現(xiàn)目標(biāo)可以點(diǎn)擊;
            isTouch = true;

            Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " found");

        
        }


        private void OnTrackingLost()
        {
            if (audio != null)
            {
                //音樂暫停
                if (audio.isPlaying)
                {
                    audio.Pause();
                }

                //背景音樂播放;
                if (!audioBg.isPlaying)
                {
                    audioBg.Play();
                }
            }




            Renderer[] rendererComponents = GetComponentsInChildren<Renderer>(true);
            Collider[] colliderComponents = GetComponentsInChildren<Collider>(true);

            // Disable rendering:
            foreach (Renderer component in rendererComponents)
            {
                component.enabled = false;
            }

            // Disable colliders:
            foreach (Collider component in colliderComponents)
            {
                component.enabled = false;
            }

            //目標(biāo)丟失點(diǎn)擊無效
            isTouch = false;
            Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " lost");
        }

        #endregion // PRIVATE_METHODS

    /// <summary>
    /// 音樂不再播放
    /// </summary>
        //public  void NotPlayMusic (){

        //    playMusic = false;
        //    Debug.Log(playMusic.ToString());
        //}

    }
}

AnimationScript

using UnityEngine;
using System.Collections;

public class AnimationScript : MonoBehaviour
{

    public bool isAnimated = false;

    public bool isRotating = false;
    public bool isFloating = false;
    public bool isScaling = false;

    public Vector3 rotationAngle;
    public float rotationSpeed;

    public float floatSpeed;
    private bool goingUp = true;
    public float floatRate;
    private float floatTimer;

    public Vector3 startScale;
    public Vector3 endScale;

    private bool scalingUp = true;
    public float scaleSpeed;
    public float scaleRate;
    private float scaleTimer;

    //旋轉(zhuǎn)的速度
    // public float roateSpeed;

    //添加聲音組件
     // public AudioSource audio;


    void Start()
    {

    }

  
    void Update()
    {


        //旋轉(zhuǎn)
       // gameObject.transform.Rotate(Vector3.forward* Time.deltaTime*roateSpeed);

        if (isAnimated)
        {
            if (isRotating)
            {
                transform.Rotate(rotationAngle * rotationSpeed * Time.deltaTime);
            }

            if (isFloating)
            {
                floatTimer += Time.deltaTime;
                Vector3 moveDir = new Vector3(0.0f, 0.0f, floatSpeed);
                transform.Translate(moveDir);

                if (goingUp && floatTimer >= floatRate)
                {
                    goingUp = false;
                    floatTimer = 0;
                    floatSpeed = -floatSpeed;
                }

                else if (!goingUp && floatTimer >= floatRate)
                {
                    goingUp = true;
                    floatTimer = 0;
                    floatSpeed = +floatSpeed;
                }
            }

            if (isScaling)
            {
                scaleTimer += Time.deltaTime;

                if (scalingUp)
                {
                    transform.localScale = Vector3.Lerp(transform.localScale, endScale, scaleSpeed * Time.deltaTime);
                }
                else if (!scalingUp)
                {
                    transform.localScale = Vector3.Lerp(transform.localScale, startScale, scaleSpeed * Time.deltaTime);
                }

                if (scaleTimer >= scaleRate)
                {
                    if (scalingUp) { scalingUp = false; }
                    else if (!scalingUp) { scalingUp = true; }
                    scaleTimer = 0;
                }
            }
        }

        ////顯示的時(shí)候就播放
        //if (gameObject.active == true)
        //{
        //    Debug.Log("準(zhǔn)備播放音樂+++++++++++++++++");
        //        audio.Play();
        //    Debug.Log("播放完畢-------");
        //}


        //點(diǎn)擊了就destory

        //if (Input.GetMouseButtonDown(0))
        //{
        //    //Debug.Log("準(zhǔn)備發(fā)送方法::::::::::::::::::");
        //    //發(fā)送不可以播放音樂的條件
        //   // GameObject.FindGameObjectWithTag("Player").SendMessage("NotPlayMusic");

        //    //Debug.Log("放松方法完畢~~~~~~~~~~~~~~~~~");

        //        if (gameObject.active==true)
        //        {
        //            Destroy(gameObject);
        //        }                     
        //}
    }


}


CameraMode

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


/// <summary>
/// 自動(dòng)對焦功能
/// </summary>
public class CameraMode : MonoBehaviour
{


    void Start()
    {
        //一開始自動(dòng)對焦
        //Vuforia.CameraDevice.Instance.SetFocusMode(Vuforia.CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
        VuforiaARController.Instance.RegisterVuforiaStartedCallback(OnVuforiaStarted);
        VuforiaARController.Instance.RegisterOnPauseCallback(OnPaused);
    }

    void Update()
    {
        //觸碰的時(shí)候?qū)?        //if (Input.GetMouseButtonUp(0))
        //{
        //    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        //    {
        //        Vuforia.CameraDevice.Instance.SetFocusMode(Vuforia.CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
        //    }
        //}

    }
    private void OnVuforiaStarted()
    {
        CameraDevice.Instance.SetFocusMode(
        CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
    }

    private void OnPaused(bool paused)
    {
        if (!paused)
        { // resumed
            // Set again autofocus mode when app is resumed
            CameraDevice.Instance.SetFocusMode(
            CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
        }
    }

}

RandonInt

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

public class RandonInt : MonoBehaviour {

    //物體數(shù)組
    private  GameObject[] goPrefabs;

   //顯示的子物體
    private GameObject go;

    //父物體
   // public GameObject goTarget;

    //下標(biāo)
    private int index;

    //子物體下標(biāo)
    //private int j = 0;
    void Start () {
        
        //定義好數(shù)組的范圍;
        goPrefabs = new GameObject[transform.childCount];

        //獲取下面所有子物體

        //第一種方式
        //foreach (Transform child in gameObject.transform)
        //{
        //    Debug.Log(child.name);
        //    //獲取所有字物體;
        //    goPrefabs[j] = child.gameObject as GameObject;
        //    j++;
        //}


        //第二種方式
        for (int i = 0; i < transform.childCount; i++)
        {
            goPrefabs[i] = transform.GetChild(i).gameObject;
        }
    }
    
    
    void Update () { 
        
    }
    /// <summary>
    /// 隨機(jī)方法
    /// </summary>
    public void RandonGo()
    {
        Debug.Log("接受方法=+++++++++++++");
        index = Random.Range(0, transform.childCount);
     
        for (int i = 0; i <goPrefabs.Length; i++)
        {
            if (goPrefabs[i] != null)
            {
                if (index==i)
                {
                    goPrefabs[i].SetActive(true);
                }
                else
                {             
                    goPrefabs[i].SetActive(false);            
                }
            }
        }
        go = goPrefabs[index];
        // go.SetActive(true);
        //if (go!=null)
        //{
           // go.transform.parent = goTarget.transform;
        //}

        Debug.Log("----------------------------------------------接受成功");
    }
}

三、展示效果

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容