Exemplo n.º 1
0
    // Update is called once per frame
    void Update()
    {
        if (Session.Status != SessionStatus.Tracking)
        {
            return;
        }
        if (detectedPlane == null)
        {
            return;
        }

        // Check for the plane being subsumed.
        // If the plane has been subsumed switch attachment to the subsuming plane.
        while (detectedPlane.SubsumedBy != null)
        {
            detectedPlane = detectedPlane.SubsumedBy;
        }

        transform.LookAt(firstPersonCamera.transform);

        // Move the position to stay consistent with the plane.
        transform.position = new Vector3(transform.position.x,
                                         detectedPlane.CenterPose.position.y + yOffset, transform.position.z);
    }
Exemplo n.º 2
0
 public static bool IsVerticalPlane(this DetectedPlane plane)
 {
     return(plane.PlaneType == DetectedPlaneType.Vertical);
 }
 public void SetPlane(DetectedPlane plane)
 {
     detectedPlane = plane;
     // Spawn a new snake.
     SpawnSnake();
 }
Exemplo n.º 4
0
        public void Update()
        {
            UpdateApplicationLifecycle();
            if (gameObjectTemp != null)
            {
                gameObjectTemp.transform.Rotate(0, SliderRotate.value, 0, Space.Self);
                gameObjectTemp.transform.localScale += SliderScale.value * scale;
            }

            // 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 hit;
            bool         foundHit = false;

            if (InstantPlacementMenu.IsInstantPlacementEnabled())
            {
                foundHit = Frame.RaycastInstantPlacement(touch.position.x, touch.position.y, 1.0f, out hit);
            }
            else
            {
                TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon | TrackableHitFlags.FeaturePointWithSurfaceNormal;
                foundHit = Frame.Raycast(touch.position.x, touch.position.y, raycastFilter, out hit);
            }

            if (foundHit)
            {
                // Choose the gameobject to place
                if (GameObjectIndex == 0)
                {
                    GameObjectVerticalPlanePrefab   = GameObjectRobot;
                    GameObjectHorizontalPlanePrefab = GameObjectRobot;
                    GameObjectPointPrefab           = GameObjectRobot;
                    InstantPlacementPrefab          = GameObjectRobot;
                }

                else if (GameObjectIndex == 1)
                {
                    GameObjectVerticalPlanePrefab   = GameObjectFox;
                    GameObjectHorizontalPlanePrefab = GameObjectFox;
                    GameObjectPointPrefab           = GameObjectFox;
                    InstantPlacementPrefab          = GameObjectFox;
                }

                else if (GameObjectIndex == 2)
                {
                    GameObjectVerticalPlanePrefab   = GameObjectCat;
                    GameObjectHorizontalPlanePrefab = GameObjectCat;
                    GameObjectPointPrefab           = GameObjectCat;
                    InstantPlacementPrefab          = GameObjectCat;
                }

                else if (GameObjectIndex == 3)
                {
                    GameObjectVerticalPlanePrefab   = GameObjectWindow;
                    GameObjectHorizontalPlanePrefab = GameObjectWindow;
                    GameObjectPointPrefab           = GameObjectWindow;
                    InstantPlacementPrefab          = GameObjectWindow;
                }

                // 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
                {
                    if (DepthMenu != null)
                    {
                        // Show depth card window if necessary.
                        DepthMenu.ConfigureDepthBeforePlacingFirstAsset();
                    }

                    // Choose the prefab based on the Trackable that got hit.
                    GameObject prefab;
                    if (hit.Trackable is InstantPlacementPoint)
                    {
                        prefab = InstantPlacementPrefab;
                    }
                    else if (hit.Trackable is FeaturePoint)
                    {
                        prefab = GameObjectPointPrefab;
                    }
                    else if (hit.Trackable is DetectedPlane)
                    {
                        DetectedPlane detectedPlane = hit.Trackable as DetectedPlane;
                        if (detectedPlane.PlaneType == DetectedPlaneType.Vertical)
                        {
                            prefab = GameObjectVerticalPlanePrefab;
                        }
                        else
                        {
                            prefab = GameObjectHorizontalPlanePrefab;
                        }
                    }
                    else
                    {
                        prefab = GameObjectHorizontalPlanePrefab;
                    }

                    // Instantiate prefab at the hit pose.
                    gameObjectTemp = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);

                    // Compensate for the hitPose rotation facing away from the raycast
                    if (GameObjectIndex != 3)
                    {
                        gameObjectTemp.transform.Rotate(0, _prefabRotation, 0, Space.Self);
                    }
                    // 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 game object a child of the anchor.
                    gameObjectTemp.transform.parent = anchor.transform;

                    // Initialize Instant Placement Effect.
                    if (hit.Trackable is InstantPlacementPoint)
                    {
                        gameObjectTemp.GetComponentInChildren <InstantPlacementEffect>().InitializeWithTrackable(hit.Trackable);
                    }
                }
            }
        }
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            _UpdateApplicationLifecycle();

            // 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      hit;
            TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
                                              TrackableHitFlags.FeaturePointWithSurfaceNormal;

            if (Frame.Raycast(touch.position.x, touch.position.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
                {
                    // Choose the Andy model for the Trackable that got hit.
                    GameObject prefab;
                    if (hit.Trackable is FeaturePoint)
                    {
                        prefab = AndyPointPrefab;
                    }
                    else if (hit.Trackable is DetectedPlane)
                    {
                        DetectedPlane detectedPlane = hit.Trackable as DetectedPlane;
                        if (detectedPlane.PlaneType == DetectedPlaneType.Vertical)
                        {
                            prefab = AndyVerticalPlanePrefab;
                        }
                        else
                        {
                            prefab = AndyHorizontalPlanePrefab;
                        }
                    }
                    else
                    {
                        prefab = AndyHorizontalPlanePrefab;
                    }

                    // Instantiate Andy model at the hit pose.
                    var andyObject = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);

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

                    // 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 Andy model a child of the anchor.
                    andyObject.transform.parent = anchor.transform;
                }
            }
        }
Exemplo n.º 6
0
    // Update is called once per frame
    void Update()
    {
        if (detectedPlane == null)
        {
            return;
        }

        if (detectedPlane.TrackingState != TrackingState.Tracking)
        {
            return;
        }

        // Check for the plane being subsumed
        // If the plane has been subsumed switch attachment to the subsuming plane.
        while (detectedPlane.SubsumedBy != null)
        {
            detectedPlane = detectedPlane.SubsumedBy;
        }

        //edamas senes
        if (foodInstance == null || foodInstance.activeSelf == false)
        {
            SpawnFoodInstance();
            return;
        }

        foodAge += Time.deltaTime;
        if (foodAge >= maxAge)
        {
            DestroyObject(foodInstance);
            foodInstance = null;
        }


        //needamas senes
        if (foodInstance2 == null || foodInstance2.activeSelf == false)
        {
            SpawnFoodInstance2();
            return;
        }

        foodAge += Time.deltaTime;
        if (foodAge >= maxAge)
        {
            DestroyObject(foodInstance2);
            foodInstance2 = null;
        }


        //augi
        if (foodInstance3 == null || foodInstance3.activeSelf == false)
        {
            SpawnFoodInstance3();
            return;
        }

        foodAge += Time.deltaTime;
        if (foodAge >= maxAge)
        {
            DestroyObject(foodInstance3);
            foodInstance3 = null;
        }
    }
Exemplo n.º 7
0
        public void Update()
        {
            _UpdateApplicationLifecycle();

            // 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      hit;
            TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
                                              TrackableHitFlags.FeaturePointWithSurfaceNormal;

            if (Frame.Raycast(touch.position.x, touch.position.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
                {
                    // Choose the prefab based on the Trackable that got hit.
                    GameObject prefab;
                    if (hit.Trackable is FeaturePoint)
                    {
                        prefab = GameObjectPointPrefab;
                    }
                    else if (hit.Trackable is DetectedPlane)
                    {
                        DetectedPlane detectedPlane = hit.Trackable as DetectedPlane;
                        if (detectedPlane.PlaneType == DetectedPlaneType.Vertical)
                        {
                            prefab = GameObjectVerticalPlanePrefab;
                        }
                        else
                        {
                            prefab = GameObjectHorizontalPlanePrefab;
                        }
                    }
                    else
                    {
                        prefab = GameObjectHorizontalPlanePrefab;
                    }

                    // Instantiate prefab at the hit pose.
                    var andyObject = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);

                    Points.Add(andyObject);

                    if (Points.Count >= 2)
                    {
                        andyObject.GetComponent <LineRenderer>().positionCount = 2;
                        andyObject.GetComponent <LineRenderer>().SetPosition(0, andyObject.transform.position);
                        andyObject.GetComponent <LineRenderer>().SetPosition(1, Points[Points.Count - 2].transform.position);

                        var temp = Instantiate(Text, (andyObject.transform.position + Points[Points.Count - 2].transform.position) / 2, Quaternion.identity);
                        temp.transform.LookAt(andyObject.transform.position);
                        temp.transform.localEulerAngles     = new Vector3(90, temp.transform.localEulerAngles.y + 90, 0);
                        temp.GetComponent <TextMesh>().text = (Vector3.Distance(andyObject.transform.position, Points[Points.Count - 2].transform.position) * 100).ToString("0.00");
                    }
                    // Compensate for the hitPose rotation facing away from the raycast (i.e.
                    // camera).
                    andyObject.transform.Rotate(0, k_PrefabRotation, 0, Space.Self);

                    // 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 game object a child of the anchor.
                    andyObject.transform.parent = anchor.transform;
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            _UpdateApplicationLifecycle();

            // 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      hit;
            TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
                                              TrackableHitFlags.FeaturePointWithSurfaceNormal;

            if (Frame.Raycast(touch.position.x, touch.position.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
                {
                    // Choose the prefab based on the Trackable that got hit.
                    GameObject prefab;
                    if (hit.Trackable is FeaturePoint)
                    {
                        prefab = GameObjectPointPrefab;
                    }
                    else if (hit.Trackable is DetectedPlane)
                    {
                        DetectedPlane detectedPlane = hit.Trackable as DetectedPlane;
                        if (detectedPlane.PlaneType == DetectedPlaneType.Vertical)
                        {
                            prefab = GameObjectVerticalPlanePrefab;
                        }
                        else
                        {
                            prefab = GameObjectHorizontalPlanePrefab;
                        }
                    }
                    else
                    {
                        prefab = GameObjectHorizontalPlanePrefab;
                    }

                    //// Instantiate prefab at the hit pose.
                    //var gameObject = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);

                    //// Compensate for the hitPose rotation facing away from the raycast (i.e.
                    //// camera).
                    //gameObject.transform.Rotate(0, k_PrefabRotation, 0, Space.Self);

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

                    // Выровнять якорь по горизонтали
                    Vector3 myEu = anchor.transform.eulerAngles;
                    myEu.x = 0.0f;
                    myEu.z = 0.0f;

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

                    // Скрыть генератор поверхностей
                    _PlaneGen.SetActive(false);

                    // Открыть объекты сцены
                    _GO_Root.transform.parent           = anchor.transform;
                    _GO_Root.transform.localPosition    = Vector3.zero;
                    _GO_Root.transform.localEulerAngles = Vector3.zero;
                    _GO_Root.SetActive(true);
                    _Text1.text = "Pos=" + _GO_Root.transform.position.ToString() + " Eu=" + _GO_Root.transform.eulerAngles.ToString();

                    // Установить поле зрения 45 градусов
                    FirstPersonCamera.fieldOfView = 45;
                    _RightCam.fieldOfView         = 45;
                }
            }
        }
Exemplo n.º 9
0
 public bool EqualsPlane(DetectedPlane plane)
 {
     return(plane.GetHashCode() == this.PlaneCode);
 }
Exemplo n.º 10
0
 public DetectedPlatform(DetectedPlane plane) : base(plane.m_TrackableNativeHandle, plane.m_NativeSession)
 {
     PlaneCode = plane.GetHashCode();
 }
Exemplo n.º 11
0
 void SetSelectedPlane(DetectedPlane selectedPlane)
 {
     // Plane controller set plane function
     planeController.SetSelectedPlane(selectedPlane);
 }
Exemplo n.º 12
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            UpdateApplicationLifecycle();

            if (DepthMenu != null && !DepthMenu.CanPlaceAsset())
            {
                return;
            }

            // 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      hit;
            TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
                                              TrackableHitFlags.FeaturePointWithSurfaceNormal;

            // To use Instant Placement, which supports frame by frame 2D tracking and
            // automatically switches to 6DOF tracking once it's available, follow these steps:
            // 1. Use InstantPlacementMode.LocalYUp in ARCoreSessionConfig.
            // 2. Use Frame.RaycastInstantPlacement(float, float, float, out TrackableHit) method
            // with an approximate distance in meters.
            // 3. Create anchor with the hit result from previous step by:
            // hit.Trackable.CreateAnchor(hit.Pose).
            //
            // An anchor will be created at the approximate pose if there has been no Trackable
            // detected yet, and updates its pose to attach to the real world.
            // Note: there may be a noticeable jump in position during this tracking method change.
            // Use InstantPlacementPoint.TrackingMethod to customize pose update logic.
            //
            // See the Instant Placement Developer's Guide at:
            // https://developers.google.com/ar/develop/unity/instant-placement.
            if (Frame.Raycast(touch.position.x, touch.position.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
                {
                    if (DepthMenu != null)
                    {
                        // Show depth card window if necessary.
                        DepthMenu.ConfigureDepthBeforePlacingFirstAsset();
                    }

                    // Choose the prefab based on the Trackable that got hit.
                    GameObject prefab;
                    if (hit.Trackable is FeaturePoint)
                    {
                        prefab = GameObjectPointPrefab;
                    }
                    else if (hit.Trackable is DetectedPlane)
                    {
                        DetectedPlane detectedPlane = hit.Trackable as DetectedPlane;
                        if (detectedPlane.PlaneType == DetectedPlaneType.Vertical)
                        {
                            prefab = GameObjectVerticalPlanePrefab;
                        }
                        else
                        {
                            prefab = GameObjectHorizontalPlanePrefab;
                        }
                    }
                    else
                    {
                        prefab = GameObjectHorizontalPlanePrefab;
                    }

                    // Instantiate prefab at the hit pose.
                    var gameObject = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);

                    // Compensate for the hitPose rotation facing away from the raycast (i.e.
                    // camera).
                    gameObject.transform.Rotate(0, _prefabRotation, 0, Space.Self);

                    // 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 game object a child of the anchor.
                    gameObject.transform.parent = anchor.transform;
                }
            }
        }
Exemplo n.º 13
0
    /// <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)
        {
            //Debug.Log("\nTarget Object != null");
            return;
        }

        if (IsPointerOverUIObject())
        {
            //Debug.Log("\n\nIsPointerOverUIObject");
            return;
        }
        // Raycast against the location the player touched to search for planes.
        TrackableHit      hit;
        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.
                DetectedPlane detectedPlane = hit.Trackable as DetectedPlane;

                //Debug.Log("\n\n\n\n\ndetectedPlane.PlaneType=" + detectedPlane.PlaneType.ToString());
                //Debug.Log("DetectedPlaneType.HorizontalUpwardFacing=" + DetectedPlaneType.HorizontalUpwardFacing.ToString());
                //Debug.Log("currentNumberOfObjects=" + currentNumberOfObjects.ToString());
                //Debug.Log("numberOfObjectsAllowed=" + numberOfObjectsAllowed.ToString());
                //Debug.Log("===>Condition=" + (detectedPlane.PlaneType == DetectedPlaneType.HorizontalUpwardFacing && currentNumberOfObjects < numberOfObjectsAllowed).ToString());
                //if (detectedPlane.PlaneType == DetectedPlaneType.Vertical && currentNumberOfVerticalObjects < numberOfObjectsAllowed)
                // {
                //GameObject modelprefab = Instantiate(GameObjectVerticalPlanePrefab, hit.Pose.position, hit.Pose.rotation);
                // GenerateModels(modelprefab, hit);
                // currentNumberOfVerticalObjects++;
                //}
                //else if (detectedPlane.PlaneType == DetectedPlaneType.HorizontalUpwardFacing && currentNumberOfObjects < numberOfObjectsAllowed )
                //{
                //floor
                //Debug.Log("\n\n hit horizontal !!!!!");

                //int prefabval = SetValue.getprefab();
                //if (prefabval == 0)
                //{
                //GameObject modelprefab = Instantiate(tablePrefab, hit.Pose.position, hit.Pose.rotation);
                //GenerateModels(modelprefab, hit);
                //}
                //else
                //{
                if (detectedPlane.PlaneType == DetectedPlaneType.Vertical || detectedPlane.PlaneType == DetectedPlaneType.HorizontalDownwardFacing || detectedPlane.PlaneType == DetectedPlaneType.HorizontalUpwardFacing)
                {
                    Vector3    pos            = hit.Pose.position;
                    GameObject currGameObject = ItemListener.getSelectedGameObject();
                    if (currGameObject != null)
                    {
                        //hit.Pose.rotation
                        GameObject modelprefab = Instantiate(currGameObject, pos, hit.Pose.rotation);
                        //modelprefab.transform.localScale = new Vector3(0.01f, 0.01f, 0.01f);
                        //modelprefab.AddComponent<BoxCollider>();

                        GenerateModels(modelprefab, hit);
                    }
                }

                //}

                //currentNumberOfObjects++;
                //}
                //else if (detectedPlane.PlaneType == DetectedPlaneType.HorizontalDownwardFacing && currentNumberOfUpObjects < numberOfObjectsAllowed)
                //{
                //   GameObject modelprefab = Instantiate(GameObjectHorizontalUpwardPlanePrefab, hit.Pose.position, hit.Pose.rotation);
                //   GenerateModels(modelprefab, hit);
                //   currentNumberOfUpObjects++;
                //}
            }
        }
    }
Exemplo n.º 14
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            if ((Input.touchCount == 1) && (Input.GetTouch(0).phase == TouchPhase.Began))
            {
                RaycastHit hitElem;
                Ray        ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
                if (Physics.Raycast(ray, out hitElem))
                {
                    if (hitElem.collider.gameObject.tag == "QuitAnim")
                    {
                        //feedbackText.text = "Quit anim clicked!";
                        overlay.SetActive(false);
                        cAnimController.SetActive(false);
                        alAnimController.SetActive(false);
                        hAnimController.SetActive(false);
                        caAnimController.SetActive(false);
                        oAnimController.SetActive(false);
                    }

                    if (hitElem.collider.gameObject.tag == "H")
                    {
                        //feedbackText.text = "H clicked!";
                        overlay.SetActive(true);
                        hAnimController.SetActive(true);
                    }

                    if (hitElem.collider.gameObject.tag == "O")
                    {
                        //feedbackText.text = "O clicked!";
                        overlay.SetActive(true);
                        oAnimController.SetActive(true);
                    }

                    if (hitElem.collider.gameObject.tag == "C")
                    {
                        //feedbackText.text = "C clicked!";
                        overlay.SetActive(true);
                        cAnimController.SetActive(true);
                    }

                    if (hitElem.collider.gameObject.tag == "Ca")
                    {
                        //feedbackText.text = "Ca clicked!";
                        overlay.SetActive(true);
                        caAnimController.SetActive(true);
                    }

                    if (hitElem.collider.gameObject.tag == "Al")
                    {
                        //feedbackText.text = "Al clicked!";
                        overlay.SetActive(true);
                        alAnimController.SetActive(true);
                    }
                }
            }

            _UpdateApplicationLifecycle();

            if (!objInstantiated)
            {
                if (DepthMenu != null && !DepthMenu.CanPlaceAsset())
                {
                    return;
                }

                // 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      hit;
                TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
                                                  TrackableHitFlags.FeaturePointWithSurfaceNormal;

                if (Frame.Raycast(touch.position.x, touch.position.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
                    {
                        if (DepthMenu != null)
                        {
                            // Show depth card window if necessary.
                            DepthMenu.ConfigureDepthBeforePlacingFirstAsset();
                        }

                        // Choose the prefab based on the Trackable that got hit.
                        GameObject prefab;
                        if (hit.Trackable is FeaturePoint)
                        {
                            prefab = GameObjectPointPrefab;
                        }
                        else if (hit.Trackable is DetectedPlane)
                        {
                            DetectedPlane detectedPlane = hit.Trackable as DetectedPlane;
                            if (detectedPlane.PlaneType == DetectedPlaneType.Vertical)
                            {
                                prefab = GameObjectVerticalPlanePrefab;
                            }
                            else
                            {
                                prefab = GameObjectHorizontalPlanePrefab;
                            }
                        }
                        else
                        {
                            prefab = GameObjectHorizontalPlanePrefab;
                        }
                        // Instantiate prefab at the hit pose.
                        var gameObject = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);

                        overlay          = GameObject.FindWithTag("DarkOverlay");
                        cAnimController  = GameObject.FindWithTag("CarbonAnimator");
                        alAnimController = GameObject.FindWithTag("AlluminumAnimator");
                        hAnimController  = GameObject.FindWithTag("HydrogenAnimator");
                        caAnimController = GameObject.FindWithTag("CalciumAnimator");
                        oAnimController  = GameObject.FindWithTag("OxygenAnimator");

                        overlay.SetActive(false);
                        cAnimController.SetActive(false);
                        alAnimController.SetActive(false);
                        hAnimController.SetActive(false);
                        caAnimController.SetActive(false);
                        oAnimController.SetActive(false);

                        // Compensate for the hitPose rotation facing away from the raycast (i.e.
                        // camera).
                        gameObject.transform.Rotate(0, k_PrefabRotation, 0, Space.Self);

                        // 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 game object a child of the anchor.
                        gameObject.transform.parent = anchor.transform;

                        gameObject.name = "Cube";

                        objInstantiated = true;
                    }
                }
            }

            /*else
             * {
             *  StopTrackingSurfaces();
             * }*/
        }
Exemplo n.º 15
0
 public void SetCurrentPlane(DetectedPlane plane)
 {
     CurrentPlane = plane;
 }
Exemplo n.º 16
0
 private void TestPlaneOn(DetectedPlane plane)
 {
     testPlaneDisplay.DisplayTestPlane(plane, selectedObjectCollider);
     testPlaneDisplayed = true;
 }
Exemplo n.º 17
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void UpdateObjectPlacer()
        {
            _UpdateApplicationLifecycle();

            // 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;
            }

            //Check if it collided with another object
            if (!IsReplacing && !IsPlacing)
            {
                Ray        ray = Camera.main.ScreenPointToRay(touch.position);
                RaycastHit firstHit;
                if (Physics.Raycast(ray, out firstHit))
                {
                    if (firstHit.collider.tag == "Object")
                    {
                        IsPlacing   = true;
                        IsReplacing = true;

                        //SELECT OBJECT
                        SelectedObject = firstHit.collider.gameObject;
                        AppManager.Instance.ActivatePlacingUI();

                        //CHANTE MATERIAL
                        ChangeObjectMaterial(SelectedObject, SelectedColor);

                        return;
                    }
                }
            }

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

            if (Frame.Raycast(touch.position.x, touch.position.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
                {
                    // Choose the Andy model for the Trackable that got hit.
                    GameObject prefab;
                    //Remove trackable points intantiation
                    if (hit.Trackable is FeaturePoint)
                    {
                        prefab = AndyPointPrefab;
                    }
                    else if (hit.Trackable is DetectedPlane)
                    {
                        DetectedPlane detectedPlane = hit.Trackable as DetectedPlane;
                        if (detectedPlane.PlaneType == DetectedPlaneType.Vertical)
                        {
                            //Vertical
                            prefab = CurrentCatalogObject.Prefab;
                        }
                        else
                        {
                            //Horizontal plane
                            prefab = CurrentCatalogObject.Prefab;
                        }
                    }
                    else
                    {
                        //Horizontal
                        prefab = CurrentCatalogObject.Prefab;
                    }

                    GameObject andyObject;
                    if (IsPlacing)
                    {
                        if (IsReplacing)
                        {
                            andyObject = SelectedObject;
                            andyObject.transform.position = hit.Pose.position;
                            andyObject.transform.rotation = hit.Pose.rotation;
                        }
                        else
                        {
                            andyObject = placedModels[placedModels.Count - 1];
                            andyObject.transform.position = hit.Pose.position;
                            andyObject.transform.rotation = hit.Pose.rotation;
                        }
                    }
                    //If not placing a object, Instantiante new one
                    else
                    {
                        //// Instantiate Andy model at the hit pose.
                        andyObject = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);
                        placedModels.Add(andyObject);
                        IsPlacing = true;

                        // 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 Andy model a child of the anchor.
                        andyObject.transform.parent = anchor.transform;

                        //CHANGE COLOR
                        ChangeObjectMaterial(andyObject, SelectedColor);


                        AppManager.Instance.ActivatePlacingUI();
                    }

                    // Compensate for the hitPose rotation facing away from the raycast (i.e.
                    // camera).
                    andyObject.transform.Rotate(0, k_ModelRotation, 0, Space.Self);
                }
            }
        }
Exemplo n.º 18
0
        private void PerformHitTest(Vector2 touchPos)
        {
            var planeType = DetectedPlaneType.HorizontalUpwardFacing;

            if (Application.platform == RuntimePlatform.IPhonePlayer)
            {
#if ARCORE_IOS_SUPPORT
                var     session       = UnityARSessionNativeInterface.GetARSessionNativeInterface();
                var     viewportPoint = Controller.MainCamera.ScreenToViewportPoint(touchPos);
                ARPoint arPoint       = new ARPoint
                {
                    x = viewportPoint.x,
                    y = viewportPoint.y
                };

                _hitResultList = session.HitTest(arPoint,
                                                 ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent);
                if (_hitResultList.Count > 0)
                {
                    // Fetch the closest hit result.
                    int minDistanceIndex = GetMinDistanceIndex(_hitResultList);

                    string identifier = _hitResultList[minDistanceIndex].anchorIdentifier;
                    if (_arPlaneAligmentMapping.ContainsKey(identifier))
                    {
                        planeType = _arPlaneAligmentMapping[identifier] ==
                                    ARPlaneAnchorAlignment.ARPlaneAnchorAlignmentVertical ?
                                    DetectedPlaneType.Vertical : DetectedPlaneType.HorizontalUpwardFacing;
                    }
                    else
                    {
                        Debug.LogWarningFormat("Didn't find anchor identifier: {0}", identifier);
                        return;
                    }

                    Pose hitPose = new Pose();
                    hitPose.position = UnityARMatrixOps.GetPosition(
                        _hitResultList[minDistanceIndex].worldTransform);
                    if (planeType == DetectedPlaneType.Vertical)
                    {
                        hitPose.rotation = UnityARMatrixOps.GetRotation(
                            _hitResultList[minDistanceIndex].worldTransform);
                    }
                    else
                    {
                        // Point the hitPose rotation roughly away from the raycast/camera
                        // to match ARCore.
                        hitPose.rotation.eulerAngles =
                            new Vector3(0.0f, Controller.MainCamera.transform.eulerAngles.y, 0.0f);
                    }

                    _hitPose = hitPose;
                    var anchorGO = new GameObject("ARUserAnchor");
                    _anchorComponent            = anchorGO.AddComponent <UnityARUserAnchorComponent>();
                    anchorGO.transform.position = hitPose.position;
                    anchorGO.transform.rotation = hitPose.rotation;
                }
#endif
            }
            else
            {
                TrackableHit arcoreHitResult = new TrackableHit();
                if (Frame.Raycast(touchPos.x, touchPos.y, TrackableHitFlags.PlaneWithinPolygon,
                                  out arcoreHitResult))
                {
                    DetectedPlane plane = arcoreHitResult.Trackable as DetectedPlane;
                    if (plane == null)
                    {
                        Debug.LogWarning("Hit test result has invalid trackable type: " +
                                         arcoreHitResult.Trackable.GetType());
                        return;
                    }

                    planeType        = plane.PlaneType;
                    _hitPose         = arcoreHitResult.Pose;
                    _anchorComponent =
                        arcoreHitResult.Trackable.CreateAnchor(arcoreHitResult.Pose);
                }
            }

            if (_anchorComponent != null)
            {
                Instantiate(CloudAnchorPrefab, _anchorComponent.transform);

                // Attach map quality indicator to this pawn.
                var indicatorGO =
                    Instantiate(MapQualityIndicatorPrefab, _anchorComponent.transform);
                _qualityIndicator = indicatorGO.GetComponent <MapQualityIndicator>();
                _qualityIndicator.DrawIndicator(planeType, Controller.MainCamera);

                InstructionText.text = " To save this location, walk around the object to " +
                                       "capture it from different angles";
                DebugText.text = "Waiting for sufficient mapping quaility...";

                // Hide plane generator so users can focus on the object they placed.
                Controller.PlaneGenerator.SetActive(false);
            }
        }
Exemplo n.º 19
0
 public void SetSelectedPlane(DetectedPlane detectedPlane)
 {
     this.detectedPlane = detectedPlane;
     CreateAnchor();
 }
Exemplo n.º 20
0
 /// <summary>
 /// Select the plane attached to the nutrition panel
 /// </summary>
 void SetSelectedPlane(DetectedPlane selectedPlane)
 {
     // Call for nutrition panel controller : Anchor scoreboard to the selected plane
     nutritionPanel.SetSelectedPlane(selectedPlane);
 }
Exemplo n.º 21
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            _UpdateApplicationLifecycle();

            // 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      hit;
            TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
                                              TrackableHitFlags.FeaturePointWithSurfaceNormal;

            if (Frame.Raycast(touch.position.x, touch.position.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
                {
                    // Choose the prefab based on the Trackable that got hit.
                    GameObject prefab;
                    if (hit.Trackable is FeaturePoint)
                    {
                        prefab = GameObjectPointPrefab;
                    }
                    else if (hit.Trackable is DetectedPlane)
                    {
                        DetectedPlane detectedPlane = hit.Trackable as DetectedPlane;
                        if (detectedPlane.PlaneType == DetectedPlaneType.Vertical)
                        {
                            prefab = GameObjectVerticalPlanePrefab;
                        }
                        else
                        {
                            prefab = GameObjectHorizontalPlanePrefab;
                        }
                    }
                    else
                    {
                        prefab = GameObjectHorizontalPlanePrefab;
                    }

                    // trying to instantiate only one dragon instead of the many that one can instantiate otherwise in HelloAR orignal code
                    //one dragon is easier to control

                    if (numDragons < 2)

                    {
                        // Instantiate prefab at the hit pose.
                        gameObject2 = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);

                        // Compensate for the hitPose rotation facing away from the raycast (i.e.
                        // camera).
                        gameObject2.transform.Rotate(0, k_PrefabRotation, 0, Space.Self);

                        // 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 game object a child of the anchor.
                        gameObject2.transform.parent = anchor.transform;

                        numDragons += 1;
                    }

                    //trying to move dragon around based on screen tilt

                    if (Input.deviceOrientation == DeviceOrientation.FaceDown)
                    {
                        gameObject2.transform.Translate(Vector3.forward * Time.deltaTime, Space.World);
                    }

                    if (Input.deviceOrientation == DeviceOrientation.FaceUp)
                    {
                        gameObject2.transform.Translate(Vector3.back * Time.deltaTime, Space.World);
                    }

                    if (Input.deviceOrientation == DeviceOrientation.LandscapeLeft)
                    {
                        gameObject2.transform.Translate(Vector3.left * Time.deltaTime, Space.World);
                    }

                    if (Input.deviceOrientation == DeviceOrientation.LandscapeRight)
                    {
                        gameObject2.transform.Translate(Vector3.right * Time.deltaTime, Space.World);
                    }

                    if (Input.touchCount > 0)
                    { //if there is any touch
                        touchDuration += Time.deltaTime;
                        touch          = Input.GetTouch(0);

                        if (touch.phase == TouchPhase.Ended && touchDuration < 0.2f) //making sure it only check the touch once && it was a short touch/tap and not a dragging.
                        {
                            StartCoroutine("singleOrDouble");
                        }
                    }
                    else
                    {
                        touchDuration = 0.0f;
                    }
                }

                // trying to make the zombie jump on double tap

                IEnumerator singleOrDouble()
                {
                    yield return(new WaitForSeconds(0.3f));

                    if (touch.tapCount == 1)
                    {
                        Debug.Log("Single");
                    }
                    else if (touch.tapCount == 2)
                    {
                        //this coroutine has been called twice. We should stop the next one here otherwise we get two double tap
                        StopCoroutine("singleOrDouble");
                        Debug.Log("Double");
                        gameObject2.transform.Translate(Vector3.up * 260 * Time.deltaTime, Space.World);
                    }
                }
            }
        }
 void SetSelectedPlane(DetectedPlane selectedPlane)
 {
     Debug.Log("Selected plane centered at " + selectedPlane.CenterPose.position);
     // Add to the end of SetSelectedPlane.
     scoreboard.SetSelectedPlane(selectedPlane);
 }
Exemplo n.º 23
0
    public GameObject[] plants;        //augi


    public void SetSelectedPlane(DetectedPlane selectedPlane)
    {
        detectedPlane = selectedPlane;
    }
Exemplo n.º 24
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            // To use Recording API:
            // 1. Create an instance of ARCoreRecordingConfig. The Mp4DatasetFilepath needs to
            // be accessible by the app, e.g. Application.persistentDataPath, or you can request
            // the permission of external storage.
            // 2. Call Session.StartRecording(ARCoreRecordingConfig) when a valid ARCore session
            // is available.
            // 3. Call Session.StopRecording() to end the recording. When
            // ARCoreRecordingConfig.AutoStopOnPause is true, it can also stop recording when
            // the ARCoreSession component is disabled.
            // To use Playback API:
            // 1. Pause the session by disabling ARCoreSession component.
            // 2. In the next frame or later, call Session.SetPlaybackDataset(datasetFilepath)
            // where the datasetFilepath is the same one used by Recording API.
            // 3. In the next frame or later, resume the session by enabling ARCoreSession component
            // and the app will play the recorded camera stream install of using the real time
            // camera stream.
            UpdateApplicationLifecycle();

            // 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      hit;
            bool              foundHit      = false;
            TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
                                              TrackableHitFlags.FeaturePointWithSurfaceNormal;

            // Allows the depth image to be queried for hit tests.
            raycastFilter |= TrackableHitFlags.Depth;
            foundHit       = Frame.Raycast(touch.position.x, touch.position.y, raycastFilter, out hit);
            if (!foundHit && InstantPlacementMenu.IsInstantPlacementEnabled())
            {
                foundHit = Frame.RaycastInstantPlacement(
                    touch.position.x, touch.position.y, 1.0f, out hit);
            }

            if (foundHit)
            {
                // 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
                {
                    if (DepthMenu != null)
                    {
                        // Show depth card window if necessary.
                        DepthMenu.ConfigureDepthBeforePlacingFirstAsset();
                    }

                    // Choose the prefab based on the Trackable that got hit.
                    GameObject prefab;
                    if (hit.Trackable is InstantPlacementPoint)
                    {
                        prefab = InstantPlacementPrefab;
                    }
                    else if (hit.Trackable is FeaturePoint)
                    {
                        prefab = GameObjectPointPrefab;
                    }
                    else if (hit.Trackable is DepthPoint)
                    {
                        prefab = GameObjectDepthPointPrefab;
                    }
                    else if (hit.Trackable is DetectedPlane)
                    {
                        DetectedPlane detectedPlane = hit.Trackable as DetectedPlane;
                        if (detectedPlane.PlaneType == DetectedPlaneType.Vertical)
                        {
                            prefab = GameObjectVerticalPlanePrefab;
                        }
                        else
                        {
                            prefab = GameObjectHorizontalPlanePrefab;
                        }
                    }
                    else
                    {
                        prefab = GameObjectHorizontalPlanePrefab;
                    }

                    // Instantiate prefab at the hit pose.
                    var gameObject = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);

                    // Compensate for the hitPose rotation facing away from the raycast (i.e.
                    // camera).
                    gameObject.transform.Rotate(0, _prefabRotation, 0, Space.Self);

                    // 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 game object a child of the anchor.
                    gameObject.transform.parent = anchor.transform;

                    // Initialize Instant Placement Effect.
                    if (hit.Trackable is InstantPlacementPoint)
                    {
                        gameObject.GetComponentInChildren <InstantPlacementEffect>()
                        .InitializeWithTrackable(hit.Trackable);
                    }
                }
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Calculates the best position to place an object in AR based on screen position.
        /// Could be used for tapping a location on the screen, dragging an object, or using a fixed
        /// cursor in the center of the screen for placing and moving objects.
        ///
        /// Objects are placed along the x/z of the grounding plane. When placed on an AR plane
        /// below the grounding plane, the object will drop straight down onto it in world space.
        /// This prevents the object from being pushed deeper into the scene when moving from a
        /// higher plane to a lower plane. When moving from a lower plane to a higher plane, this
        /// function returns a new groundingPlane to replace the old one.
        /// </summary>
        /// <returns>The best placement position.</returns>
        /// <param name="currentAnchorPosition">Position of the parent anchor, i.e., where the
        /// object is before translation starts.</param>
        /// <param name="screenPos">Location on the screen in pixels to place the object at.</param>
        /// <param name="groundingPlaneHeight">The starting height of the plane that the object is
        /// being placed along.</param>
        /// <param name="hoverOffset">How much should the object hover above the groundingPlane
        /// before it has been placed.</param>
        /// <param name="maxTranslationDistance">The maximum distance that the object can be
        /// translated.</param>
        /// <param name="translationMode">The translation mode, indicating the plane types allowed.
        /// </param>
        public static Placement GetBestPlacementPosition(
            Vector3 currentAnchorPosition,
            Vector2 screenPos,
            float groundingPlaneHeight,
            float hoverOffset,
            float maxTranslationDistance,
            TranslationMode translationMode)
        {
            Placement result = new Placement();

            result.UpdatedGroundingPlaneHeight = groundingPlaneHeight;

            // Get the angle between the camera and the object's down direction.
            float angle = Vector3.Angle(Camera.main.transform.forward, Vector3.down);

            angle = 90.0f - angle;

            float touchOffsetRatio  = Mathf.Clamp01(angle / 90.0f);
            float screenTouchOffset = touchOffsetRatio * k_MaxScreenTouchOffset;

            screenPos.y += GestureTouchesUtility.InchesToPixels(screenTouchOffset);

            float hoverRatio = Mathf.Clamp01(angle / 45.0f);

            hoverOffset *= hoverRatio;

            float distance           = (Camera.main.transform.position - currentAnchorPosition).magnitude;
            float distanceHoverRatio = Mathf.Clamp01(distance / k_HoverDistanceThreshold);

            hoverOffset *= distanceHoverRatio;

            // The best estimate of the point in the plane where the object will be placed:
            Vector3 groundingPoint;

            // Get the ray to cast into the scene from the perspective of the camera.
            TrackableHit hit;

            if (Frame.Raycast(
                    screenPos.x, screenPos.y, TrackableHitFlags.PlaneWithinBounds, out hit))
            {
                if (hit.Trackable is DetectedPlane)
                {
                    DetectedPlane plane = hit.Trackable as DetectedPlane;
                    if (IsPlaneTypeAllowed(translationMode, plane.PlaneType))
                    {
                        // Avoid detecting the back of existing planes.
                        if ((hit.Trackable is DetectedPlane) &&
                            Vector3.Dot(Camera.main.transform.position - hit.Pose.position,
                                        hit.Pose.rotation * Vector3.up) < 0)
                        {
                            Debug.Log("Hit at back of the current DetectedPlane");
                            return(result);
                        }

                        // Don't allow hovering for vertical or horizontal downward facing planes.
                        if (plane.PlaneType == DetectedPlaneType.Vertical ||
                            plane.PlaneType == DetectedPlaneType.HorizontalDownwardFacing)
                        {
                            // Limit the translation to maxTranslationDistance.
                            groundingPoint = LimitTranslation(
                                hit.Pose.position, currentAnchorPosition, maxTranslationDistance);
                            groundingPoint.y                   = groundingPlaneHeight;
                            result.PlacementPlane              = hit;
                            result.PlacementPosition           = groundingPoint;
                            result.HoveringPosition            = groundingPoint;
                            result.UpdatedGroundingPlaneHeight = groundingPoint.y;
                            //result.PlacementRotation = hit.Pose.rotation;
                            return(result);
                        }

                        // Allow hovering for horizontal upward facing planes.
                        if (plane.PlaneType == DetectedPlaneType.HorizontalUpwardFacing)
                        {
                            // Return early if the camera is pointing upwards.
                            if (angle < 0f)
                            {
                                return(result);
                            }

                            // Limit the translation to maxTranslationDistance.
                            groundingPoint = LimitTranslation(
                                hit.Pose.position, currentAnchorPosition, maxTranslationDistance);
                            groundingPoint.y = groundingPlaneHeight; //changed
                            // Find the hovering position by casting from the camera onto the
                            // grounding plane and offsetting the result by the hover offset.
                            result.HoveringPosition = groundingPoint + (Vector3.up * hoverOffset);

                            // If the AR Plane is above the grounding plane, then the hit plane's
                            // position is used to replace the current groundingPlane. Otherwise,
                            // the hit is ignored because hits are only detected on lower planes by
                            // casting straight downwards in world space.
                            if (groundingPoint.y > groundingPlaneHeight)
                            {
                                result.PlacementPlane              = hit;
                                result.PlacementPosition           = groundingPoint;
                                result.UpdatedGroundingPlaneHeight = hit.Pose.position.y;
                                //result.PlacementRotation = hit.Pose.rotation;
                                return(result);
                            }
                        }
                        else
                        {
                            // Not supported plane type.
                            return(result);
                        }
                    }
                    else
                    {
                        // Plane type not allowed.
                        return(result);
                    }
                }
                else
                {
                    // Hit is not a plane.
                    return(result);
                }
            }

            // Return early if the camera is pointing upwards.
            if (angle < 0f)
            {
                return(result);
            }

            // If the grounding point is lower than the current gorunding plane height, or if the
            // raycast did not return a hit, then we extend the grounding plane to infinity, and do
            // a new raycast into the scene from the perspective of the camera.
            Ray   cameraRay      = Camera.main.ScreenPointToRay(screenPos);
            Plane groundingPlane =
                new Plane(Vector3.up, new Vector3(0.0f, groundingPlaneHeight, 0.0f));

            // Find the hovering position by casting from the camera onto the grounding plane
            // and offsetting the result by the hover offset.
            float enter;

            if (groundingPlane.Raycast(cameraRay, out enter))
            {
                groundingPoint = LimitTranslation(
                    cameraRay.GetPoint(enter), currentAnchorPosition, maxTranslationDistance);
                groundingPoint.y        = groundingPlaneHeight; //changed
                result.HoveringPosition = groundingPoint + (Vector3.up * hoverOffset);
            }
            else
            {
                // If we can't successfully cast onto the groundingPlane, just return early.
                return(result);
            }

            // Cast straight down onto AR planes that are lower than the current grounding plane.
            if (Frame.Raycast(
                    groundingPoint + (Vector3.up * k_DownRayOffset), Vector3.down,
                    out hit, Mathf.Infinity, TrackableHitFlags.PlaneWithinBounds))
            {
                result.PlacementPosition = hit.Pose.position;
                result.PlacementPlane    = hit;
                //result.PlacementRotation = hit.Pose.rotation;
                //result.UpdatedGroundingPlaneHeight = groundingPlaneHeight;//changed
                return(result);
            }

            return(result);
        }
Exemplo n.º 26
0
Arquivo: Card.cs Projeto: ramanxg/cARd
 public void SetSelectedPlane(TrackableHit hit)
 {
     Debug.Log("Setting plane to: " + hit.Trackable);
     detectedPlane = (DetectedPlane)hit.Trackable;
     AttachToAnchor(hit);
 }
    void Update()
    {
        _UpdateApplicationLifecycle();
        Touch touch;

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

        TrackableHit      hit;
        TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
                                          TrackableHitFlags.FeaturePointWithSurfaceNormal;

        if (Frame.Raycast(touch.position.x, touch.position.y, raycastFilter, out 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
            {
                GameObject prefab;
                if (hit.Trackable is FeaturePoint)
                {
                    prefab     = _respawnPoint;
                    _isStarted = true;
                }
                else if (hit.Trackable is DetectedPlane)
                {
                    DetectedPlane detectedPlane = hit.Trackable as DetectedPlane;
                    if (detectedPlane.PlaneType == DetectedPlaneType.Vertical)
                    {
                        prefab     = _respawnPoint;
                        _isStarted = true;
                    }
                    else
                    {
                        prefab     = _respawnPoint;
                        _isStarted = true;
                    }
                }
                else
                {
                    prefab     = _respawnPoint;
                    _isStarted = true;
                }
                var RespawnPoint = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);

                RespawnPoint.transform.Rotate(0, k_ModelRotation, 0, Space.Self);

                var anchor = hit.Trackable.CreateAnchor(hit.Pose);

                RespawnPoint.transform.parent = anchor.transform;
            }
        }
    }
Exemplo n.º 28
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            _UpdateApplicationLifecycle();

            //Checks the current phase
            CheckPhase();

            //If we are in the Display Phase, we need to check touches to set the furniture
            if (currentPhase == Phase.Display)
            {
                // 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      hit;
                TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
                                                  TrackableHitFlags.FeaturePointWithSurfaceNormal;

                if (Frame.Raycast(touch.position.x, touch.position.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
                    {
                        // Choose the Kivik model for the Trackable that got hit.
                        GameObject prefab = null;

                        /*if (hit.Trackable is FeaturePoint)
                         * {
                         *  prefab = AndyPointPrefab;
                         * }*/
                        if (hit.Trackable is DetectedPlane)
                        {
                            DetectedPlane detectedPlane = hit.Trackable as DetectedPlane;
                            if (detectedPlane.PlaneType == DetectedPlaneType.Vertical)
                            {
                                prefab = Furniture;
                            }
                            else
                            {
                                prefab = Furniture;
                            }
                        }

                        /*else
                         * {
                         *  prefab = AndyHorizontalPlanePrefab;
                         * }*/

                        // Instantiate Andy model at the hit pose.
                        var andyObject = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);

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

                        // 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 Andy model a child of the anchor.
                        andyObject.transform.parent = anchor.transform;

                        //Get the displayed object
                        sofa = andyObject;

                        //If everything has gone ok, we change the phase
                        if (sofa != null)
                        {
                            currentPhase = Phase.Rotate;
                            //Gives the object to the rotation scripts by reference
                            RotateLeft.GetComponent <RotateLeft>().setSofa(sofa);
                            RotateRight.GetComponent <RotateRight>().setSofa(sofa);
                            //Gives a callback to the animation buttons
                            AnimateForward.GetComponent <Button>().onClick.AddListener(sofa.GetComponent <AnimationController>().setForward);
                            AnimateBackward.GetComponent <Button>().onClick.AddListener(sofa.GetComponent <AnimationController>().setBackward);
                        }
                    }
                }
            }
        }
Exemplo n.º 29
0
 void SetSelectedPlane(DetectedPlane selectedPlane)
 {
     Debug.Log("Selected plane centered at " + selectedPlane.CenterPose.position);
     cube.SetSelectedPlane(selectedPlane);
 }
Exemplo n.º 30
0
    public void Update()
    {
        EventDetection();

        Session.GetTrackables <DetectedPlane>(planes);
        bool trackingUI = true;

        for (int i = 0; i < planes.Count; i++)
        {
            if (planes[i].TrackingState == TrackingState.Tracking)
            {
                trackingUI = false;
                break;
            }
        }

        Touch touch;

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

        TrackableHit      hit;
        TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
                                          TrackableHitFlags.FeaturePointWithSurfaceNormal;

        RaycastHit[] h;
        Ray          r = camera.ScreenPointToRay(touch.position);

        h = Physics.RaycastAll(r);
        for (int i = 0; i < h.Length; i++)
        {
            h[i].collider.gameObject.SendMessage("turnOnGravity", SendMessageOptions.DontRequireReceiver);
        }
        if (Frame.Raycast(touch.position.x, touch.position.y, raycastFilter, out hit))
        {
            if ((hit.Trackable is DetectedPlane) &&
                Vector3.Dot(camera.transform.position - hit.Pose.position,
                            hit.Pose.rotation * Vector3.up) < 0)
            {
                Debug.Log("Hit at back of the current DetectedPlane");
            }
            else
            {
                if ((hit.Trackable is DetectedPlane))
                {
                    DetectedPlane plane = (DetectedPlane)hit.Trackable;
                    if (plane.PlaneType == DetectedPlaneType.Vertical && currentFrameOnScene < frameLimit)
                    {
                        var andyObject = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);
                        andyObject.transform.position = new Vector3(hit.Pose.position.x + 0.06f, hit.Pose.position.y + 0.06f, hit.Pose.position.z + 0.06f);

                        var     placedObjectForward = Vector3.up;
                        var     placedObjectUp      = plane.CenterPose.rotation * Vector3.up;
                        Vector3 normal = plane.CenterPose.rotation * Vector3.up;

                        andyObject.transform.rotation = Quaternion.LookRotation(placedObjectForward, placedObjectUp);
                        andyObject.transform.Rotate(-90, 0, 180);
                        andyObject.transform.Translate(Vector3.forward * 0.05f);

                        var anchor = hit.Trackable.CreateAnchor(hit.Pose);

                        andyObject.transform.parent = anchor.transform;

                        currentFrameOnScene++;

                        if (currentFrameOnScene >= frameLimit)
                        {
                            List <GameObject> l = DetectedPlanePrefab.GetComponent <GoogleARCore.Examples.Common.DetectedPlaneGenerator>().getPlaneList();
                            for (int i = 0; i < l.Count; i++)
                            {
                                Destroy(l[i].GetComponent <MeshRenderer>());
                            }
                        }
                    }
                    else
                    {
                        Handheld.Vibrate();
                    }
                }
            }
        }
    }