为了帮助理解答案,这里简要介绍了 Vuforia 如何处理标记检测。如果您查看附加到 ImageTarget 预制件 的 DefaultTrackableEventHandler 脚本,您会发现当跟踪系统发现或丢失一个图片。
这些是 DefaultTrackableEventHandler.cs 中的 OnTrackingFound(第 67 行)和 OnTrackingLost(第 88 行)
如果您想在跟踪时显示 Sprite,您需要做的就是放置 Image Target 预制件(或任何其他)并使 Sprite 成为预制件的子代。启用和禁用应该自动发生。
但是,如果您想做更多事情,这里有一些经过编辑的代码。
DefaultTrackableEventHandler.cs
//Assign this in the inspector. This is the GameObject that
//has a SpriteRenderer and Collider2D component attached to it
public GameObject spriteGameObject ;
将以下行添加到 OnTrackingFound
//Enable both the Sprite Renderer, and the Collider for the sprite
//upon Tracking Found. Note that you can change the type of
//collider to be more specific (such as BoxCollider2D)
spriteGameObject.GetComponent<SpriteRenderer>().enabled = true;
spriteGameObject.GetComponent<Collider2D>().enabled = true;
//EDIT 1
//Have the sprite inherit the position and rotation of the Image
spriteGameObject.transform.position = transform.position;
spriteGameObject.transform.rotation = transform.rotation;
以下是OnTrackingLost
//Disable both the Sprite Renderer, and the Collider for the sprite
//upon Tracking Lost.
spriteGameObject.GetComponent<SpriteRenderer>().enabled = false;
spriteGameObject.GetComponent<Collider2D>().enabled = false;
接下来,您关于检测此 Sprite 的点击的问题。 Unity 的 Monobehaviour 会为很多鼠标事件触发事件,例如 OnMouseUp、OnMouseDown 等。
Link to Monobehaviour on Unity's API docs
您需要的是一个名为 OnMouseUpAsButton
的事件
创建一个名为 HandleClicks.cs 的新脚本并将以下代码添加到其中。将此脚本作为组件附加到您为上述分配的 spriteGameObject。
public class HandleClicks : MonoBehaviour {
//Event fired when a collider receives a mouse down
//and mouse up event, like the interaction with a button
void OnMouseUpAsButton () {
//Do whatever you want to
Application.LoadLevel("myOtherLevel");
}
}