一袖瞻、主要框架
二营密、關(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("----------------------------------------------接受成功");
}
}
三、展示效果