Search code examples
unity-game-engineaugmented-realityvuforia

Detecting touch on a 3d model imported in Unity for an AR application using Vuforia


I have built an AR application using Unity and Vuforia. So basically when i scan something i see a model. I have removed the main camera and we are using AR camera for this purpose.

Now on running the apk on Mobile i want to open a url or show some message on touching the 3d model which comes after scanning the image.

I know it uses Raycasting but a code snippet which can help me in opening a url on clicking 3d model would help. I am a beginner in Unity so the help would be appreciated a lot.


Solution

  • Your models need to have colliders attached to them in order for the raycast to register the collision. Also it's convenient to use tags to filter out the raycast results. You can use layer masks for the same purposes though. Input.touches return an array of all registered touches during last frame, let's assume that there is only one touch registered, but if you want you can iterate through all the touches in case there are more than one and check if any of them hit the model. Then, you can do something like this:

        public void RegisterModelTouch()
        {
            // We assume that there was only one touch and take the first 
            // element in the array.
            Touch touch = Input.touches[0];
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(touch.position);
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.CompareTag("YourModelTag"))
                {
                    // Do something (open an URL in your case).
                }                
            }
        }
    

    Hope this helps.