关于ImageTarget的使用不再赘述,现在假设有个按钮,按下之后,imagetarget下的球体便变为正方体。
添加如下脚本,挂在ARCamera上。
using UnityEngine;
using Vuforia;
using System.Collections;
public class ModelSwapper : MonoBehaviour {
public TrackableBehaviour theTrackable;
private bool mSwapModel = false;
// Use this for initialization
void Start () {
if (theTrackable == null)
{
Debug.Log ("Warning: Trackable not set !!");
}
}
// Update is called once per frame
void Update () {
if (mSwapModel && theTrackable != null) {
SwapModel();
mSwapModel = false;
}
}
void OnGUI() {
if (GUI.Button (new Rect(50,50,120,40), "Swap Model")) {
mSwapModel = true;
}
}
private void SwapModel() {
GameObject trackableGameObject = theTrackable.gameObject;
//把原来显示的模型隐藏掉。
for (int i = 0; i < trackableGameObject.transform.GetChildCount(); i++)
{
Transform child = trackableGameObject.transform.GetChild(i);
child.gameObject.active = false;
}
// 创建新物体cube
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
// 把cube的parent设置为trackable gameObject
cube.transform.parent = theTrackable.transform;
// 调整它的大小,使它能更好地适应target
cube.transform.localPosition = new Vector3(0,0.2f,0);
cube.transform.localRotation = Quaternion.identity;
cube.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
// 保证它是激活的
cube.active = true;
}
}