AR开发实战Vuforia项目之仿支付宝集五福(云识别)

一、主要框架

AR开发实战Vuforia项目之仿支付宝集五福(云识别)_第1张图片

二、云识别

AR开发实战Vuforia项目之仿支付宝集五福(云识别)_第2张图片

三、加载资源

四、关键脚本

AndroidStatusBar

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

/**
 * @author zeh fernando
 * @modify MemoryC_2017-02-05
 */
class AndroidStatusBar
{

    /**
 * Manipulates the system application chrome to change the way the status bar and navigation bar work
 *POSTS FROM :
 *http://zehfernando.com/2015/unity-tidbits-changing-the-visibility-of-androids-navigation-and-status-bars-and-implementing-immersive-mode/
 *[url=http://www.manew.com/thread-100054-1-1.html]http://www.manew.com/thread-100054-1-1.html[/url]
 * References:
 * . http://developer.android.com/reference/android/view/View.html#setSystemUiVisibility(int)
 * . http://forum.unity3d.com/threads/calling-setsystemuivisibility.139445/#post-952946
 * . http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_LAYOUT_IN_SCREEN
 **/

    // Enums
    public enum States
    {
        Unknown,
        Visible,
        VisibleOverContent,
        TranslucentOverContent,
        Hidden,
    }

    // Constants
    private const uint DEFAULT_BACKGROUND_COLOR = 0xff000000;

#if UNITY_ANDROID
    // Original Android flags
    private const int VIEW_SYSTEM_UI_FLAG_VISIBLE = 0;                                        // Added in API 14 (Android 4.0.x): Status bar visible (the default)
    private const int VIEW_SYSTEM_UI_FLAG_LOW_PROFILE = 1;                                // Added in API 14 (Android 4.0.x): Low profile for games, book readers, and video players; the status bar and/or navigation icons are dimmed out (if visible)
    private const int VIEW_SYSTEM_UI_FLAG_HIDE_NAVIGATION = 2;                        // Added in API 14 (Android 4.0.x): Hides all navigation. Cleared when theres any user interaction.
    private const int VIEW_SYSTEM_UI_FLAG_FULLSCREEN = 4;                                // Added in API 16 (Android 4.1.x): Hides status bar. Does nothing in Unity (already hidden if "status bar hidden" is checked)
    private const int VIEW_SYSTEM_UI_FLAG_LAYOUT_STABLE = 256;                        // Added in API 16 (Android 4.1.x): ?
    private const int VIEW_SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 512;        // Added in API 16 (Android 4.1.x): like HIDE_NAVIGATION, but for layouts? it causes the layout to be drawn like that, even if the whole view isn't (to avoid artifacts in animation)
    private const int VIEW_SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 1024;                // Added in API 16 (Android 4.1.x): like FULLSCREEN, but for layouts? it causes the layout to be drawn like that, even if the whole view isn't (to avoid artifacts in animation)
    private const int VIEW_SYSTEM_UI_FLAG_IMMERSIVE = 2048;                                // Added in API 19 (Android 4.4): like HIDE_NAVIGATION, but interactive (it's a modifier for HIDE_NAVIGATION, needs to be used with it)
    private const int VIEW_SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 4096;                // Added in API 19 (Android 4.4): tells that HIDE_NAVIGATION and FULSCREEN are interactive (also just a modifier)

    private static int WINDOW_FLAG_FULLSCREEN = 0x00000400;
    private static int WINDOW_FLAG_FORCE_NOT_FULLSCREEN = 0x00000800;
    private static int WINDOW_FLAG_LAYOUT_IN_SCREEN = 0x00000100;
    private static int WINDOW_FLAG_TRANSLUCENT_STATUS = 0x04000000;
    private static int WINDOW_FLAG_TRANSLUCENT_NAVIGATION = 0x08000000;
    private static int WINDOW_FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS = -2147483648; // 0x80000000; // Added in API 21 (Android 5.0): tells the Window is responsible for drawing the background for the system bars. If set, the system bars are drawn with a transparent background and the corresponding areas in this window are filled with the colors specified in getStatusBarColor() and getNavigationBarColor()

    // Current values
    private static int systemUiVisibilityValue;
    private static int flagsValue;
#endif

    // Properties
    private static States _statusBarState;
    //        private static States _navigationBarState;

    private static uint _statusBarColor = DEFAULT_BACKGROUND_COLOR;
    //        private static uint _navigationBarColor = DEFAULT_BACKGROUND_COLOR;

    private static bool _isStatusBarTranslucent; // Just so we know whether its translucent when hidden or not
                                                 //        private static bool _isNavigationBarTranslucent;

    private static bool _dimmed;
    // ================================================================================================================
    // INTERNAL INTERFACE ---------------------------------------------------------------------------------------------

    static AndroidStatusBar()
    {
        applyUIStates();
        applyUIColors();
    }

    private static void applyUIStates()
    {
#if UNITY_ANDROID && !UNITY_EDITOR
 
                int newFlagsValue = 0;
                int newSystemUiVisibilityValue = 0;
 
                // Apply dim values
                if (_dimmed) newSystemUiVisibilityValue |= VIEW_SYSTEM_UI_FLAG_LOW_PROFILE;
 
                // Apply color values
//                if (_navigationBarColor != DEFAULT_BACKGROUND_COLOR || _statusBarColor != DEFAULT_BACKGROUND_COLOR) newFlagsValue |= WINDOW_FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
                if (_statusBarColor != DEFAULT_BACKGROUND_COLOR) newFlagsValue |= WINDOW_FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
 
                // Apply status bar values
                switch (_statusBarState) {
                case States.Visible:
                _isStatusBarTranslucent = false;
                newFlagsValue |= WINDOW_FLAG_FORCE_NOT_FULLSCREEN;
                break;
                case States.VisibleOverContent:
                _isStatusBarTranslucent = false;
                newFlagsValue |= WINDOW_FLAG_FORCE_NOT_FULLSCREEN | WINDOW_FLAG_LAYOUT_IN_SCREEN;
                newSystemUiVisibilityValue |= VIEW_SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
                break;
                case States.TranslucentOverContent:
                _isStatusBarTranslucent = true;
                newFlagsValue |= WINDOW_FLAG_FORCE_NOT_FULLSCREEN | WINDOW_FLAG_LAYOUT_IN_SCREEN | WINDOW_FLAG_TRANSLUCENT_STATUS;
                newSystemUiVisibilityValue |= VIEW_SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
                break;
                case States.Hidden:
                newFlagsValue |= WINDOW_FLAG_FULLSCREEN | WINDOW_FLAG_LAYOUT_IN_SCREEN;
                if (_isStatusBarTranslucent) newFlagsValue |= WINDOW_FLAG_TRANSLUCENT_STATUS;
                break;
                }
 
                // Applies navigation values
                /*
                switch (_navigationBarState) {
                case States.Visible:
                _isNavigationBarTranslucent = false;
                newSystemUiVisibilityValue |= VIEW_SYSTEM_UI_FLAG_LAYOUT_STABLE;
                break;
                case States.VisibleOverContent:
                // TODO: Side effect: forces status bar over content if set to VISIBLE
                _isNavigationBarTranslucent = false;
                newSystemUiVisibilityValue |= VIEW_SYSTEM_UI_FLAG_LAYOUT_STABLE | VIEW_SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
                break;
                case States.TranslucentOverContent:
                // TODO: Side effect: forces status bar over content if set to VISIBLE
                _isNavigationBarTranslucent = true;
                newFlagsValue |= WINDOW_FLAG_TRANSLUCENT_NAVIGATION;
                newSystemUiVisibilityValue |= VIEW_SYSTEM_UI_FLAG_LAYOUT_STABLE | VIEW_SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
                break;
                case States.Hidden:
                newSystemUiVisibilityValue |= VIEW_SYSTEM_UI_FLAG_FULLSCREEN | VIEW_SYSTEM_UI_FLAG_HIDE_NAVIGATION | VIEW_SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
                if (_isNavigationBarTranslucent) newFlagsValue |= WINDOW_FLAG_TRANSLUCENT_NAVIGATION;
                break;
                }
                */
                if (Screen.fullScreen) Screen.fullScreen = false;
 
                // Applies everything natively
                setFlags(newFlagsValue);
                setSystemUiVisibility(newSystemUiVisibilityValue);
#endif
    }

    private static void applyUIColors()
    {
#if UNITY_ANDROID && !UNITY_EDITOR
                runOnAndroidUiThread(applyUIColorsAndroidInThread);
#endif
    }

#if UNITY_ANDROID
    private static void runOnAndroidUiThread(Action target)
    {
        using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            using (var activity = unityPlayer.GetStatic("currentActivity"))
            {
                activity.Call("runOnUiThread", new AndroidJavaRunnable(target));
            }
        }
    }

    private static void setSystemUiVisibility(int value)
    {
        if (systemUiVisibilityValue != value)
        {
            systemUiVisibilityValue = value;
            runOnAndroidUiThread(setSystemUiVisibilityInThread);
        }
    }

    private static void setSystemUiVisibilityInThread()
    {
        //Debug.Log("SYSTEM FLAGS: " + systemUiVisibilityValue);
        using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            using (var activity = unityPlayer.GetStatic("currentActivity"))
            {
                using (var window = activity.Call("getWindow"))
                {
                    using (var view = window.Call("getDecorView"))
                    {
                        view.Call("setSystemUiVisibility", systemUiVisibilityValue);
                    }
                }
            }
        }
    }

    private static void setFlags(int value)
    {
        if (flagsValue != value)
        {
            flagsValue = value;
            runOnAndroidUiThread(setFlagsInThread);
        }
    }

    private static void setFlagsInThread()
    {
        //Debug.Log("FLAGS: " + flagsValue);
        using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            using (var activity = unityPlayer.GetStatic("currentActivity"))
            {
                using (var window = activity.Call("getWindow"))
                {
                    window.Call("setFlags", flagsValue, -1); // (int)0x7FFFFFFF
                }
            }
        }
    }

    private static void applyUIColorsAndroidInThread()
    {
        using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            using (var activity = unityPlayer.GetStatic("currentActivity"))
            {
                using (var window = activity.Call("getWindow"))
                {
                    //Debug.Log("Colors SET: " + _statusBarColor);
                    window.Call("setStatusBarColor", unchecked((int)_statusBarColor));
                    //                                        window.Call("setNavigationBarColor", unchecked((int)_navigationBarColor));
                }
            }
        }
    }

#endif

    // ================================================================================================================
    // ACCESSOR INTERFACE ---------------------------------------------------------------------------------------------
    /*
    public static States navigationBarState {
            get { return _navigationBarState; }
            set {
                    if (_navigationBarState != value) {
                            _navigationBarState = value;
                            applyUIStates();
                    }
            }
    }
*/
    public static States statusBarState
    {
        get { return _statusBarState; }
        set
        {
            if (_statusBarState != value)
            {
                _statusBarState = value;
                applyUIStates();
            }
        }
    }

    public static bool dimmed
    {
        get { return _dimmed; }
        set
        {
            if (_dimmed != value)
            {
                _dimmed = value;
                applyUIStates();
            }
        }
    }

    public static uint statusBarColor
    {
        get { return _statusBarColor; }
        set
        {
            if (_statusBarColor != value)
            {
                _statusBarColor = value;
                applyUIColors();
                applyUIStates();
            }
        }
    }
    /*
    public static uint navigationBarColor {
            get { return _navigationBarColor; }
            set {
                    if (_navigationBarColor != value) {
                            _navigationBarColor = value;
                            applyUIColors();
                            applyUIStates();
                    }
            }
    }
    */
}

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;

    // Use this for initialization
    void Start () {
    
    }
    
    // Update is called once per frame
    void Update () {

       
        
        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;
                }
            }
        }
    }
}

AssetUtil

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/// 
/// 加载进度
/// 
public delegate void LoadProgress(string bundleName, float progress);

/// 
/// 加载完成时候的调用
/// 
public delegate void LoadComplete(string bundleName);

/// 
/// 加载assetbundle的回调
/// 
public delegate void LoadAssetBundleCallback(string sceneName, string bundleName);

public class AssetUtil
{

}


CameraMode

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


/// 
/// 自动对焦功能
/// 
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);
        }
    }
   
}


CloudRecoManage

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Vuforia;  //添加引用

public class CloudRecoManage : MonoBehaviour, ICloudRecoEventHandler //继承接口并实现
{
    //声明两个变量
    private GameObject mImageTarget;        //ImageTarget的Object对象  
    private ObjectTracker mObjectTracker;   //跟踪器变量  (个人理解)识别出的物体就靠它才能跟着图片移动

    //需要保留Start方法 初始化用 
    void Start()
    {
        //把这个脚本和CloudRecoBehaviour云识别进行绑定   --不然脚本怎么知道哪个云识别模块给这个脚本提供识别信息呢~

        //获取到场景中的云识别组件   因为我们只有一个云识别 所以不用担心冲突
        CloudRecoBehaviour cloudRecoBehaviour = FindObjectOfType();

        //把云识别和脚本绑定
        cloudRecoBehaviour.RegisterEventHandler(this);
    }

    public void OnInitError(TargetFinder.InitState initError)
    {
        //初始化错误
        Debug.Log("初始化错误:" + initError);
    }

    public void OnInitialized()
    {
        //初始化
        Debug.Log("初始化开始");

        //获取ImageTarget的Object对象  
        mImageTarget = FindObjectOfType().gameObject;

        //获取追踪管理器
        mObjectTracker = TrackerManager.Instance.GetTracker();
    }

    public void OnNewSearchResult(TargetFinder.TargetSearchResult targetSearchResult)
    {
        //搜索到新的目标
        Debug.Log("搜索到目标:" + targetSearchResult.TargetName);
        if (targetSearchResult.TargetSize <= 1)     //判断targetSearchResult是否符合要求
            return;
        //搜索到新的目标关闭ClearTrackables
        mObjectTracker.TargetFinder.ClearTrackables(false);

        //启动追踪 很简单 两个参数1、识别到的目标 2、生成的物体   两个同步运动
        mObjectTracker.TargetFinder.EnableTracking(targetSearchResult, mImageTarget);
    }

    public void OnStateChanged(bool scanning)
    {
        //云识别状态改变
        Debug.Log("云识别状态:" + scanning);
        //云识别开启时关闭ClearTrackables
        if (scanning)
            mObjectTracker.TargetFinder.ClearTrackables(false);
    }

    public void OnUpdateError(TargetFinder.UpdateState updateError)
    {
        //云识别错误
        Debug.Log("云识别错误:" + updateError);

    }
}


Gradient

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

[AddComponentMenu("UI/Effects/Gradient")]
public class Gradient : BaseMeshEffect
{
    [SerializeField]
    private Color32 topColor = Color.white;

    [SerializeField]
    private Color32 bottomColor = Color.black;

    [SerializeField]
    private float PaddingY = 0;

    public override void ModifyMesh(VertexHelper vh)
    {
        if (!IsActive())
        {
            return;
        }

        var vertexList = new List();
        vh.GetUIVertexStream(vertexList);
        int count = vertexList.Count;

        //0值代表开始的字符数
        ApplyGradient(vertexList, 0, count);
        vh.Clear();
        vh.AddUIVertexTriangleStream(vertexList);
    }

    private void ApplyGradient(List vertexList, int start, int end)
    {
        float bottomY = vertexList[0].position.y;
        float topY = vertexList[0].position.y;
        for (int i = start; i < end; ++i)
        {
            float y = vertexList[i].position.y;
            if (y > topY)
            {
                topY = y;
            }
            else if (y < bottomY)
            {
                bottomY = y;
            }
        }

        float uiElementHeight = topY - bottomY;
        for (int i = start; i < end; ++i)
        {
            UIVertex uiVertex = vertexList[i];
            uiVertex.color = Color32.Lerp(bottomColor, topColor, (uiVertex.position.y - bottomY) / uiElementHeight- PaddingY);
            vertexList[i] = uiVertex;
        }
    }
}

LightEffect

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

public class LightEffect : MonoBehaviour {
    //定义一个时间长度
    public float duration = 1.0F;
    //定义一个红色(颜色自取)
    public Color colorRed = Color.red;
    //定义一个蓝色(颜色自取)
    public Color colorBlue = Color.blue;

    // Update is called once per frame
    void Update()
    {
        float phi = Time.time / duration * 2 * Mathf.PI;

        //使用数学函数来实现闪光灯效果
        float amplitude = Mathf.Cos(phi) * 0.5F + 0.5F;
        // light.intensity = amplitude;
       gameObject.GetComponent().intensity = amplitude;
        float x = Mathf.PingPong(Time.time, duration) / duration;
       // light.color = Color.Lerp(colorRed, colorBlue, x);
       gameObject.GetComponent().color = Color.Lerp(colorRed, colorBlue, x);


    }
}

MyTrackableEventHandler

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

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

namespace Vuforia
{
    /// 
    /// A custom handler that implements the ITrackableEventHandler interface.
    /// 
    public class MyTrackableEventHandler : MonoBehaviour,
                                                ITrackableEventHandler
    {
        #region PRIVATE_MEMBER_VARIABLES

        private TrackableBehaviour mTrackableBehaviour;


        //公开物体的应用;
        //public  GameObject scan;
        //public GameObject BtnStart;
        //public GameObject Btnagain;

        private  GameObject scan;
        private  GameObject BtnStart;
      //  private  GameObject Btnagain;
        private GameObject BtnEnd;

        //对红包进行引用;
        private GameObject hongBao;

        //判断是否收了红包;
        private bool isShou;


        //添加音乐的数组
        public  AudioSource  [] mAudioSorce;
       
        private AudioSource m1;
        private AudioSource m2;
        private AudioSource m3;

        //定义一个计时器
        // private float timePlay ;


        //声明一个特效
       // public  GameObject eff;

        // 用于获取各种模型
        public GameObject[] models;
       // TrackableBehaviour trackableBehaviour;
        #endregion // PRIVATE_MEMBER_VARIABLES





        #region UNTIY_MONOBEHAVIOUR_METHODS

        void Start()
        {
            //----------------------------------------------
          //  trackableBehaviour =GetComponent();
           // if (trackableBehaviour)
           // {
             //   trackableBehaviour.RegisterTrackableEventHandler(this);
           // }

            //-----------------------------------------------

            scan = GameObject.FindGameObjectWithTag("Scan");
            BtnStart = GameObject.FindGameObjectWithTag("Start");
           // Btnagain = GameObject.FindGameObjectWithTag("Again");
            BtnEnd = GameObject.FindGameObjectWithTag("End");

            mTrackableBehaviour = GetComponent();
            if (mTrackableBehaviour)
            {
                mTrackableBehaviour.RegisterTrackableEventHandler(this);
            }

            //一开始设置引用;
           // scan = GameObject.FindGameObjectWithTag("Scan");
            scan.SetActive(true);
            BtnStart.SetActive(true);
           // Btnagain.SetActive(false);

            //默认是没有收红包
            isShou = false;

            //对音乐进行赋值;
            // mAudioSorce =GameObject.FindGameObjectsWithTag("Music") ;

            // m1= mAudioSorce[0].GetComponent();
            m1 = mAudioSorce[0];
            //m1.Play();
            Debug.Log("播了没有!!!!!!!!!");
            m1.volume = 1;
            Debug.Log("声音没有!!!!!!!!!!!");

            // m2= mAudioSorce[1].GetComponent();
            m2 = mAudioSorce[1];
            m3 = mAudioSorce[2];

            //特效引用
           // eff = GameObject.FindGameObjectWithTag("Eff");
            //特效隐藏
            //if (eff!=null)
            //{
            //    eff.SetActive(false);
            //}
          
        }

        #endregion // UNTIY_MONOBEHAVIOUR_METHODS


        void Update() {


            //if (isShou)
            //{
            //    //timePlay++;
            //    //if (timePlay>=m2.clip.length)
            //    //{
            //    //    //背景音乐开启;
            //    //  // m1.volume = 1;

            //    //}
            //    m1.PlayDelayed(1.5f);
            //}

            //执行被按下的方法
            if (Input.GetMouseButtonDown(0))
            {
                ClickDown();
            }

            Debug.Log("屏幕被点击!!");
        }


        #region PUBLIC_METHODS

        /// 
        /// Implementation of the ITrackableEventHandler function called when the
        /// tracking state changes.
        /// 
        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(true);
            Collider[] colliderComponents = GetComponentsInChildren(true);
          //  if (!isShou)
          //  {
                //发现的时候显示按钮相关状态;
                // scan = GameObject.FindGameObjectWithTag("Scan");
                scan.SetActive(false);
                BtnStart.SetActive(false);
               // Btnagain.SetActive(true);
                BtnEnd.SetActive(false);

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

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

                //播放发现宝物的声音;
                 m2.PlayDelayed(0.5f);
                //先将音量静音 再把音乐开到最大
                m2.volume = 0;
              StartCoroutine("MusicPlay");

               m3.Play();

                //eff = GameObject.FindGameObjectWithTag("Eff");
                //显示特效
              //  eff.SetActive(true);

                //------------------------------------------------------------------------
                // 根据不同的Target的名称设置不同的模型
                if (mTrackableBehaviour.TrackableName.Equals("fu1"))
                {
                    //              ShowObject(true);
                    models[0].SetActive(true);
                    models[1].SetActive(false);
                }
                else if (mTrackableBehaviour.TrackableName.Equals("fu2"))
                {
                    //              ShowObject(false);
                    models[0].SetActive(false);
                    models[1].SetActive(true);
                }
                //------------------------------------------------------------------------
            //}
            //else
            //{
            //    scan.SetActive(true);
            //    BtnStart.SetActive(true);
            //    Btnagain.SetActive(false);
            //    BtnEnd.SetActive(true);
            //    // Enable rendering:
            //    foreach (Renderer component in rendererComponents)
            //    {
            //        component.enabled = false;
            //    }

            //    // Enable colliders:
            //    foreach (Collider component in colliderComponents)
            //    {
            //        component.enabled = false;
            //    }
            //   // eff = GameObject.FindGameObjectWithTag("Eff");
            //    //隐藏特效
            //   // eff.SetActive(false);
            //}
           

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

        

        }


        private void OnTrackingLost()
        {
            //丢失的时候显示按钮相关状态;
            // scan = GameObject.FindGameObjectWithTag("Scan");
            //scan = GameObject.FindWithTag("Scan");
            if (scan!=null)
            {
                scan.SetActive(true);
                BtnStart.SetActive(true);
               // Btnagain.SetActive(false);
                BtnEnd.SetActive(true);
            }
            
           
            Renderer[] rendererComponents = GetComponentsInChildren(true);
            Collider[] colliderComponents = GetComponentsInChildren(true);

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

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

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

           // eff = GameObject.FindGameObjectWithTag("Eff");
            //隐藏特效
           // if (eff!=null)
           // {
            //    eff.SetActive(false);
          //  }
            
        }




        #endregion // PRIVATE_METHODS


        //按键被按下的方法
        public void ClickDown()
        {
            //按键的时候显示按钮相关状态;
            //scan = GameObject.FindGameObjectWithTag("Scan");
           // scan = GameObject.FindWithTag("Scan");
            //Debug.Log(scan.name);
            scan.SetActive(true);
            BtnStart.SetActive(true);
           // Btnagain.SetActive(false);
            BtnEnd.SetActive(true);

            //按键 按下表示收了红包;
            isShou = true;

            //判断收下红包的时候背景音乐音量为0;
             m2.volume = 0;
            StartCoroutine("MusicPlay");
            //m2.PlayDelayed(0.5f);

            //播放红包的音效;
           // m1.Play();
            //开启计时;
           // timePlay = 0;

            //把红包隐藏起来
            // hongBao = GameObject.FindGameObjectWithTag("Fu");
            Renderer[] rendererComponents = GetComponentsInChildren(true);
            Collider[] colliderComponents = GetComponentsInChildren(true);

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

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

           
        }





        //开启协程
        IEnumerator MusicPlay() {

            yield return new WaitForSeconds(1f);
            //等待1秒之后再播放背景音乐
            m2.volume = 1;
        }



        //退出按钮
        public void BtnOut()
        {

            Application.Quit();
        }

       
    }
  


}


PathUtil

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

/// 
/// 路径
/// 
public class PathUtil
{
    /// 
    /// 获取assetbundle的输出目录
    /// 
    /// 
    public static string GetAssetBundleOutPath()
    {
        string outPath = getPlatformPath() + "/" + GetPlatformName();

        if (!Directory.Exists(outPath))
            Directory.CreateDirectory(outPath);

        //return outPath;
        return Application.streamingAssetsPath;

    }

    /// 
    /// 自动获取对应平台的路径
    /// 
    /// 
    private static string getPlatformPath()
    {
        switch (Application.platform)
        {
            case RuntimePlatform.WindowsPlayer:
            case RuntimePlatform.WindowsEditor:
                return Application.streamingAssetsPath;
            case RuntimePlatform.Android:
                //return Application.persistentDataPath;
                return Application.streamingAssetsPath;

            default:
                return null;
        }
    }


    /// 
    /// 获取对应平台的名字
    /// 
    /// 
    public static string GetPlatformName()
    {
        switch (Application.platform)
        {
            case RuntimePlatform.WindowsPlayer:
            case RuntimePlatform.WindowsEditor:
                return "Windows";
            case RuntimePlatform.Android:
                return "Android";
            default:
                return null;
        }
    }


    /// 
    /// 获取WWW协议的路径
    /// 
    public static string GetWWWPath()
    {
        switch (Application.platform)
        {
            case RuntimePlatform.WindowsPlayer:
            case RuntimePlatform.WindowsEditor:
                return "file:///" + Application.streamingAssetsPath;
            case RuntimePlatform.Android:
                //return "jar:file://" + GetAssetBundleOutPath();
                // return "jar:file://" + Application.streamingAssetsPath + "!/assets";
                return "jar:file://" + Application.dataPath + "!/assets";
            default:
                return null;
        }
    }

}

StateFucard

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Threading; //开启线程
using UnityEngine.UI;



/// 
/// 显示手机状态栏的类
/// 
public class StateFucard : MonoBehaviour {

    ////滑动条
    //public Slider progress;
    ////显示值

    //public Text progressValue;

    ////异步加载的场景
    //private AsyncOperation op;


    ////定义线程的引用;
    //Thread th ;


    
    /// 
    /// 保留手机状态栏,必须放在awake方法中去
    /// 
    void Awake() {

        // 透明栏 不显示
        // AndroidStatusBar.statusBarState = AndroidStatusBar.States.TranslucentOverContent;
        //不透明栏
        AndroidStatusBar.statusBarState = AndroidStatusBar.States.Visible;

        //定义线程
        //th = new Thread(new ThreadStart(ReturnAs));
        ////开启线程;
        //th.Start();
        ////协程优先级
        //th.Priority = System.Threading.ThreadPriority.Highest;
        ////是否后端运行
        //th.IsBackground = true;
    }




    void Start () {

        //op = SceneManager.LoadSceneAsync("FuCard");
        ////开启进度条
        //StartCoroutine(LoadingScene());

    }
    
    
    void Update () {

        // 从unity界面返回到安卓的界面
        if (Input.GetKeyUp(KeyCode.Escape))
        {
            AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject jo = jc.GetStatic("currentActivity");
            jo.Call("onBackPressed");
        }

    }



    //线程的方法 返回的方法
    //void ReturnAs() {

    //    //加入判断 终止线程;否则一直执行下去会占内存
    //    while (true)
    //    {
    //        AndroidStatusBar.statusBarState = AndroidStatusBar.States.Visible;
    //        // 从unity界面返回到安卓的界面
    //        if (Input.GetKeyUp(KeyCode.Escape))
    //        {
    //            AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    //            AndroidJavaObject jo = jc.GetStatic("currentActivity");
    //            jo.Call("onBackPressed");

    //            //终止线程;
    //            break;
    //        }
    //        //加载完成 终止线程
    //        if (op.allowSceneActivation)
    //        {
    //            break;
    //        }
    //    }
        
    //}




    /// 
    /// 设置进度值
    /// 
    /// 参数名
    //private void setProgressValue(int value)
    //{
    //    //获取进度条的值
    //    progress.value = value;

    //    //显示进度条的值
    //    progressValue.text = value + "%";
    //}

    ///// 
    ///// 加载场景
    ///// 
    ///// 
    //private IEnumerator LoadingScene()
    //{
    //    int displayProgress = 0;

    //    int toProgress = 0;

    //    op.allowSceneActivation = false; //不允许自动加载场景

    //    while (op.progress < 0.9f)
    //    {
    //        toProgress = (int)op.progress * 100;
    //        while (displayProgress < toProgress)
    //        {
    //            ++displayProgress;
    //            setProgressValue(displayProgress);
    //            yield return new WaitForEndOfFrame();
    //        }
    //    }

    //    toProgress = 100;

    //    while (displayProgress < toProgress)
    //    {
    //        ++displayProgress;
    //        setProgressValue(displayProgress);
    //        yield return new WaitForEndOfFrame();
    //    }

    //    op.allowSceneActivation = true;
    //}


}

五、效果展示

你可能感兴趣的:(AR开发实战Vuforia项目之仿支付宝集五福(云识别))