Exemplo n.º 1
0
        public bool Raycast(IntPtr frameHandle, float[] ray_origin, float[] ray_direction, TrackableHitFlags filter,
                            List <TrackableHit> outHitList, bool isOnlyQueryingNearestHit)
        {
            outHitList.Clear();

            IntPtr hitResultListHandle = IntPtr.Zero;

            ExternApi.arQueryResultListCreate(m_NativeSession.SessionHandle, ref hitResultListHandle);
            ExternApi.arFrameRayQuery(m_NativeSession.SessionHandle, frameHandle, ray_origin, ray_direction, hitResultListHandle);

            int hitListSize = 0;

            ExternApi.arQueryResultListGetSize(m_NativeSession.SessionHandle, hitResultListHandle, ref hitListSize);

            for (int i = 0; i < hitListSize; i++)
            {
                TrackableHit trackableHit = new TrackableHit();
                if (HitResultListGetItemAt(hitResultListHandle, i, ref trackableHit))
                {
                    outHitList.Add(trackableHit);
                }
            }

            ExternApi.arQueryResultListDestroy(hitResultListHandle);
            return(outHitList.Count != 0);
        }
Exemplo n.º 2
0
        private void CreateVirtualAnchor()
        {
            if (_environmentVisualizer == null)
            {
                return;
            }

            var trackableHits = new List <TrackableHit>();

//                        const TrackableHitFlags filter =
//                            TrackableHitFlags.PlaneWithinBounds | TrackableHitFlags.PlaneWithinPolygon;

            // TODO think : like in HelloAR example
            const TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
                                                    TrackableHitFlags.FeaturePointWithSurfaceNormal;

            var didHitSomething = Frame.RaycastAll(_firstPersonCamera.transform.position,
                                                   _firstPersonCamera.transform.forward, trackableHits, Mathf.Infinity, raycastFilter);

            if (didHitSomething)
            {
                var minY = Mathf.Infinity;

                var hitToAssociateWith    = new TrackableHit(); // with minimal 'y'
                var foundSuchTrackableHit = false;

                foreach (var trackableHit in trackableHits)
                {
                    // Use hit pose and camera pose to check if hittest is from the
                    // back of the plane, if it is, no need to create the anchor.
                    if ((trackableHit.Trackable is DetectedPlane) &&
                        Vector3.Dot(_firstPersonCamera.transform.position - trackableHit.Pose.position,
                                    trackableHit.Pose.rotation * Vector3.up) < 0)
                    {
                        Debug.Log("Hit at back of the current DetectedPlane");
                    }
                    else
                    {
                        if (trackableHit.Pose.position.y < minY)
                        {
                            minY = trackableHit.Pose.position.y;
                            hitToAssociateWith    = trackableHit;
                            foundSuchTrackableHit = true;
                        }
                    }
                }

                if (foundSuchTrackableHit)
                {
                    var virtualAnchor = hitToAssociateWith.Trackable.CreateAnchor(hitToAssociateWith.Pose);
                    _environmentVisualizer.transform.parent = virtualAnchor.transform;

                    // create a model for this virtual anchor
                    var virtualAnchorModel = Instantiate(_vitualAnchorPlanePrefab, hitToAssociateWith.Pose.position,
                                                         hitToAssociateWith.Pose.rotation);

                    virtualAnchorModel.transform.parent = virtualAnchor.transform;
                }
            }
        }
Exemplo n.º 3
0
    private void SpawnCharacter(TrackableHit hit)
    {
        Vector3 lookRotation = Quaternion.LookRotation(firstPersonCamera.transform.position - hit.Point).eulerAngles;

        lookRotation.x = 0f;
        lookRotation.z = 0f;

        // Spawned characted needs to face the camera
        Quaternion spawnRotation = Quaternion.Euler(lookRotation);

        // Create an anchor to allow ARCore to track the hitpoint as understanding of the physical
        // world evolves.
        Anchor anchor = Session.CreateAnchor(hit.Point, Quaternion.identity);

        // Spawn character from prefab and attach it to anchor
        GameObject akiraGO = Instantiate(akiraPrefab, hit.Point, spawnRotation, anchor.transform);

        // Save reference to character
        akira = akiraGO.GetComponent <Akira>();

        // Use a plane attachment component to maintain Akira's y-offset from the plane
        // (occurs after anchor updates).
        akiraGO.AddComponent <PlaneAttachment>().Attach(hit.Plane);

        // Print message on screen
        _ShowAndroidToastMessage("Created character!");
    }
Exemplo n.º 4
0
    // Set the Gameobjekt of the Plane we touched
    void SetGameObject(TrackableHit hit)
    {
        //Enable the GameObject
        PrefabObject.SetActive(true);

        //Create a new Anchor
        Anchor anchor = hit.Trackable.CreateAnchor(hit.Pose);

        //Set the position of the PrefabObject to be the smae as the hit postion
        PrefabObject.transform.position = new Vector3(hit.Pose.position.x, hit.Pose.position.y + (PrefabObject.transform.localScale.y / 2), hit.Pose.position.z);
        PrefabObject.transform.rotation = hit.Pose.rotation;

        //we want the portal to face the camera
        Vector3 cameraPositon = ARCamera.transform.position;

        //the portal should only rotate arround the y axis
        cameraPositon.y = hit.Pose.position.y;

        //Rotate the portal to face the camera
        PrefabObject.transform.LookAt(cameraPositon, PrefabObject.transform.up);

        //the object should rotate left by 180 degrees
        Quaternion newRotation = Quaternion.AngleAxis(180, Vector3.up);

        PrefabObject.transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, .05f);

        text.GetComponent <Text>().text = "tricker fur z-achse " + hit.Pose.position.z;

        //ARCore will keep understanding the world and update the anchors accordingly hence we need to attach our portal to the anchor
        PrefabObject.transform.parent = anchor.transform;
    }
Exemplo n.º 5
0
    // Update is called once per frame
    void Update()
    {
        _UpdateApplicationLifecycle();

        //If the y / cloud anchor is set, return
        if (m_IsStarted)
        {
            return;
        }

        if (auto_setup)
        {
            UI_Snackbar.text = "Initialize Settings Called";
            SetFloorY(-1f);
            FloorCaptureControl.SetFloorY(-1);
            WorldOriginHelp.SetNoPlanes(true);
            IllusionModeStart();
            m_IsStarted = true;
        }

        // If the player has not touched the screen, we are done with this update.
        Touch touch;

        if (Input.touchCount < 1 || (touch = Input.GetTouch(0)).phase != TouchPhase.Began)
        {
            return;
        }

        // Should not handle input if the player is pointing on UI.
        if (EventSystem.current.IsPointerOverGameObject(touch.fingerId))
        {
            return;
        }

        // Raycast against the location the player touched to search for planes.
        TrackableHit arcoreHitResult = new TrackableHit();

        m_LastHitPose = null;
        if (WorldOriginHelp.Raycast(touch.position.x, touch.position.y,
                                    TrackableHitFlags.PlaneWithinPolygon, out arcoreHitResult))
        {
            m_LastHitPose = arcoreHitResult.Pose;
        }

        if (m_LastHitPose != null)
        {
            m_WorldOriginAnchor = arcoreHitResult.Trackable.CreateAnchor(arcoreHitResult.Pose);

            SetWorldOrigin(m_WorldOriginAnchor.transform);
            _InstantiateAnchor();


            WorldOriginHelp.SetNoPlanes(true);
            SetFloorY(arcoreHitResult.Pose.position.y);
            FloorCaptureControl.SetFloorY(arcoreHitResult.Pose.position.y);
            IllusionModeStart();
            // UI_Snackbar.text = "Take a picture of only your floor in the frame";
            m_IsStarted = true;
        }
    }
Exemplo n.º 6
0
        private bool HitResultListGetItemAt(IntPtr hitResultListHandle, int index, ref TrackableHit outTrackableHit)
        {
            // Query the hit result.
            IntPtr hitResultHandle = IntPtr.Zero;

            ExternApi.arQueryResultCreate(m_NativeSession.SessionHandle, ref hitResultHandle);
            ExternApi.arQueryResultListGetItem(m_NativeSession.SessionHandle, hitResultListHandle, index, hitResultHandle);
            if (hitResultHandle == IntPtr.Zero)
            {
                ExternApi.arQueryResultDestroy(hitResultHandle);
                return(false);
            }

            // Query the pose from hit result.
            IntPtr poseHandle = m_NativeSession.PoseApi.Create();

            ExternApi.arQueryResultGetHitPose(m_NativeSession.SessionHandle, hitResultHandle, poseHandle);
            Pose hitPose = m_NativeSession.PoseApi.ExtractPoseValue(poseHandle);

            // Query the distance from hit result.
            float hitDistance = 0.0f;

            // Query the trackable from hit result.
            IntPtr trackableHandle = IntPtr.Zero;

            ExternApi.arQueryResultAcquireNode(m_NativeSession.SessionHandle, hitResultHandle, ref trackableHandle);
            Trackable trackable = m_NativeSession.TrackableFactory(trackableHandle);
            //m_NativeSession.TrackableApi.Release(trackableHandle);


            // TODO fixed me, need to release hitResultHandle
            //ExternApi.ArHitResult_destroy(hitResultHandle);

            // Calculate trackable hit flags.
            TrackableHitFlags flag = TrackableHitFlags.None;

            if (trackable == null)
            {
                Debug.Log("Could not create trackable from hit result.");
                m_NativeSession.PoseApi.Destroy(poseHandle);
                return(false);
            }
            else if (trackable is TrackedPlane)
            {
                flag |= TrackableHitFlags.PlaneWithinInfinity;
            }
            else if (trackable is TrackedPoint)
            {
                flag |= TrackableHitFlags.PointCloud;
            }
            else
            {
                m_NativeSession.PoseApi.Destroy(poseHandle);
                return(false);
            }

            outTrackableHit = new TrackableHit(hitPose, hitDistance, flag, trackable);
            m_NativeSession.PoseApi.Destroy(poseHandle);
            return(true);
        }
Exemplo n.º 7
0
    /// <summary>
    /// Sends information about clicked coordinates.
    /// Function checks if the clicked position is on the same platform or does player need
    /// to move up or down.
    /// </summary>
    /// <param name="hit"></param>
    public void HandlePlayerMovement(TrackableHit hit, GameObject playerGameObject)
    {
        var inputManager    = playerGameObject.GetComponent <PlayerInputManager>();
        var movementManager = playerGameObject.GetComponent <PlayerMovementManager>();

        if (inputManager.touchHitPlayer)
        {
            inputManager.touchHitPlayer = false;
            return;
        }

        Vector3 worldHitPos = hit.Pose.position;
        Vector3 playerPos   = playerGameObject.transform.position;

        float roundedClickedPosition = (float)Math.Round(worldHitPos.y, 2, MidpointRounding.ToEven);
        float roundedPlayerPosition  = (float)Math.Round(playerPos.y, 2, MidpointRounding.ToEven);

        if (roundedPlayerPosition == roundedClickedPosition)
        {
            movementManager.MovePlayer(worldHitPos);
        }
        else if (roundedClickedPosition < roundedPlayerPosition)
        {
            movementManager.MovePlayerToLowerPlatform(worldHitPos);
        }
        else if (roundedClickedPosition > roundedPlayerPosition)
        {
            movementManager.MovePlayerToHigherPlatform(worldHitPos);
        }

        return;
    }
Exemplo n.º 8
0
        public void setWorldOriginCloudAnchor()
        {
            TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon;
            TrackableHit      hit           = new TrackableHit();

            if (Application.platform != RuntimePlatform.IPhonePlayer)
            {
                if (ARCoreWorldOriginHelper.Raycast(Screen.width * 0.5f, Screen.height * 0.5f, raycastFilter, out hit))
                {
                    m_LastHitPose = hit.Pose;
                }
            }
            if (m_LastHitPose != null)
            {
                // The first touch on the Hosting mode will instantiate the origin anchor. Any
                // subsequent touch will instantiate a star, both in Hosting and Resolving modes.
                if (!IsOriginPlaced && m_CurrentMode == ApplicationMode.Hosting)   //原點錨
                {
                    if (Application.platform != RuntimePlatform.IPhonePlayer)
                    {
                        m_WorldOriginAnchor =
                            hit.Trackable.CreateAnchor(hit.Pose);
                    }

                    SetWorldOrigin(m_WorldOriginAnchor.transform);  //定義世界原點
                    _InstantiateAnchor();
                    OnAnchorInstantiated(true);
                    CloudAnchorSight.SetActive(false);
                }
            }
        }
Exemplo n.º 9
0
    private void CenterMarkerOnScreen(TrackableHit hit)
    {
        Vector3 hitPoint     = hit.Pose.position;
        var     activeMarker = marker[marker.Count - 1];

        activeMarker.transform.position = new Vector3(hitPoint.x, activeMarker.transform.position.y, hitPoint.z);
    }
Exemplo n.º 10
0
    public void OnAnchorFound(Anchor anchor, TrackableHit hit)
    {
        gameObject.SetActive(true);
        transform.SetParent(anchor.transform);
        transform.localRotation = Quaternion.identity;
        transform.localPosition = Vector3.zero;

        var dot = Vector3.Dot(anchor.transform.up, Camera.transform.position - hit.Pose.position);

        if (hit.Distance > 1f && dot > .5f)
        {
            if (_table == null)
            {
                _table = Instantiate(TablePrefab, transform);
            }
            _table.transform.localPosition = new Vector3(0, -0.5f, 0);
            _table.transform.localPosition = Vector3.zero;
            _table.transform.localRotation = Quaternion.Euler(0, -90f, 0);
            _spline.SetControlPoint(_spline.ControlPointCount - 1, anchor.transform.position + new Vector3(0, 0.91f, 0));
        }
        else
        {
            if (_table != null)
            {
                _table.SetActive(false);
            }
            _spline.SetControlPoint(_spline.ControlPointCount - 1, anchor.transform.position);
        }
    }
Exemplo n.º 11
0
    void PlacePreview()
    {
        TrackableHit hit;

        if (Frame.Raycast(Screen.width * 0.5f, Screen.height * 0.5f, TrackableHitFlags.PlaneWithinPolygon, out hit)) // Middle of the screen
        {
            if (hit.Pose != null)
            {
                _hit = hit;
            }

            if ((_hit.Trackable is DetectedPlane) && Vector3.Dot(_firstPersonCamera.transform.position - _hit.Pose.position, _hit.Pose.rotation * Vector3.up) < 0)
            {
                Debug.Log("Hit at back of the current DetectedPlane");
            }
            else
            {
                // Enable object
                if (!_currentObject.gameObject.activeSelf)
                {
                    _currentObject.gameObject.SetActive(true);
                }

                // Place object in center of the screen
                PositionCharacter(_hit);
            }
        }

        if (Input.GetMouseButton(0) && !_hasPlaced && _hasPositioned)
        {
            PlaceCharacter(_hit);
        }
    }
Exemplo n.º 12
0
    private void createAnchor(TrackableHit spawnPoint, Vector3 position, Quaternion rotation)
    {
        anchor = (detectedPlane.CreateAnchor(
                      new Pose(spawnPoint.Pose.position, rotation)));

        if (room != null)
        {
            DestroyImmediate(room);
        }

        //Vector3 negativeAmount = roomPrefab.transform.Find("SpawnPoint").position;
        //float distance = Vector3.Distance(roomPrefab.transform.Find("SpawnPoint").position, roomPrefab.transform.Find("FloorForMeasurement").position);
        //Debug.Log(distance);
        //Vector3 newPosition = position-negativeAmount;
        room = Instantiate(TestRoom(), position, rotation);

        room.transform.SetParent(anchor.transform);

        /*
         * GameObject marker = GameObject.Find("PlacementMarkerController");
         * marker.SetActive(false);
         */
        GameObject planeGenerator = GameObject.Find("Plane Generator");

        planeGenerator.SetActive(false);
    }
Exemplo n.º 13
0
        public bool Raycast(IntPtr frameHandle, float x, float y, TrackableHitFlags filter,
                            List <TrackableHit> outHitList, bool isOnlyQueryingNearestHit)
        {
            outHitList.Clear();

            IntPtr hitResultListHandle = IntPtr.Zero;

            ExternApi.ArHitResultList_create(m_NativeApi.SessionHandle, ref hitResultListHandle);
            ExternApi.ArFrame_hitTest(m_NativeApi.SessionHandle, frameHandle, x, y, hitResultListHandle);

            int hitListSize = 0;

            ExternApi.ArHitResultList_getSize(m_NativeApi.SessionHandle, hitResultListHandle, ref hitListSize);

            for (int i = 0; i < hitListSize; i++)
            {
                TrackableHit trackableHit = new TrackableHit();
                if (HitResultListGetItemAt(hitResultListHandle, i, ref trackableHit))
                {
                    if ((filter & trackableHit.Flags) != TrackableHitFlags.None)
                    {
                        outHitList.Add(trackableHit);
                    }
                }
            }

            ExternApi.ArHitResultList_destroy(hitResultListHandle);
            return(outHitList.Count != 0);
        }
Exemplo n.º 14
0
    private void PositionCharacter(TrackableHit pHit)
    {
        _currentObject.transform.position = pHit.Pose.position;
        _currentObject.transform.rotation = pHit.Pose.rotation;

        _hasPositioned = true;
    }
Exemplo n.º 15
0
    void AnchorButtonPressed()
    {
        TrackableHit arcoreHitResult = new TrackableHit();

        m_LastHitPose = null;
        if (WorldOriginHelp.Raycast(1300, 800,
                                    TrackableHitFlags.PlaneWithinPolygon, out arcoreHitResult))
        {
            m_LastHitPose = arcoreHitResult.Pose;
        }

        if (m_LastHitPose != null)
        {
            m_WorldOriginAnchor = arcoreHitResult.Trackable.CreateAnchor(arcoreHitResult.Pose);

            SetWorldOrigin(m_WorldOriginAnchor.transform);
            _InstantiateAnchor();


            //WorldOriginHelp.SetNoPlanes(true);
            SetFloorY(arcoreHitResult.Pose.position.y);
            IllusionModeStart();
            UI_Snackbar.text = "Take a picture of only your floor in the frame";
            m_IsStarted      = true;
        }
    }
Exemplo n.º 16
0
    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0) || (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began))
        {
            if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
            {
                return;
            }
            if (Input.touchCount == 1 && UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
            {
                return;
            }


            Debug.Log("Click");

            Vector3 p = Input.mousePosition;
            GoogleARCore.TrackableHit hit;

            if (GoogleARCore.Frame.Raycast(p.x, p.y, GoogleARCore.TrackableHitFlags.PlaneWithinPolygon, out hit))
            {
                FlagObj.SetActive(false);
                _hit = hit;
                Pose planePose = hit.Pose;
                PlaneAnchor = hit.Trackable.CreateAnchor(hit.Pose);

                transform.position = planePose.position;
                transform.rotation = planePose.rotation;
                FlagObj.SetActive(true);
                SetFlagEvent.Invoke(this);
            }
        }
    }
Exemplo n.º 17
0
    /// <summary>
    /// Function for placing avatar and the ground plane.
    /// </summary>
    /// <param name="hit">Trackable hit.</param>
    private void PlaceAvatarScene(TrackableHit hit)
    {
        m_SceneContainer = new GameObject();

        // Creates an anchor to allow ARCore to track the hitpoint as understanding of
        // the physical world evolves.
        var anchor = hit.Trackable.CreateAnchor(hit.Pose);

        // Instantiates avatar model at the hit pose.
        var avatarObject = Instantiate(AvatarPrefab, hit.Pose.position, hit.Pose.rotation);

        // Compensates for the hitPose rotation facing away from the raycast (i.e. camera).
        avatarObject.transform.Rotate(0, k_ModelRotation, 0, Space.Self);

        // Makes avatar model a child of the anchor.
        Avatar = avatarObject;
        var avatarController = Avatar.GetComponent <AvatarController>();

        if (avatarController != null)
        {
            avatarController.EnableAvatarManipulation = EnableAvatarManipulation;
        }

        if (EnableAvatarManipulation)
        {
            // Attaches the collision-aware manipulator.
            var manipulator = Instantiate(CollisionAwareManipulatorPrefab,
                                          hit.Pose.position, hit.Pose.rotation);

            // Allows the manipulator to read user-customized parameters in the detector.
            var manipulatorScript = manipulator.GetComponent <CollisionAwareManipulator>();
            var collisionDetector = CollisionDetectorGameObject.GetComponent <CollisionDetector>();
            manipulatorScript.SetCollisionDetector(collisionDetector);
            avatarObject.transform.parent = manipulator.transform;

            anchor.transform.parent = m_SceneContainer.transform;

            // Makes manipulator a child of the anchor.
            manipulator.transform.parent = anchor.transform;

            // Selects the placed object.
            manipulator.GetComponent <Manipulator>().Select();
        }
        else
        {
            anchor.transform.parent = m_SceneContainer.transform;
            Avatar.transform.parent = m_SceneContainer.transform;
        }

        // Places the ground plane to avoid the cubes to fall to holes.
        Vector3    planePosition  = hit.Pose.position + new Vector3(0.0f, 0.0f, 0.0f);
        GameObject NewGroundPlane = Instantiate(GroundPlane, planePosition, hit.Pose.rotation)
                                    as GameObject;

        NewGroundPlane.transform.Rotate(0, k_ModelRotation, 0, Space.Self);
        NewGroundPlane.transform.parent = anchor.transform;

        ToggleUI();
    }
Exemplo n.º 18
0
 private void TouchHandleCreatCloudAncObj(TrackableHit pHIt)
 {
     if (CloundRoom.IsRoommer())
     {
         Anchor anchor = pHIt.Trackable.CreateAnchor(pHIt.Pose);
         CloundRoom.RegisterRoomCloudAnc(anchor, CreateCloudSuccess, CreateCloudFalure);
     }
 }
Exemplo n.º 19
0
    void PlacePortal(TrackableHit h)
    {
        var anchor       = h.Trackable.CreateAnchor(h.Pose);
        var placedObject = Instantiate(portal, h.Pose.position, h.Pose.rotation);

        placedObject.transform.Rotate(90, 0, 0, Space.Self);
        placedObject.transform.parent = anchor.transform;
    }
Exemplo n.º 20
0
    private bool SearchHitTrackable(float worldPositionX, float worldPositionY, out TrackableHit hitTrackable)
    {
        bool ret = false;
        TrackableHitFlags flags = TrackableHitFlags.None;
        TrackableHitFlags featureFlag;
        TrackableHitFlags planeWithFlag;

        string    currentFeatureCaptionText = mTrackableHitFlagsFeatureDd.captionText.text;
        FieldInfo featureFieldInfo          = typeof(TrackableHitFlags).GetField(currentFeatureCaptionText, System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Static);

        if (featureFieldInfo != null)
        {
            featureFlag = (TrackableHitFlags)featureFieldInfo.GetValue(null);
            mLogger.CategoryLog(LogCategoryMethodTrace, "featureFlag=" + featureFlag.ToString());
        }
        else
        {
            featureFlag = TrackableHitFlags.None;
        }

        string    currentPlaneWithCaptionText = mTrackableHitFlagsPlaneWithDd.captionText.text;
        FieldInfo planeWithFieldInfo          = typeof(TrackableHitFlags).GetField(currentPlaneWithCaptionText, System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Static);

        if (planeWithFieldInfo != null)
        {
            planeWithFlag = (TrackableHitFlags)planeWithFieldInfo.GetValue(null);
            mLogger.CategoryLog(LogCategoryMethodTrace, "planeWithFlag=" + planeWithFlag.ToString());
        }
        else
        {
            planeWithFlag = TrackableHitFlags.None;
        }

        if (featureFlag == TrackableHitFlags.None && planeWithFlag == TrackableHitFlags.None)
        {
            flags = TrackableHitFlags.None;
        }
        else
        {
            if (featureFlag != TrackableHitFlags.None)
            {
                flags = featureFlag;
            }
            if (planeWithFlag != TrackableHitFlags.None)
            {
                if (flags == TrackableHitFlags.None)
                {
                    flags = planeWithFlag;
                }
                else
                {
                    flags |= planeWithFlag;
                }
            }
        }

        return(Frame.Raycast(worldPositionX, worldPositionY, flags, out hitTrackable));
    }
    public void SetSelectedPlane(TrackableHit hit)
    {
        Debug.Log("Selected plane centered at " + selectedPlane.CenterPose.position);
        Debug.Log("With size of x " + selectedPlane.ExtentX + " and z of " + selectedPlane.ExtentZ);
//		showSearchingUI = false;

        this.selectedPlane = hit.Trackable as DetectedPlane;
        CreateAnchor(hit);
    }
Exemplo n.º 22
0
        /// <summary>
        /// Used to do exactly what the function name says
        /// <param name="_gameObject">The gameobject that comes with the post cloud anchor function - is not used here</param>
        /// <param name="_worldOriginAnchorSpawnLocation">The original cloud anchor trackable</param>
        /// </summary>
        public void AnchorWithOriginBeingDifferentAnchor(GameObject _gameObject, TrackableHit _worldOriginAnchorSpawnLocation)
        {
            //Place the new anchor at the world origin (but not the location of the world origin anchor - yes they're different and yes its annoying)
            TrackableHit nextCloudAnchorTrackable = new TrackableHit(new Pose(Vector3.zero, _worldOriginAnchorSpawnLocation.Pose.rotation),
                                                                     _worldOriginAnchorSpawnLocation.Distance, _worldOriginAnchorSpawnLocation.Flags, _worldOriginAnchorSpawnLocation.Trackable);


            //Set "TheWorld"'s initial position to the new cloud anchor's initial position
            ASL.ASLHelper.CreateARCoreCloudAnchor(nextCloudAnchorTrackable, null, SetInitialPositionToCloudAnchorsInitialPosition, true, false);
        }
Exemplo n.º 23
0
Arquivo: Card.cs Projeto: ramanxg/cARd
    public void AttachToAnchor(TrackableHit hit)
    {
        // if moving off plane
        if (hit.Trackable == null)
        {
            Debug.Log("Card off plane!");
            return;
        }

        // move to hit position
        transform.position = hit.Pose.position;

        // if moving to new plane
        if (hit.Trackable != detectedPlane)
        {
            Debug.Log("Moving Card to new plane!");
            detectedPlane = (DetectedPlane)hit.Trackable;
            return;
        }

        // if does not have an anchor or too far away from current anchor
        // give it an anchor
        if (anchor == null || (anchor.transform.position - transform.position).magnitude > 1)
        {
            // gets all existing anchors on this plane
            List <Anchor> existingAnchors = new List <Anchor>();
            detectedPlane.GetAllAnchors(existingAnchors);

            bool anchorFound = false;
            // look for a nearby existing anchor
            foreach (Anchor a in existingAnchors)
            {
                // if found a nearby anchor
                if ((a.transform.position - hit.Pose.position).magnitude < 1)
                {
                    Debug.Log("Moving card to existing anchor!");
                    anchor      = a;
                    anchorFound = true;
                    break;
                }
            }

            //if did not find an anchor, create a new one
            if (!anchorFound)
            {
                Debug.Log("Creating new anchor!");
                anchor = detectedPlane.CreateAnchor(hit.Pose);
            }

            transform.SetParent(anchor.transform);
        }

        //Debug.Log("Anchor Position: " + anchor.transform.position);
        //Debug.Log("Distance From Anchor: " + transform.localPosition.magnitude);
    }
        /// <summary>
        /// Continues the translation.
        /// </summary>
        /// <param name="gesture">The current gesture.</param>
        protected override void OnContinueManipulation(DragGesture gesture)
        {
            m_IsActive = true;

            TransformationUtility.Placement desiredPlacement =
                TransformationUtility.GetBestPlacementPosition(
                    transform.parent.position, gesture.Position, m_GroundingPlaneHeight,
                    s_ObjectVerticalPlacementOffset, MaxTranslationDistanceInMeters,
                    ObjectTranslationMode);

            // Discards invalid position.
            if (!desiredPlacement.HoveringPosition.HasValue ||
                !desiredPlacement.PlacementPosition.HasValue)
            {
                return;
            }

            m_ManipulatedObject = gesture.TargetObject;

            // Drops the value when collision occurs.
            if (TestCollision(desiredPlacement.PlacementPosition.Value))
            {
                m_CollisionEvent.Trigger(m_ManipulatedObject);
                return;
            }

            if (desiredPlacement.PlacementRotation.HasValue)
            {
                // Rotates if the plane direction has changed.
                if (((desiredPlacement.PlacementRotation.Value * Vector3.up) - transform.up)
                    .sqrMagnitude > k_MinimumSquaredDistance)
                {
                    m_CollisionEvent.Trigger(m_ManipulatedObject);
                    return;
                }
                else
                {
                    m_DesiredRotation = transform.rotation;
                }
            }

            // If desired position is lower than the current position, don't drop it until it's
            // finished.
            m_DesiredLocalPosition = transform.parent.InverseTransformPoint(
                desiredPlacement.HoveringPosition.Value);

            m_DesiredAnchorPosition = desiredPlacement.PlacementPosition.Value;

            m_GroundingPlaneHeight = desiredPlacement.UpdatedGroundingPlaneHeight;

            if (desiredPlacement.PlacementPlane.HasValue)
            {
                m_LastHit = desiredPlacement.PlacementPlane.Value;
            }
        }
Exemplo n.º 25
0
    public void SpawnToy(TrackableHit hit)
    {
        int randomToy = Random.Range(0, toyPrefabs.Count);

        // change lookrotation
        if (toyList.Count < 1)
        {
            spawnedToy = Instantiate(toyPrefabs[randomToy], hit.Pose.position, hit.Pose.rotation);
            toyList.Add(spawnedToy);
        }
    }
Exemplo n.º 26
0
    private List<GameObject> Planes = new List<GameObject>(); // 앵커 설치 전 인지된 바닥 리스트

    public bool Raycast(float x, float y, TrackableHitFlags filter, out TrackableHit hitResult)
    {
        bool foundHit = Frame.Raycast(x, y, filter, out hitResult);
        if (foundHit)
        {
            Pose worldPose = WorldToAnchorPose(hitResult.Pose);
            TrackableHit newHit = new TrackableHit(worldPose, hitResult.Distance, hitResult.Flags, hitResult.Trackable);
            hitResult = newHit;
        }

        return foundHit;
    }
Exemplo n.º 27
0
        /// <summary>
        /// Used to do exactly what the function name says
        /// </summary>
        /// <param name="_gameObject">The gameobject that comes with the post cloud anchor function - is not used here</param>
        /// <param name="_worldOriginAnchorSpawnLocation">The original cloud anchor trackable</param>
        public void ParentToAnchorWithOriginBeingDifferentAnchor(GameObject _gameObject, TrackableHit _worldOriginAnchorSpawnLocation)
        {
            //Place the new anchor at the world origin (but not the location of the world origin anchor - yes they're different and yes its annoying)
            TrackableHit nextCloudAnchorTrackable = new TrackableHit(new Pose(Vector3.zero, _worldOriginAnchorSpawnLocation.Pose.rotation),
                                                                     _worldOriginAnchorSpawnLocation.Distance, _worldOriginAnchorSpawnLocation.Flags, _worldOriginAnchorSpawnLocation.Trackable);

            mModel.GetComponent <ASL.ASLObject>().SendAndSetClaim(() =>
            {
                //Parent "TheWorld" to Cloud Anchor - Cloud Anchor is world origin
                ASL.ASLHelper.CreateARCoreCloudAnchor(nextCloudAnchorTrackable, mModel.GetComponent <ASL.ASLObject>(), null, true, false);
            });
        }
Exemplo n.º 28
0
    public void SpawnFood(TrackableHit hit)
    {
        int randomFood = Random.Range(0, foodPrefabs.Count);

        if (foodList.Count < 1)
        {
            //spawnedFood = Instantiate(foodPrefabs[randomFood], hit.Pose.position, hit.Pose.rotation);
            spawnedFood = Instantiate(foodPrefabs[randomFood], new Vector3(hit.Pose.position.x, stateMachineManager.player.spawnedPlayer.transform.position.y, hit.Pose.position.z), hit.Pose.rotation);
            //spawnedFood.transform.position = new Vector3(spawnedFood.transform.position.x, 0, spawnedFood.transform.position.z);
            foodList.Add(spawnedFood);
        }
    }
Exemplo n.º 29
0
        // Mouse click selection
        void FingerSelect()
        {
            Touch touch;

            // If the player has not touched the screen then the update is complete.
            if (Input.touchCount < 1 || (touch = Input.GetTouch(0)).phase != TouchPhase.Began)
            {
                return;
            }

            if (!EventSystem.current.IsPointerOverGameObject(touch.fingerId)) // check for GUI
            {
                //Ray cast to check hit location
                RaycastHit hitInfo = new RaycastHit();
                bool       hit     = Physics.Raycast(MainCamera.ScreenPointToRay(Input.GetTouch(0).position), out hitInfo, Mathf.Infinity, 1);

                if (hit)// if we hit a game object (does not detect if we hit a trackable plane to set cloud anchor)
                {
                    SelectObject(hitInfo.transform.gameObject);
                }
                else //if we did not hit a game object
                {
                    //If we haven't set a cloud anchor yet && we are the Host -> then we can set a cloud anchor
                    //Note: ASL does not prevent users from create unlimited cloud anchors, this means if two users create a cloud anchor at the same time
                    //With the same ASL object, there is the chance things will become out of sync. This if statement is one way to avoid that synchronization problem
                    if (ASL.ASLHelper.m_CloudAnchors.Count <= 0 && ASL.GameSparksManager.Instance().AmLowestPeer())
                    {
                        TrackableHit arcoreHitResult = new TrackableHit();
                        Pose?        m_LastHitPose   = null;

                        // Raycast against the location the player touched to search for planes. -> used for setting cloud anchor
                        if (ASL.ARWorldOriginHelper.Instance().Raycast(touch.position.x, touch.position.y,
                                                                       TrackableHitFlags.PlaneWithinPolygon, out arcoreHitResult))
                        {
                            m_LastHitPose = arcoreHitResult.Pose;
                        }

                        // If there was a successful hit on a trackable plane -> create a cloud anchor
                        if (m_LastHitPose != null)
                        {
                            DetermineCloudAnchorCreationStyle(arcoreHitResult);
                        }
                    }
                    else //If we haven't set a cloud anchor in the scene yet
                    {
                        m_CloudAnchorFeedback.text = "";
                        //if we have, then select nothing
                        SelectObject(null);
                    }
                }
            }
        }
        /// <summary>
        /// Function called when the manipulation is ended.
        /// </summary>
        /// <param name="gesture">The current gesture.</param>
        protected override void OnEndManipulation(TapGesture gesture)
        {
            if (gesture.WasCancelled)
            {
                return;
            }

            // If gesture is targeting an existing object we are done.
            if (gesture.TargetObject != null)
            {
                return;
            }

            // Raycast against the location the player touched to search for planes.
            TrackableHit      hit           = m_LastHit;
            TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon;

            if (Frame.Raycast(
                    gesture.StartPosition.x, gesture.StartPosition.y, raycastFilter, out hit))
            {
                // Use hit pose and camera pose to check if hittest is from the
                // back of the plane, if it is, no need to create the anchor.
                if ((hit.Trackable is DetectedPlane) &&
                    Vector3.Dot(FirstPersonCamera.transform.position - hit.Pose.position,
                                hit.Pose.rotation * Vector3.up) < 0)
                {
                    Debug.Log("Hit at back of the current DetectedPlane");
                }
                else
                {
                    // Instantiate game object at the hit pose.
                    var gameObject = Instantiate(StarPrefab, hit.Pose.position, hit.Pose.rotation);

                    // Instantiate manipulator.
                    var manipulator =
                        Instantiate(ManipulatorPrefab, hit.Pose.position, hit.Pose.rotation);

                    // Make game object a child of the manipulator.
                    gameObject.transform.parent = manipulator.transform;

                    // Create an anchor to allow ARCore to track the hitpoint as understanding of
                    // the physical world evolves.
                    var anchor = hit.Trackable.CreateAnchor(hit.Pose);

                    // Make manipulator a child of the anchor.
                    manipulator.transform.parent = anchor.transform;

                    // Select the placed object.
                    manipulator.GetComponent <Manipulator>().Select();
                }
            }
        }