Пример #1
0
        /// <summary>
        /// Update the transform of the game board with the latest hit test result and camera
        /// </summary>
        private void UpdateTransform(ARHitTestResult hitTestResult, ARCamera camera)
        {
            var position = hitTestResult.WorldTransform.GetTranslation();

            // Average using several most recent positions.
            this.recentPositions.Add(position);
            this.recentPositions = new List <SCNVector3>(this.recentPositions.TakeLast(10));

            // Move to average of recent positions to avoid jitter.
            var average = this.recentPositions.Reduce(new SCNVector3(0f, 0f, 0f)) / (float)this.recentPositions.Count;

            this.Position = average;

            // Orient bounds to plane if possible
            if (hitTestResult.Anchor is ARPlaneAnchor planeAnchor)
            {
                this.OrientToPlane(planeAnchor, camera);
                this.ScaleToPlane(planeAnchor);
            }
            else
            {
                // Fall back to camera orientation
                this.OrientToCamera(camera);
                this.Scale = new SCNVector3(GameBoard.MinimumScale, GameBoard.MinimumScale, GameBoard.MinimumScale);
            }

            // Remove any animation duration if present
            SCNTransaction.AnimationDuration = 0;
        }
Пример #2
0
    /// <summary>
    /// Called when a touch interaction has ended.
    /// </summary>
    /// <param name="touch">The touch.</param>
    protected virtual void OnTouchInteractionEnded(Touch touch)
    {
        #if UNITY_IOS
        var     screenPosition = Camera.main.ScreenToViewportPoint(touch.position);
        ARPoint point          = new ARPoint
        {
            x = screenPosition.x,
            y = screenPosition.y
        };

        var hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point,
                                                                                             ARHitTestResultType.ARHitTestResultTypeEstimatedHorizontalPlane | ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent);
        if (hitResults.Count > 0)
        {
            ARHitTestResult hitResult = hitResults[0];
            Vector3         pos       = UnityARMatrixOps.GetPosition(hitResult.worldTransform);
            OnSelectObjectInteraction(pos, hitResult);
        }
        #elif UNITY_ANDROID
        TrackableHit      hit;
        TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
                                          TrackableHitFlags.FeaturePointWithSurfaceNormal;

        if (Frame.Raycast(touch.position.x, touch.position.y, raycastFilter, out hit))
        {
            OnSelectObjectInteraction(hit.Pose.position, hit);
        }
        #elif WINDOWS_UWP || UNITY_WSA
        RaycastHit hit;
        if (TryGazeHitTest(out hit))
        {
            OnSelectObjectInteraction(hit.point, hit);
        }
        #endif
    }
Пример #3
0
        public bool ARHitTest(Vector2 screenPosition, ARHitTestResultType hitTestResultType, float defaultDistance, out float distance)
        {
            ARPoint arPoint = new ARPoint();

            arPoint.x = screenPosition.x;
            arPoint.y = screenPosition.y;

            List <ARHitTestResult> hitResults =
                UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(arPoint, hitTestResultType);
            int hitResultsCount = hitResults.Count;

            if (hitResultsCount == 0)
            {
                distance = defaultDistance;
                return(false);
            }

            distance = 1.0e+6f;
            for (int index = 0; index < hitResultsCount; index++)
            {
                ARHitTestResult hitResult = hitResults[index];
                if (hitResult.distance < distance)
                {
                    distance = (float)hitResult.distance;
                    pointerARHitTestResult = hitResult;
                }
            }

            return(true);
        }
Пример #4
0
    static bool HitTestWithResultType(ARPoint point, ARHitTestResultType resultTypes, ref Position position)
    {
        List <ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, resultTypes);

        if (hitResults.Count > 0)
        {
            ARHitTestResult hitResult = hitResults[0];
            //TODO: get the position and rotations to spawn the hat
            Vector3    pos      = UnityARMatrixOps.GetPosition(hitResult.worldTransform);
            Quaternion rotation = UnityARMatrixOps.GetRotation(hitResult.worldTransform);
            position.location = pos;
            position.rotation = rotation;
            Debug.Log("found plane in hit test");
            debugPos = pos;
            //				spawnedObjects.Add( Instantiate (hitPrefab, pos, rotation) ); // in order to use for shuffling
            return(true);
//			foreach (var hitResult in hitResults) {
//				//TODO: get the position and rotations to spawn the hat
//				Vector3 pos = UnityARMatrixOps.GetPosition (hitResult.worldTransform);
//				Quaternion rotation = UnityARMatrixOps.GetRotation (hitResult.worldTransform);
//				position.location = pos;
//				position.rotation = rotation;
//				Debug.Log ("found plane in hit test");
////				spawnedObjects.Add( Instantiate (hitPrefab, pos, rotation) ); // in order to use for shuffling
//				return true;
//			}
        }
        return(false);
    }
    private void PlaceActorAt(float x, float y)
    {
        m_hitPoint.x = x / (float)m_opencvProcessing.m_lastBufferMarshalledWidth;
        m_hitPoint.y = y / (float)m_opencvProcessing.m_lastBufferMarshalledHeight;

        List <ARHitTestResult> hitResults = m_arSession.HitTest(m_hitPoint, m_resultTypeToUse);

        if (hitResults.Count > 0)
        {
            ARHitTestResult hitResult = Utils.GetFirstValidHit(hitResults);
            if (hitResult.isValid)
            {
                var nextPosition = UnityARMatrixOps.GetPosition(hitResult.worldTransform);
                if ((nextPosition - m_actor.position).magnitude > 0.1f)
                {
                    m_actor.position = nextPosition + m_offset;
                }
            }
            else
            {
                Debug.Log("Invalid hit point");
            }
        }
        else
        {
            Debug.Log("No hit points");
        }
    }
Пример #6
0
        private void AddSelectedItem(ARHitTestResult hitTestResult)
        {
            SCNNode  node        = GetSelectedNode();
            NMatrix4 transform   = hitTestResult.WorldTransform;
            Vector4  thirdColumn = transform.Column3;

            node.Position = new SCNVector3(thirdColumn.X, thirdColumn.Y, thirdColumn.Z);

            sceneView.Scene.RootNode.AddChildNode(node);
        }
Пример #7
0
    public static UnityARUserAnchorData ToUnityArUserAnchorData(this ARHitTestResult arHitTestResult)
    {
        var transform  = UnityARMatrixOps.GetMatrix(arHitTestResult.worldTransform);
        var anchorData = new UnityARUserAnchorData
        {
            transform = transform
        };

        return(anchorData);
    }
Пример #8
0
    static public ARHitTestResult GetFirstValidHit(List <ARHitTestResult> hitResults)
    {
        ARHitTestResult hitResult = hitResults[0];         // Return the first hit, if no valid hits were found.

        foreach (var h in hitResults)
        {
            if (h.isValid)
            {
                hitResult = h;
                break;
            }
        }
        return(hitResult);
    }
Пример #9
0
    static bool TryHitTest(ARPoint point, ARHitTestResultType resultTypes, out ARHitTestResult hitTestResult)
    {
        var results = UnityARSessionNativeInterface.GetARSessionNativeInterface()
                      .HitTest(point, resultTypes);

        if (results.Any())
        {
            hitTestResult = results.First();
            return(true);
        }

        hitTestResult = default(ARHitTestResult);
        return(false);
    }
 /// <summary>
 /// Hit test against existing anchors
 /// </summary>
 private bool TryHitTestFromTouchPoint(CGPoint pt, out NMatrix4 worldTransform)
 {
     ARHitTestResult[] hits = this.sceneView.HitTest(pt, ARHitTestResultType.FeaturePoint);
     if (hits != null && hits.Length > 0)
     {
         ARHitTestResult hit = hits.FirstOrDefault();
         if (hit != null)
         {
             worldTransform = hit.WorldTransform;
             return(true);
         }
     }
     worldTransform = default;
     return(false);
 }
Пример #11
0
    bool GetCursorPosition(ref Vector3 positionToUpdate)
    {
        bool wasCursorFound = false;
        List <ARHitTestResult> hitResults =
            UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(m_hitPointToUse, m_resultTypeToUse);

        if (hitResults.Count > 0)
        {
            ARHitTestResult hitResult = Utils.GetFirstValidHit(hitResults);
            if (hitResult.isValid)
            {
                positionToUpdate = UnityARMatrixOps.GetPosition(hitResult.worldTransform);
                wasCursorFound   = true;
            }
        }

        return(wasCursorFound);
    }
        private void OnPlaneFound(ARHitTestResult hitResult)
        {
            Debug.Log("<color=cyan>OnPlaneFound</color>");

            GameObject anchor = new GameObject("game world");

            anchor.transform.position = UnityARMatrixOps.GetPosition(hitResult.worldTransform);
            anchor.transform.rotation = UnityARMatrixOps.GetRotation(hitResult.worldTransform);

            planeFound(anchor);

            if (_previousAnchor != null)
            {
                Destroy(_previousAnchor);
            }

            _previousAnchor = anchor;
        }
Пример #13
0
        /// <summary>
        /// Updates the game board with the latest hit test result and camera.
        /// </summary>
        public void Update(ARHitTestResult hitTestResult, ARCamera camera)
        {
            if (this.IsBorderHidden)
            {
                this.UnhideBorder();
            }

            if (hitTestResult.Anchor is ARPlaneAnchor planeAnchor)
            {
                this.PerformCloseAnimation(!this.anchorsOfVisitedPlanes.Contains(planeAnchor));
                this.anchorsOfVisitedPlanes.Add(planeAnchor);
            }
            else
            {
                this.PerformOpenAnimation();
            }

            this.UpdateTransform(hitTestResult, camera);
        }
Пример #14
0
    void checkForPlane()
    {
        // check for planes
        var screenPosition = Camera.main.ScreenToViewportPoint(new Vector2(Screen.width / 2f, Screen.height / 2f));
        List <ARHitTestResult> hitResults = getHitTest(screenPosition);

        Debug.Log("CHECKING FOR PLANE");

        // if plane exists, place the dog
        if (hitResults.Count > 0 && corgi.GetComponent <DogControl> ().isReadyForQRDetection)
        {
            Debug.Log("PLANE DETECTED AND READY FOR DOG");
            ARHitTestResult result = hitResults[0];
            checkingForPlane = false;
            corgi.GetComponent <DogControl> ().dogNamePanel.SetActive(true);
            mat.transform.forward         = Camera.main.transform.forward;
            mat.transform.position        = UnityARMatrixOps.GetPosition(result.worldTransform);
            matPlane.transform.localScale = new Vector3(.05f, .05f, .05f);
        }
    }
        private Vector3 GetHitPosition_IOS()
        {
            var     screenPosition = Camera.main.ScreenToViewportPoint(new Vector3(0.5f, 0.5f));
            ARPoint point          = new ARPoint
            {
                x = screenPosition.x,
                y = screenPosition.y
            };
            var hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, ARHitTestResultType.ARHitTestResultTypeEstimatedHorizontalPlane | ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent);

            if (hitResults.Count > 0)
            {
                // The hitTest method sorts the resulting list by increasing distance from the camera
                // The first hit result will usually be the most relevant when responding to user input
                ARHitTestResult hitResult = hitResults[0];
                hitPosition = UnityARMatrixOps.GetPosition(hitResult.worldTransform);
            }

            return(hitPosition);
        }
Пример #16
0
        private void ShowPortal(ARHitTestResult hitTestResult)
        {
            SCNScene portalScene = SCNScene.FromFile("art.scnassets/Portal.scn");
            SCNNode  portalNode  = portalScene.RootNode.FindChildNode("Portal", false);

            OpenTK.NMatrix4 transform = hitTestResult.WorldTransform;

            float planeXposition = transform.Column3.X;
            float planeYposition = transform.Column3.Y;
            float planeZposition = transform.Column3.Z;

            portalNode.Position = new SCNVector3(planeXposition, planeYposition, planeZposition);
            sceneView.Scene.RootNode.AddChildNode(portalNode);

            AddPlane("roof", portalNode, "portalTop.png");
            AddPlane("floor", portalNode, "portalBottom.png");
            AddWalls("backWall", portalNode, "portalBack.png");
            AddWalls("sideWallA", portalNode, "portalSideA.png");
            AddWalls("sideWallB", portalNode, "portalSideB.png");
            AddWalls("sideDoorA", portalNode, "portalSideDoorA.png");
            AddWalls("sideDoorB", portalNode, "portalSideDoorB.png");
        }
Пример #17
0
    bool GetAverageCursorPosition(ref Vector3 positionToUpdate)
    {
        bool wasCursorFound = false;

        float[] pointDeltas = { -m_delta, -m_delta, -m_delta, m_delta, m_delta, 0 };

        Vector3 sum   = Vector3.zero;
        ARPoint point = new ARPoint();

        for (int i = 0; i < pointDeltas.GetLength(0) / 2; ++i)
        {
            point.x = m_hitPointToUse.x + pointDeltas [i * 2];
            point.y = m_hitPointToUse.y + pointDeltas [i * 2 + 1];

            List <ARHitTestResult> hitResults =
                UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, m_resultTypeToUse);
            if (hitResults.Count > 0)
            {
                ARHitTestResult hitResult = Utils.GetFirstValidHit(hitResults);
                if (hitResult.isValid)
                {
                    sum += UnityARMatrixOps.GetPosition(hitResult.worldTransform);

                    if (i == 2)
                    {
                        positionToUpdate = sum / 3;
                        wasCursorFound   = true;
                    }
                }
                else
                {
                    break;
                }
            }
        }

        return(wasCursorFound);
    }
Пример #18
0
        public void OnHitTestFinished(ARHitTestResult[] p0)
        {
            if (p0 == null || p0.Length <= 0)
            {
                return;
            }

            // If we have found intersected AR Hit points, update views as needed, reset miss count.
            ViroViewARCore viewArView = mViroView;
            var            cameraPos  = viewArView.LastCameraPositionRealtime;

            // Grab the closest ar hit target
            float           closestDistance = float.MaxValue;
            ARHitTestResult result          = null;

            for (int i = 0; i < p0.Length; i++)
            {
                ARHitTestResult currentResult = p0[i];

                float distance = currentResult.Position.Distance(cameraPos);
                if (distance < closestDistance && distance > .3 && distance < 5)
                {
                    result          = currentResult;
                    closestDistance = distance;
                }
            }

            // Update the cross hair target location with the closest target.
            if (result != null)
            {
                mCrosshairModel.SetPosition(result.Position);
                mCrosshairModel.SetRotation(result.Rotation);
            }

            // Update State based on hit target
            SetTrackingStatus(result != null ? TrackStatus.SurfaceFound : TrackStatus.FindingSurface);
        }
Пример #19
0
 protected override void HitResultFunction(ARHitTestResult hitResult)
 {
     targetPosition = UnityARMatrixOps.GetPosition(hitResult.worldTransform);
     targetRotation = UnityARMatrixOps.GetRotation(hitResult.worldTransform);
 }
Пример #20
0
 protected virtual void HitResultFunction(ARHitTestResult hitResult)
 {
 }