Vanny
Vanny

Reputation: 15

Unity - Disable AR HitTest after initial placement

I am using ARKit plugin for Unity leveraging the UnityARHitTestExample.cs.

After I place my object into the world scene I want to disable the ARKit from trying to place the object again every time I touch the screen. Can someone please help?

Upvotes: 0

Views: 641

Answers (1)

PongBongoSaurus
PongBongoSaurus

Reputation: 7385

There are a number of ways you can achieve this, although perhaps the simplest is creating a boolean to determine whether or not your model has been placed.

First off all you would create a boolean as noted above e.g:

private bool modelPlaced = false;

Then you would set this to true within the HitTestResultType function once your model has been placed:

bool HitTestWithResultType (ARPoint point, ARHitTestResultType resultTypes)
{
    List<ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface ().HitTest (point, resultTypes);
    if (hitResults.Count > 0) {
        foreach (var hitResult in hitResults) {

            //1. If Our Model Hasnt Been Placed Then Set Its Transform From The HitTest WorldTransform
            if (!modelPlaced){

                m_HitTransform.position = UnityARMatrixOps.GetPosition (hitResult.worldTransform);
                m_HitTransform.rotation = UnityARMatrixOps.GetRotation (hitResult.worldTransform);
                Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z));

                //2. Prevent Our Model From Being Positioned Again
                modelPlaced = true;
            }


            return true;
        }
    }
    return false;
}

And then in the Update() function:

void Update () {

    //Only Run The HitTest If We Havent Placed Our Model
    if (!modelPlaced){

        if (Input.touchCount > 0 && m_HitTransform != null)
        {
            var touch = Input.GetTouch(0);
            if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved)
            {
                var screenPosition = Camera.main.ScreenToViewportPoint(touch.position);
                ARPoint point = new ARPoint {
                    x = screenPosition.x,
                    y = screenPosition.y
                };

                ARHitTestResultType[] resultTypes = {
                    ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent, 
                }; 

                foreach (ARHitTestResultType resultType in resultTypes)
                {
                    if (HitTestWithResultType (point, resultType))
                    {
                        return;
                    }
                }
            }
        }
    }   
}

Hope it helps...

Upvotes: 2

Related Questions