AR开发实战Vuforia项目之神偷奶爸(自定义识别)

一、主要框架

二、关键脚本

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;

    //定义协程扫描利用时间
    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;
    // 新定义的数据集添加到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("发送方法前:--------------");
        // gameObject.SendMessage("RandonGo");
        GameObject.Find("ImageTarget").SendMessage("RandonGo");
        Debug.Log("发送方法后:、、、、、、、、、、、、、、、、、");

        //按下 按钮隐藏
      //  btn.SetActive(false);
        
        //开启协程;
        StartCoroutine("FadeGameObject");

    }

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

    }


    /// <summary>
    /// 隐藏按钮的协程
    /// </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;



        //定义标志位 用来保存分数

        private bool isTouch = false;


        //定义分数
        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))
                {
                    //累加分数
                    nowScore++;
                    //存贮分数
                    PlayerPrefs.SetFloat("score", nowScore);
                    //获取分数
                    highScore = PlayerPrefs.GetFloat("score");
                    if (highScore < nowScore)
                    {
                        highScore = nowScore;
                    }
                    scoreText.text= " nowScore  :" + nowScore + "  " + "highScore :" + highScore;

                    //点心消失
                   // OnTrackingLost();
                }
               

            }
            //执行此方法才能改变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;

            }
           
            //发现目标可以点击;
            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;

    //旋转的速度
    // public float roateSpeed;

    //添加声音组件
     // public AudioSource audio;


    void Start()
    {

    }

  
    void Update()
    {


        //旋转
       // 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("准备发送方法::::::::::::::::::");
        //    //发送不可以播放音乐的条件
        //   // 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()
    {
        //触碰的时候对焦
        //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 {

    //物体数组
    private  GameObject[] goPrefabs;

   //显示的子物体
    private GameObject go;

    //父物体
   // public GameObject goTarget;

    //下标
    private int index;

    //子物体下标
    //private int j = 0;
    void Start () {
        
        //定义好数组的范围;
        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("----------------------------------------------接受成功");
    }
}

三、展示效果

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,445评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,889评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,047评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,760评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,745评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,638评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,011评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,669评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,923评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,655评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,740评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,406评论 4 320
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,995评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,961评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,023评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,483评论 2 342

推荐阅读更多精彩内容