Search code examples
c#unity-game-enginevuforia

Accessing Objects outside an Image target through Virtual Buttons?


Can I use Virtual Buttons, that are children of an Image target, to move an object that it not a child of the image target?

If yes, how do I script the same?

If no, are there any other ways around this?

From this picture, you'll understand what I'm trying to do.

Basically, I want those virtual keys to move the ball within the mazeenter image description here


Solution

  • Try this on for size.

    On your Image Target, attach this script to it. Basically you would used FindChild or something, but instead leave the gameobject public on the class. This way you can assign it directly to anything on your scene through the inspector.

    And TADAA!

    using UnityEngine;
    using System.Collections.Generic;
    
    public class VirtualButtonEvent : MonoBehaviour, IVirtualButtonEventHandler {
    
        public GameObject Sphere;
        public float speed;
    
        // register buttons for event handling
        void Start() {
            VirtualButtonBehaviour[] vbs = GetComponentsInChildren<VirtualButtonBehaviour>();
            for (int i = 0; i < vbs.Length; ++i) { vbs[i].RegisterEventHandler(this); }
        }
    
        // button is "pressed" to move Sphere
        public void OnButtonPressed(VirtualButtonAbstractBehaviour vb) {
            if (vb.VirtualButtonName=="Up")  { 
                Sphere.rigidbody.AddForce(new Vector3 (0, 0, speed) * speed);
            }
            if (vb.VirtualButtonName=="Down") {  
                Sphere.rigidbody.AddForce(new Vector3 (0, 0, -speed) * speed);
            }
            if (vb.VirtualButtonName=="Left") { 
                Sphere.rigidbody.AddForce(new Vector3 (-speed, 0, 0) * speed);
            }
            if (vb.VirtualButtonName=="Right") { 
                Sphere.rigidbody.AddForce(new Vector3 (speed, 0, 0) * speed);
            }
        }
    
        // Release to stop Sphere? (Maybe. Don't think this will stop the ball from moving.
        public void OnButtonReleased(VirtualButtonAbstractBehaviour vb) {
            if (vb.VirtualButtonName=="Up")  {  
                Sphere.rigidbody.AddForce(new Vector3 (0, 0, 0));
            }
            if (vb.VirtualButtonName=="Down") {  
                Sphere.rigidbody.AddForce(new Vector3 (0, 0, 0));
            }
            if (vb.VirtualButtonName=="Left") {  
                Sphere.rigidbody.AddForce(new Vector3 (0, 0, 0));
            }
            if (vb.VirtualButtonName=="Right") {  
                Sphere.rigidbody.AddForce(new Vector3 (0, 0, 0));
            }
        }
    
    }