【Vuforia】基于Vuforia增强现实开发(二)之模型移动

前边步骤一样。需要写一个脚本,关联要移动的模型。

跟上一篇相比,知识把对象从AudioSource换成了model,把脚本改了改接着用。

多三个新知识:

1、yield return

2、C#中的IEnumerator类

3、u3D中的开线程——StartCoroutine (move ());穿进去的是一个枚举类。


新建一个plane,以及它的材质球。当作地面。

【Vuforia】基于Vuforia增强现实开发(二)之模型移动_第1张图片【Vuforia】基于Vuforia增强现实开发(二)之模型移动_第2张图片【Vuforia】基于Vuforia增强现实开发(二)之模型移动_第3张图片


代码如下:

using UnityEngine;
using System.Collections;
using Vuforia;
public class TestMy : MonoBehaviour,ITrackableEventHandler {
	#region PRIVATE_MEMBER_VARIABLES
	//public GameObject UI;
	private TrackableBehaviour mTrackableBehaviour;
	public Transform Car;

	#endregion // PRIVATE_MEMBER_VARIABLES



	#region UNTIY_MONOBEHAVIOUR_METHODS

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

	#endregion // UNTIY_MONOBEHAVIOUR_METHODS



	#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();
			//UI.SetActive (true);
			StopAllCoroutines();
			StartCoroutine (move ());
		}
		else
		{
			//UI.SetActive (false);
			OnTrackingLost();
		}
	}

	#endregion // PUBLIC_METHODS

	IEnumerator move(){
		Car.transform.localPosition = new Vector3 (0,-2,0);
		while(Car.transform.localPosition!=Vector3.zero){
			yield return new WaitForEndOfFrame ();
			//相对父级的位置
			Car.transform.localPosition = Vector3.MoveTowards (Car.transform.localPosition, Vector3.zero, 0.5f * Time.deltaTime);
		}
	}

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

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


	private void OnTrackingLost()
	{
		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");
	}

	#endregion // PRIVATE_METHODS
}


你可能感兴趣的:(AR,Vuforia)