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

一袖瞻、主要框架

二营密、關(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é)程掃描利用時間
    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;
    //聲明一個公開的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;



        //定義標志位 用來保存分數(shù)

        private bool isTouch = false;


        //定義分數(shù)
        private float nowScore=0;
        private float highScore;

        //text 持有引用
        public Text scoreText;

        //定義一個標志位判斷是否可以播放寶物的聲音
        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))
                {
                    //累加分數(shù)
                    nowScore++;
                    //存貯分數(shù)
                    PlayerPrefs.SetFloat("score", nowScore);
                    //獲取分數(shù)
                    highScore = PlayerPrefs.GetFloat("score");
                    if (highScore < nowScore)
                    {
                        highScore = nowScore;
                    }
                    scoreText.text= " nowScore  :" + nowScore + "  " + "highScore :" + highScore;

                    //點心消失
                   // 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)目標可以點擊恋腕;
            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;
            }

            //目標丟失點擊無效
            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;
                }
            }
        }

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


        //點擊了就destory

        //if (Input.GetMouseButtonDown(0))
        //{
        //    //Debug.Log("準備發(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>
/// 自動對焦功能
/// </summary>
public class CameraMode : MonoBehaviour
{


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

    void Update()
    {
        //觸碰的時候?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;

    //下標
    private int index;

    //子物體下標
    //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>
    /// 隨機方法
    /// </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)系作者
  • 序言:七十年代末获高,一起剝皮案震驚了整個濱河市哈肖,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌谋减,老刑警劉巖牡彻,帶你破解...
    沈念sama閱讀 207,113評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異出爹,居然都是意外死亡庄吼,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,644評論 2 381
  • 文/潘曉璐 我一進店門严就,熙熙樓的掌柜王于貴愁眉苦臉地迎上來总寻,“玉大人,你說我怎么就攤上這事梢为〗バ校” “怎么了?”我有些...
    開封第一講書人閱讀 153,340評論 0 344
  • 文/不壞的土叔 我叫張陵铸董,是天一觀的道長祟印。 經(jīng)常有香客問我,道長粟害,這世上最難降的妖魔是什么蕴忆? 我笑而不...
    開封第一講書人閱讀 55,449評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮悲幅,結(jié)果婚禮上套鹅,老公的妹妹穿的比我還像新娘。我一直安慰自己汰具,他們只是感情好卓鹿,可當(dāng)我...
    茶點故事閱讀 64,445評論 5 374
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著留荔,像睡著了一般吟孙。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,166評論 1 284
  • 那天杰妓,我揣著相機與錄音肥隆,去河邊找鬼。 笑死稚失,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的恰聘。 我是一名探鬼主播句各,決...
    沈念sama閱讀 38,442評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼晴叨!你這毒婦竟也來了凿宾?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,105評論 0 261
  • 序言:老撾萬榮一對情侶失蹤兼蕊,失蹤者是張志新(化名)和其女友劉穎初厚,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體孙技,經(jīng)...
    沈念sama閱讀 43,601評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡产禾,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,066評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了诽嘉。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片煌抒。...
    茶點故事閱讀 38,161評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡昙沦,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出楞件,到底是詐尸還是另有隱情,我是刑警寧澤裳瘪,帶...
    沈念sama閱讀 33,792評論 4 323
  • 正文 年R本政府宣布土浸,位于F島的核電站,受9級特大地震影響彭羹,放射性物質(zhì)發(fā)生泄漏黄伊。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,351評論 3 307
  • 文/蒙蒙 一皆怕、第九天 我趴在偏房一處隱蔽的房頂上張望毅舆。 院中可真熱鬧,春花似錦愈腾、人聲如沸憋活。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,352評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽悦即。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間辜梳,已是汗流浹背粱甫。 一陣腳步聲響...
    開封第一講書人閱讀 31,584評論 1 261
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留作瞄,地道東北人茶宵。 一個月前我還...
    沈念sama閱讀 45,618評論 2 355
  • 正文 我出身青樓,卻偏偏與公主長得像宗挥,于是被迫代替她去往敵國和親乌庶。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,916評論 2 344

推薦閱讀更多精彩內(nèi)容