一、主要框架
二、关键脚本
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();
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();
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 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() {
}
///
/// 隐藏按钮的协程
///
///
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
{
///
/// A custom handler that implements the ITrackableEventHandler interface.
///
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();
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
///
/// 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);
// 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(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;
}
//目标丢失点击无效
isTouch = false;
Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " lost");
}
#endregion // PRIVATE_METHODS
///
/// 音乐不再播放
///
//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;
///
/// 自动对焦功能
///
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 () {
}
///
/// 随机方法
///
public void RandonGo()
{
Debug.Log("接受方法=+++++++++++++");
index = Random.Range(0, transform.childCount);
for (int i = 0; i
三、展示效果