private void UpdateApplicationLifecycle()
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            if (Session.Status != SessionStatus.Tracking)
            {
                Screen.sleepTimeout = SleepTimeout.SystemSetting;
            }
            else
            {
                Screen.sleepTimeout = SleepTimeout.NeverSleep;
            }

            if (_isQuitting)
            {
                return;
            }

            if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
            {
                ShowAndroidToastMessage("Camera permission is needed to run this application.");
                _isQuitting = true;
                Invoke("DoQuit", 0.5f);
            }
            else if (Session.Status.IsError())
            {
                ShowAndroidToastMessage(
                    "ARCore encountered a problem connecting.  Please start the app again.");
                _isQuitting = true;
                Invoke("DoQuit", 0.5f);
            }
        }
Example #2
0
        private void _QuitOnConnectionErrors()
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }
            if (m_IsQuitting)
            {
                return;
            }

            // Quit if ARCore was unable to connect and give Unity some time for the toast to appear.
            if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
            {
                _ShowAndroidToastMessage("Camera permission is needed to run this application.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
            else if (Session.Status.IsError())
            {
                _ShowAndroidToastMessage("ARCore encountered a problem connecting.  Please start the app again.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
        }
        /// <summary>
        /// Check and update the application lifecycle.
        /// </summary>
        private void _UpdateApplicationLifecycle()
        {
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            // Only allow the screen to sleep when not tracking.
            Screen.sleepTimeout = Session.Status != SessionStatus.Tracking ? SleepTimeout.SystemSetting : SleepTimeout.NeverSleep;

            if (m_IsQuitting)
            {
                return;
            }

            // Quit if ARCore was unable to connect and give Unity some time for the toast to
            // appear.
            if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
            {
                _ShowAndroidToastMessage("Camera permission is needed to run this application.");
                m_IsQuitting = true;
                Invoke(nameof(_DoQuit), 0.5f);
            }
            else if (Session.Status.IsError())
            {
                _ShowAndroidToastMessage(
                    "ARCore encountered a problem connecting.  Please start the app again.");
                m_IsQuitting = true;
                Invoke(nameof(_DoQuit), 0.5f);
            }
        }
Example #4
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            _QuitOnConnectionErrors();
            _HandleSwipeInput();

            if (!Session.Status.IsValid())
            {
                return;
            }

            if (UseCustomResolutionImage)
            {
                return;
            }

            using (var image = Frame.CameraImage.AcquireCameraImageBytes())
            {
                if (!image.IsAvailable)
                {
                    return;
                }

                _OnImageAvailable(TextureReaderApi.ImageFormatType.ImageFormatGrayscale,
                                  image.Width, image.Height, image.Y, 0);
            }
        }
Example #5
0
        private void _UpdateApplicationLifecycle()
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                SceneManager.LoadScene("SelectionMenu");
            }
            if (Session.Status != SessionStatus.Tracking)
            {
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
            }
            else
            {
                Screen.sleepTimeout = SleepTimeout.NeverSleep;
            }

            if (m_IsQuitting)
            {
                return;
            }

            if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
            {
                _ShowAndroidToastMessage("Camera permission is needed to run this application.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
            else if (Session.Status.IsError())
            {
                _ShowAndroidToastMessage("ARCore encountered a problem connecting.  Please start the app again.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
        }
Example #6
0
        private void _UpdateApplicationLifecycle()
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }
            if (Session.Status != SessionStatus.Tracking)
            {
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
            }
            else
            {
                Screen.sleepTimeout = SleepTimeout.NeverSleep;
            }

            if (m_IsQuitting)
            {
                return;
            }

            // Quit if ARCore was unable to connect and give Unity some time for the toast to appear.
            if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
            {
                _ShowAndroidToastMessage("Camera permission is needed to run this application.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
            else if (Session.Status.IsError())
            {
                _ShowAndroidToastMessage("ARCore encountered a problem connecting.  Please start the app again.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
        }
        private void _UpdateApplicationLifecycle()
        {
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            if (m_IsQuitting)
            {
                return;
            }

            // Quit if ARCore was unable to connect and give Unity some time for the toast to appear.
            if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
            {
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
            else if (Session.Status.IsError())
            {
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
        }
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            _QuitOnConnectionErrors();

            // Change the CPU resolution checkbox visibility.
            LowResConfigToggle.gameObject.SetActive(EdgeDetectionBackgroundImage.enabled);
            HighResConfigToggle.gameObject.SetActive(EdgeDetectionBackgroundImage.enabled);

            if (!Session.Status.IsValid())
            {
                return;
            }

            using (var image = Frame.CameraImage.AcquireCameraImageBytes())
            {
                if (!image.IsAvailable)
                {
                    return;
                }

                _OnImageAvailable(image.Width, image.Height, image.YRowStride, image.Y, 0);
            }

            var cameraIntrinsics = EdgeDetectionBackgroundImage.enabled
                ? Frame.CameraImage.ImageIntrinsics : Frame.CameraImage.TextureIntrinsics;
            string intrinsicsType = EdgeDetectionBackgroundImage.enabled ? "Image" : "Texture";

            CameraIntrinsicsOutput.text = _CameraIntrinsicsToString(cameraIntrinsics, intrinsicsType);
        }
Example #9
0
        /// <summary>
        /// Code from GoogleARCore Computer Vision example - modified
        /// </summary>
        private void updateApplicationLifecycle()
        {
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            quitOnConnectionErrors();

            imageTextureToggleText.text = EdgeDetectionBackgroundImage.enabled ?
                                          "Switch to GPU Texture" : "Switch to CPU Image";
        }
Example #10
0
        /// <summary>
        /// The Unity Update method.
        /// </summary>
        public void Update()
        {
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            // Check that motion tracking is tracking.
            if (Session.Status != SessionStatus.Tracking)
            {
                return;
            }

            // Get updated augmented images for this frame.
            Session.GetTrackables <AugmentedImage>(m_TempAugmentedImages, TrackableQueryFilter.Updated);

            // Create visualizers and anchors for updated augmented images that are tracking and do not previously
            // have a visualizer. Remove visualizers for stopped images.
            foreach (var image in m_TempAugmentedImages)
            {
                AugmentedImageVisualizer visualizer = null;
                m_Visualizers.TryGetValue(image.DatabaseIndex, out visualizer);
                if (image.TrackingState == TrackingState.Tracking && visualizer == null)
                {
                    // Create an anchor to ensure that ARCore keeps tracking this augmented image.
                    Anchor anchor = image.CreateAnchor(image.CenterPose);
                    visualizer       = (AugmentedImageVisualizer)Instantiate(AugmentedImageVisualizerPrefab, anchor.transform);
                    visualizer.Image = image;
                    m_Visualizers.Add(image.DatabaseIndex, visualizer);
                }
                else if (image.TrackingState == TrackingState.Stopped && visualizer != null)
                {
                    m_Visualizers.Remove(image.DatabaseIndex);
                    GameObject.Destroy(visualizer.gameObject);
                }
            }

            // Show the fit-to-scan overlay if there are no images that are Tracking.
            foreach (var visualizer in m_Visualizers.Values)
            {
                if (visualizer.Image.TrackingState == TrackingState.Tracking)
                {
                    FitToScanOverlay.SetActive(false);
                    return;
                }
            }

            FitToScanOverlay.SetActive(true);
        }
Example #11
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            _QuitOnConnectionErrors();

            // Toggle background to edge detection.
            if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
            {
                EdgeDetectionBackgroundImage.enabled = !EdgeDetectionBackgroundImage.enabled;
            }

            var cameraIntrinsics = EdgeDetectionBackgroundImage.enabled
                ? Frame.CameraImage.ImageIntrinsics : Frame.CameraImage.TextureIntrinsics;
            string intrinsicsType = EdgeDetectionBackgroundImage.enabled ? "Image" : "Texture";

            CameraIntrinsicsOutput.text = _CameraIntrinsicsToString(cameraIntrinsics, intrinsicsType);

            if (UseCustomResolutionImage && EdgeDetectionBackgroundImage.enabled)
            {
                CameraIntrinsicsOutput.text = string.Empty;
            }

            if (!Session.Status.IsValid())
            {
                return;
            }

            if (UseCustomResolutionImage)
            {
                return;
            }

            using (var image = Frame.CameraImage.AcquireCameraImageBytes())
            {
                if (!image.IsAvailable)
                {
                    return;
                }

                _OnImageAvailable(TextureReaderApi.ImageFormatType.ImageFormatGrayscale,
                                  image.Width, image.Height, image.Y, 0);
            }
        }
Example #12
0
        /// <summary>
        /// Check and update the application lifecycle.
        /// </summary>
        private void _UpdateApplicationLifecycle()
        {
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            // Only allow the screen to sleep when not tracking.
            if (Session.Status != SessionStatus.Tracking)
            {
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
            }
            else
            {
                Screen.sleepTimeout = SleepTimeout.NeverSleep;
            }

            if (m_IsQuitting)
            {
                return;
            }

            // Quit if ARCore was unable to connect and give Unity some time for the toast to
            // appear.
            if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
            {
                _ShowAndroidToastMessage("Camera permission is needed to run this application.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
            else if (Session.Status.IsError())
            {
                _ShowAndroidToastMessage(
                    "ARCore encountered a problem connecting.  Please start the app again.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }

            if (!audioSource.isPlaying)
            {
                audioSource.Play();
            }
            audioSource.volume = 0.25f;
        }
Example #13
0
        //Checking and updating an application's lifecycle.
        private void _UpdateApplicationLifecycle()
        {
            // Exit the app when the back button is pressed (for desktop testing only).
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            //Only allows screen to sleep when the device is not tracking.
            if (Session.Status != SessionStatus.Tracking)
            {
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
            }
            else
            {
                Screen.sleepTimeout = SleepTimeout.NeverSleep;
            }

            if (m_IsQuitting)
            {
                return;
            }

            //Quits if ARCore is unable to connect and give Unity time for the toast message to appear.
            if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
            {
                //Pop-Up error message.
                _ShowAndroidToastMessage("Camera permission is required to run the application. Try again.");
                m_IsQuitting = true;

                //Quits app.
                Invoke("_DoQuit", 0.5f);
            }
            //If the status is an error in connection.
            else if (Session.Status.IsError())
            {
                _ShowAndroidToastMessage(
                    "ARCore encountered a problem connecting. Try connecting again");
                m_IsQuitting = true;

                //Quits app.
                Invoke("_DoQuit", 0.5f);
            }
        }
Example #14
0
        /// <summary>
        /// Check and update the application lifecycle.
        /// </summary>
        private void _UpdateApplicationLifecycle()
        {
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }
            /// <summary>
            /// ARCore는 실제 환경에서 사용자의 움직임을 추적하기 위해 충분한 정보를 캡처하고 처리해야 한다.
            /// ARCore가 추적하면 frame 객체는 ARCore와 상호 작용하기 위해 사용된다.
            /// 동시에 화면 시간 초과를 조정하여 추적 중이면 계속 유지되도록 한다.
            /// </summary>
            if (Session.Status != SessionStatus.Tracking)                       //Session 상태는 Frame에 접근하기 위해 추적상태가 되어야한다.
            {
                //추적하지 않는 상태엔 스크린이 sleep 상태가 된다.
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
            }
            else
            {
                Screen.sleepTimeout = SleepTimeout.NeverSleep;
            }

            if (m_IsQuitting)
            {
                return;
            }

            // Quit if ARCore was unable to connect and give Unity some time for the toast to appear.      //ARcore가 app상에서 잘돌아가는 ARcore Session 상태를 체크
            if (Session.Status == SessionStatus.ErrorPermissionNotGranted)                                 //카메라 사용에 대해 허가를 받는지?
            {                                                                                              //ARcore 라이브러리가 ARcore 서비스에 접속가능한지?
                                                                                                           //void QuitOnConnectionErrors()
                _ShowAndroidToastMessage("Camera permission is needed to run this application.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
            else if (Session.Status.IsError())
            {
                _ShowAndroidToastMessage("ARCore encountered a problem connecting.  Please start the app again.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
        }
Example #15
0
        /// <summary>
        /// Check and update the application lifecycle.
        /// </summary>
        private void _UpdateApplicationLifecycle()
        {
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            // Only allow the screen to sleep when not tracking.
            if (Session.Status != SessionStatus.Tracking)
            {
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
            }
            else
            {
                Screen.sleepTimeout = SleepTimeout.NeverSleep;
            }

            if (m_IsQuitting)
            {
                return;
            }

            //이 밑에 오류처리가 한번만 실행되게 하려고 m_IsQuitting이라는걸 만든것인듯? _DoQuit 같은게 여러번 실행되면 문제가 발생할 수 있을거같긴함. 
            //컴퓨터 입장에서 _DoQuit 메소드를 실행한다고 바로 꺼지는것도 아니니.  

            // Quit if ARCore was unable to connect and give Unity some time for the toast to appear.
            if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
            {
                _ShowAndroidToastMessage("Camera permission is needed to run this application.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
            else if (Session.Status.IsError())
            {
                _ShowAndroidToastMessage("ARCore encountered a problem connecting.  Please start the app again.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
        }
Example #16
0
        /// <summary>
        /// Check and update the application lifecycle.
        /// </summary>
        private void _UpdateApplicationLifecycle()
        {
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            // Ef síminn er ekki "tracking" þá leyfum við honum að slökkva á skjánum samkvæmt
            // símastillingunni, en ef síminn er "tracking" þá viljum við ekki slökkva á skjánum
            if (Session.Status != SessionStatus.Tracking)
            {
                Screen.sleepTimeout = SleepTimeout.SystemSetting;
            }
            else
            {
                Screen.sleepTimeout = SleepTimeout.NeverSleep;
            }

            if (m_IsQuitting)
            {
                return;
            }

            // Quit if ARCore was unable to connect and give Unity some time for the toast to
            // appear.
            if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
            {
                _ShowAndroidToastMessage("Camera permission is needed to run this application.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
            else if (Session.Status.IsError())
            {
                _ShowAndroidToastMessage(
                    "ARCore encountered a problem connecting.  Please start the app again.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
        }
        /// <summary>
        /// Check and update the application lifecycle.
        /// </summary>
        private void _UpdateApplicationLifecycle()    //매 프레임마다 어플리케이션의 생명주기 변동 확인을 위한 메소드
        {
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();                             //뒤로가기 키를 누르면 어플리케이션이 종료된다.
            }

            // Only allow the screen to sleep when not tracking. Tracking 상태가 아니면 어플리케이션을 절전상태로 바꾼다.
            if (Session.Status != SessionStatus.Tracking)
            {
                Screen.sleepTimeout = SleepTimeout.SystemSetting;
            }
            else
            {
                Screen.sleepTimeout = SleepTimeout.NeverSleep;
            }

            if (m_IsQuitting)
            {
                return;
            }

            // Quit if ARCore was unable to connect and give Unity some time for the toast to
            // appear.
            //if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
            //{
            //    _ShowAndroidToastMessage("Camera permission is needed to run this application.");
            //    m_IsQuitting = true;
            //    Invoke("_DoQuit", 0.5f);
            //}
            //else if (Session.Status.IsError())
            //{
            //    _ShowAndroidToastMessage(
            //        "ARCore encountered a problem connecting.  Please start the app again.");
            //    m_IsQuitting = true;
            //    Invoke("_DoQuit", 0.5f);
            //}
        }
Example #18
0
        /// <summary>
        /// Check and update the application lifecycle.
        /// </summary>
        private void UpdateApplicationLifecycle()
        {
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                appController.LoadScene("MainMenuScene");
            }

            // Only allow the screen to sleep when not tracking.
            if (Session.Status != SessionStatus.Tracking)
            {
                Screen.sleepTimeout = SleepTimeout.SystemSetting;
            }
            else
            {
                Screen.sleepTimeout = SleepTimeout.NeverSleep;
            }

            // If the app is already in a quitting state, skip the next verifications
            if (isQuitting)
            {
                return;
            }

            if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
            {
                ShowAndroidToastMessage("Camera permission is needed to run this application.");
                isQuitting = true;
                Invoke("QuitTheApplication", 0.5f);
            }
            else if (Session.Status.IsError())
            {
                ShowAndroidToastMessage("ARCore encountered a problem connecting. Please start the app again.");
                isQuitting = true;
                Invoke("QuitTheApplication", 0.5f);
            }
        }
Example #19
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            _QuitOnConnectionErrors();

            // Toggle background to edge detection.
            if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
            {
                EdgeDetectionBackgroundImage.enabled = !EdgeDetectionBackgroundImage.enabled;
            }

            if (!Session.Status.IsValid())
            {
                return;
            }

            if (UseCustomResolutionImage)
            {
                return;
            }

            using (var image = Frame.CameraImage.AcquireCameraImageBytes())
            {
                if (!image.IsAvailable)
                {
                    return;
                }

                _OnImageAvailable(TextureReaderApi.ImageFormatType.ImageFormatGrayscale,
                                  image.Width, image.Height, image.Y, 0);
            }
        }
        public void Update()
        {
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            if (CrossPlatformInputManager.GetButtonDown("Restart"))
            {
                //Application.Quit();
                m_hasCreateBattle = false;
                TouchControls.SetActive(false);
                if (battleGO != null)
                {
                    DestroyImmediate(battleGO);
                }
            }
            _QuitOnConnectionErrors();

            // Check that motion tracking is tracking.
            if (Session.Status != SessionStatus.Tracking)//mata mod
            {
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
                if (!m_IsQuitting && Session.Status.IsValid())
                {
                    //SearchingForPlaneUI.SetActive(true);
                }

                return;
            }

            Screen.sleepTimeout = SleepTimeout.NeverSleep;

            // Iterate over planes found in this frame and instantiate corresponding GameObjects to visualize them.
            Session.GetTrackables <TrackedPlane>(m_NewPlanes, TrackableQueryFilter.New);
            for (int i = 0; i < m_NewPlanes.Count; i++)
            {
                // Instantiate a plane visualization prefab and set it to track the new plane. The transform is set to
                // the origin with an identity rotation since the mesh for our prefab is updated in Unity World
                // coordinates.
                GameObject planeObject = Instantiate(TrackedPlanePrefab, Vector3.zero, Quaternion.identity,
                                                     transform);
                planeObject.GetComponent <TrackedPlaneVisualizer>().Initialize(m_NewPlanes[i]);
            }

            // Hide snackbar when currently tracking at least one plane.
            Session.GetTrackables <TrackedPlane>(m_AllPlanes);
            bool showSearchingUI = true;//mata mod

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

            //SearchingForPlaneUI.SetActive(showSearchingUI);

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

            // 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) && !m_hasCreateBattle)
            {
                battleGO = Instantiate(AndyAndroidPrefab, hit.Pose.position, hit.Pose.rotation);

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

                // Andy should look at the camera but still be flush with the plane.
                if ((hit.Flags & TrackableHitFlags.PlaneWithinPolygon) != TrackableHitFlags.None)
                {
                    // Get the camera position and match the y-component with the hit position.
                    Vector3 cameraPositionSameY = FirstPersonCamera.transform.position;
                    cameraPositionSameY.y = hit.Pose.position.y;//相机在地板上的投影点。
                    var lookAtPos = battleGO.transform.position - (cameraPositionSameY - battleGO.transform.position);
                    // Have Andy look toward the camera respecting his "up" perspective, which may be from ceiling.
                    //andyObject.transform.LookAt(andyObject.transform.position + Vector3.forward, anchor.transform.up);
                    battleGO.transform.LookAt(lookAtPos, anchor.transform.up);
                }

                // Make Andy model a child of the anchor.
                battleGO.transform.parent = anchor.transform;
                m_hasCreateBattle         = true;
                TouchControls.SetActive(true);

                //dualTouchControls = (GameObject)Instantiate(Resources.Load("Standard_Assets/CrossPlatformInput/Prefabs/DualTouchControls"));
            }
        }
Example #21
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            _QuitOnConnectionErrors();

            // Check that motion tracking is tracking.
            if (Session.Status != SessionStatus.Tracking)
            {
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
                if (!m_IsQuitting && Session.Status.IsValid())
                {
                    SearchingForPlaneUI.SetActive(true);
                }

                return;
            }

            Screen.sleepTimeout = SleepTimeout.NeverSleep;

            // Iterate over planes found in this frame and instantiate corresponding GameObjects to visualize them.
            Session.GetTrackables <TrackedPlane>(m_NewPlanes, TrackableQueryFilter.New);
            for (int i = 0; i < m_NewPlanes.Count; i++)
            {
                // Instantiate a plane visualization prefab and set it to track the new plane. The transform is set to
                // the origin with an identity rotation since the mesh for our prefab is updated in Unity World
                // coordinates.
                GameObject planeObject = Instantiate(TrackedPlanePrefab, Vector3.zero, Quaternion.identity,
                                                     transform);
                planeObject.GetComponent <TrackedPlaneVisualizer>().Initialize(m_NewPlanes[i]);
            }

            // Disable the snackbar UI when no planes are valid.
            Session.GetTrackables <TrackedPlane>(m_AllPlanes);
            bool showSearchingUI = true;

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

            SearchingForPlaneUI.SetActive(showSearchingUI);

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

            // 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) && !farmCreated)
            {
                var farmObject = Instantiate(AndyAndroidPrefab, hit.Pose.position, hit.Pose.rotation);

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

                //Pretty sure we don't need this. Probably.
                //// Andy should look at the camera but still be flush with the plane.
                //if ((hit.Flags & TrackableHitFlags.PlaneWithinPolygon) != TrackableHitFlags.None)
                //{
                //    // Get the camera position and match the y-component with the hit position.
                //    Vector3 cameraPositionSameY = FirstPersonCamera.transform.position;
                //    cameraPositionSameY.y = hit.Pose.position.y;

                //    // Have Andy look toward the camera respecting his "up" perspective, which may be from ceiling.
                //    farmObject.transform.LookAt(cameraPositionSameY, farmObject.transform.up);
                //}

                // Make Farm model a child of the anchor.
                farmObject.transform.parent = anchor.transform;

                farmCreated = true;
            }
            Ray        ray     = Camera.current.ScreenPointToRay(Input.GetTouch(0).position);
            RaycastHit tileHit = new RaycastHit();

            if (farmCreated && Physics.Raycast(ray, out tileHit))
            {
                //if (selectedTile != tileHit.collider.gameObject)
                //{
                //    mSelected.color = mOriginal.color;
                //}
                selectedTile = tileHit.collider.gameObject;
                mSelected    = selectedTile.GetComponent <Renderer>().material;
                if (mSelected.color != Color.yellow)
                {
                    mOriginal = mSelected;
                }

                _ShowAndroidToastMessage(selectedTile.name);
                mSelected.color = Color.yellow;
            }
        }
Example #22
0
        /// <summary>
        /// The Unity Update() method. (called once per frame)
        /// Call the detector if the device touchscreen was pressed and then update the panel.
        /// </summary>

        public async void Update()
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            _QuitOnConnectionErrors();
            _UpdateFrameRate();


            if (!Session.Status.IsValid())
            {
                return;
            }

            // Google ARCore, pose tracking
            // The session status must be Tracking in order to access the Frame.
            if (Session.Status != SessionStatus.Tracking)
            {
                int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
                return;
            }
            Screen.sleepTimeout = SleepTimeout.NeverSleep;


            Touch touch;

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

            // Process image on click or touch (Crop, Scale, Rotate)
            ScaleCropRotate();

            // Forward the input image into the model
            boxOutlines = await detector.ProcessImageAsync(rotated);

            Debug.Log("Box outlines length : " + boxOutlines.Count);
            if (boxOutlines.Count > 0)
            {
                Debug.Log("Update, score  : " + boxOutlines[0].Score + " classe : " + boxOutlines[0].Label);
                UpdatePanel();
            }


            // Select plane attached to the nutrition panel according to the touch position using Raycast
            TrackableHit      hit;
            TrackableHitFlags raycastFilter =
                TrackableHitFlags.PlaneWithinBounds |
                TrackableHitFlags.PlaneWithinPolygon;

            if (Frame.Raycast(touch.position.x, touch.position.y, raycastFilter, out hit))
            {
                Debug.Log(" Touch position x : " + touch.position.x + "y : " + touch.position.y);
                SetSelectedPlane(hit.Trackable as DetectedPlane);
            }
        }
Example #23
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            _QuitOnConnectionErrors();

            // Check that motion tracking is tracking.
            if (Session.Status != SessionStatus.Tracking)
            {
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
                if (!m_IsQuitting && Session.Status.IsValid())
                {
                    SearchingForPlaneUI.SetActive(true);
                }

                return;
            }

            Screen.sleepTimeout = SleepTimeout.NeverSleep;

            // Iterate over planes found in this frame and instantiate corresponding GameObjects to visualize them.
            Session.GetTrackables <TrackedPlane>(m_NewPlanes, TrackableQueryFilter.New);
            for (int i = 0; i < m_NewPlanes.Count; i++)
            {
                // Instantiate a plane visualization prefab and set it to track the new plane. The transform is set to
                // the origin with an identity rotation since the mesh for our prefab is updated in Unity World
                // coordinates.
                GameObject planeObject = Instantiate(TrackedPlanePrefab, Vector3.zero, Quaternion.identity,
                                                     transform);
                planeObject.GetComponent <TrackedPlaneVisualizer>().Initialize(m_NewPlanes[i]);
            }

            // Disable the snackbar UI when no planes are valid.
            Session.GetTrackables <TrackedPlane>(m_AllPlanes);
            bool showSearchingUI = true;
            bool showPlaceFarmUI = false;
            bool showTileUI      = false;
            bool showEscapeUI    = false;
            bool showCurrencyUI  = false;

            if (selectedTile != null)
            {
                showEscapeUI   = true;
                showTileUI     = true;
                showCurrencyUI = true;
            }
            for (int i = 0; i < m_AllPlanes.Count; i++)
            {
                if (m_AllPlanes[i].TrackingState == TrackingState.Tracking)
                {
                    showSearchingUI = false;
                    showPlaceFarmUI = true;
                    break;
                }
            }
            if (farmCreated)
            {
                showPlaceFarmUI = false;
            }

            PlaceFarmUI.SetActive(showPlaceFarmUI);
            SearchingForPlaneUI.SetActive(showSearchingUI);
            TileUI.SetActive(showTileUI);
            EscapeUI.SetActive(showEscapeUI);
            CurrencyUI.SetActive(showCurrencyUI);
            try
            {
                CheckPlantStage();
                //_ShowAndroidToastMessage("Check Plant OK!");
            }
            catch (Exception e)
            {
                //_ShowAndroidToastMessage("Check plant crashed");
            }
            try
            {
                CheckWaterLevel();
                //_ShowAndroidToastMessage("Check Water OK!");
            }
            catch (Exception e)
            {
                //_ShowAndroidToastMessage("Water code crashed");
            }



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

            // 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) && !farmCreated)
            {
                farmObject = Instantiate(FarmPrefab, hit.Pose.position, hit.Pose.rotation);

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


                // Make Farm model a child of the anchor.
                farmObject.transform.parent = anchor.transform;

                farmCreated = true;

                bool farmSaved = false;
                if (PlayerPrefs.GetInt("farmSaved") == 1)
                {
                    farmSaved = true;
                }
                ReloadFarm(farmSaved);
            }



            //Create ray and raycasthit for tile selection
            Ray        ray     = Camera.current.ScreenPointToRay(Input.GetTouch(0).position);
            RaycastHit tileHit = new RaycastHit();

            //Selects tile and changes material, currently uses color.yellow as temporary highlighter.
            if (farmCreated && Physics.Raycast(ray, out tileHit))
            {
                if (selectedTile != tileHit.collider.gameObject && selectedTile != null)
                {
                    InventoryUI.SetActive(false);
                    for (int i = 0; i < selectedTile.GetComponent <Renderer>().sharedMaterials.Length; i++)
                    {
                        selectedTile.GetComponent <Renderer>().sharedMaterials[i].color = oldMaterials[i];
                    }

                    //mSelected.color = mOriginal.color;
                }
                selectedTile = tileHit.collider.gameObject;
                mSelected    = selectedTile.GetComponent <Renderer>().material;
                if (mSelected.color != Color.yellow)
                {
                    //_ShowAndroidToastMessage("Original Material Saved");
                    //mOriginal = new Material(mSelected);
                    for (int i = 0; i < selectedTile.GetComponent <Renderer>().sharedMaterials.Length; i++)
                    {
                        oldMaterials[i] = selectedTile.GetComponent <Renderer>().sharedMaterials[i].color;
                    }
                }

                foreach (Material mat in selectedTile.GetComponent <Renderer>().sharedMaterials)
                {
                    //_ShowAndroidToastMessage(selectedTile.GetComponent<Renderer>().sharedMaterials.Length.ToString());
                    mat.color = Color.yellow;
                }
                //mSelected.color = Color.yellow;
            }



            if (TileUI.activeSelf)
            {
                Button[] buttonList    = TileUI.GetComponentsInChildren <Button>();
                Button   harvestButton = buttonList[0];
                Button   waterButton   = buttonList[1];
                Button   plantButton   = buttonList[2];



                plantButton.onClick.AddListener(() =>
                {
                    //                    Plant(selectedTile, -1);
                    // storage.OpenInventory();
                    InventoryUI.SetActive(true);
                });
                waterButton.onClick.AddListener(() =>
                {
                    TileState oldState          = selectedTile.GetComponent <TileState>();
                    int plantStage              = oldState.PlantStage;
                    int plantType               = oldState.PlantType;
                    int currentPlantModel       = oldState.PlantModel;
                    bool watered                = oldState.IsWatered;
                    bool hasPlant               = oldState.HasPlant;
                    System.DateTime wateredLast = oldState.WateredLast;
                    System.DateTime plantedLast = oldState.PlantedLast;
                    DestroyImmediate(oldState);
                    TileState newState  = selectedTile.AddComponent <TileState>();
                    newState.PlantStage = plantStage;
                    newState.PlantType  = plantType;
                    newState.PlantModel = currentPlantModel;
                    newState.IsWatered  = watered;
                    newState.HasPlant   = hasPlant;
                    newState.Water();
                });
                harvestButton.onClick.AddListener(() => { Harvest(selectedTile); });


                if (InventoryUI.activeSelf)
                {
                    Button[] seedButtons = InventoryUI.GetComponentsInChildren <Button>();
                    int      i           = 0;


                    seedButtons[0].onClick.AddListener(() =>
                    {
                        try
                        {
                            //_ShowAndroidToastMessage("Selected item at " + 0);
                            Plant(selectedTile, 2);
                        }
                        catch (Exception e)
                        {
                            //_ShowAndroidToastMessage("Inventory Button listener crashed");
                        }
                    });

                    seedButtons[1].onClick.AddListener(() =>
                    {
                        try
                        {
                            //_ShowAndroidToastMessage("Selected item at " + 1);
                            Plant(selectedTile, 1);
                        }
                        catch (Exception e)
                        {
                            //_ShowAndroidToastMessage("Inventory Button listener crashed");
                        }
                    });

                    seedButtons[2].onClick.AddListener(() =>
                    {
                        try
                        {
                            //_ShowAndroidToastMessage("Selected item at " + 2);
                            Plant(selectedTile, 0);
                        }
                        catch (Exception e)
                        {
                            //_ShowAndroidToastMessage("Inventory Button listener crashed");
                        }
                    });

                    seedButtons[3].onClick.AddListener(() =>
                    {
                        try
                        {
                            // _ShowAndroidToastMessage("Selected item at " + 3);
                            Plant(selectedTile, 3);
                        }
                        catch (Exception e)
                        {
                            // _ShowAndroidToastMessage("Inventory Button listener crashed");
                        }
                    });
                }
            }



            if (EscapeUI.activeSelf)
            {
                Button[] buttonList   = EscapeUI.GetComponentsInChildren <Button>();
                Button   escapeButton = buttonList[0];

                escapeButton.onClick.AddListener(() =>
                {
                    mSelected.color = mOriginal.color;
                    selectedTile    = null;
                });
            }



            //Scale Farm by pinching
            //if (Input.touchCount == 2 && farmCreated)
            //{
            //    if (Input.touchCount >= 2 && (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved))
            //    {
            //        Vector2 touch1 = Input.GetTouch(0).position;
            //        Vector2 touch2 = Input.GetTouch(1).position;

            //        newDistance = (touch1 - touch2).sqrMagnitude;
            //        float changeInDistance = newDistance - initialDistance;
            //        float percentageChange = changeInDistance / initialDistance;


            //        Vector3 newScale = farmObject.transform.parent.localScale;
            //        newScale += percentageChange * newScale;

            //        farmObject.transform.parent.localScale = newScale;
            //        farmObject.transform.localScale = newScale;

            //    }

            //}
        }
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {

            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            _QuitOnConnectionErrors();

            if (myTowerBaseTrackingState == TowerBaseTrackingState.tracking)
            {
                // Check that motion tracking is tracking.
                if (Session.Status != SessionStatus.Tracking)
                {
                    const int lostTrackingSleepTimeout = 15;
                    Screen.sleepTimeout = lostTrackingSleepTimeout;
                    if (!m_IsQuitting && Session.Status.IsValid())
                    {
                        SearchingForPlaneUI.SetActive(true);
                    }

                    return;
                }

                Screen.sleepTimeout = SleepTimeout.NeverSleep;

                // Iterate over planes found in this frame and instantiate corresponding GameObjects to visualize them.
                Session.GetTrackables<TrackedPlane>(m_NewPlanes, TrackableQueryFilter.New);
                for (int i = 0; i < m_NewPlanes.Count; i++)
                {
                    // Instantiate a plane visualization prefab and set it to track the new plane. The transform is set to
                    // the origin with an identity rotation since the mesh for our prefab is updated in Unity World
                    // coordinates.
                    planeGridObject = Instantiate(TrackedPlanePrefab, Vector3.zero, Quaternion.identity,
                        transform);
                    planeGridObject.GetComponent<MeshRenderer>().enabled = true;
                    planeGridObject.GetComponent<TrackedPlaneVisualizer>().enabled = true;
                    planeGridObject.GetComponent<TrackedPlaneVisualizer>().Initialize(m_NewPlanes[i]); //아마 이 planeobject가 없어지면 설치 후 그릴 없엘 수 있겠
                }
                
                // Disable the snackbar UI when no planes are valid.
                Session.GetTrackables<TrackedPlane>(m_AllPlanes); //여기서 현재 추적되어 있는 그릴을 찾는군
                bool showSearchingUI = true;
                for (int i = 0; i < m_AllPlanes.Count; i++)
                {
                    if (m_AllPlanes[i].TrackingState == TrackingState.Tracking)
                    {
                        showSearchingUI = false;
                        break;
                    }
                }

                SearchingForPlaneUI.SetActive(showSearchingUI);

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

                // 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))
                {
                    var defenseStation = Instantiate(defenseStation_Prefab, hit.Pose.position, hit.Pose.rotation);

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

                    // Andy should look at the camera but still be flush with the plane.
                    if ((hit.Flags & TrackableHitFlags.PlaneWithinPolygon) != TrackableHitFlags.None)
                    {
                        // Get the camera position and match the y-component with the hit position.
                        Vector3 cameraPositionSameY = FirstPersonCamera.transform.position;
                        cameraPositionSameY.y = hit.Pose.position.y;

                        // Have Andy look toward the camera respecting his "up" perspective, which may be from ceiling.
                        defenseStation.transform.LookAt(cameraPositionSameY, defenseStation.transform.up);
                    }

                    // Make Andy model a child of the anchor.
                    defenseStation.transform.parent = defenseStation_Anchor.transform;

                    myTowerBaseTrackingState = TowerBaseTrackingState.built;
                    //defenseStation_Tr = defenseStation.transform;
                    defenseStation_Anchor_Tr = defenseStation_Anchor.transform;

                    //planeGridObject.GetComponent<MeshRenderer>().enabled = false;
                    //planeGridObject.GetComponent<TrackedPlaneVisualizer>().enabled = false;

                    //StartCoroutine(StartSceneB());
                    IFP.LoadingManagement.instance.ShowLoadingBar();

                    if (IFP.TempStageManagement.instance.CurrentStageLevel == 10)
                    {
                        SceneManager.LoadScene("GameScene F", LoadSceneMode.Additive);
                    }
                    else
                    {
                        SceneManager.LoadScene("GameScene B", LoadSceneMode.Additive);
                    }

                    planeGridObject.GetComponent<MeshRenderer>().enabled = false;
                    planeGridObject.GetComponent<TrackedPlaneVisualizer>().enabled = false;
                    //if (IFP.TempStageManagement.instance.CurrentStageLevel == 2)
                    //SceneManager.LoadScene("GameScene B", LoadSceneMode.Additive);
                    //else if (IFP.TempStageManagement.instance.CurrentStageLevel == 5)
                    //{
                    //    defenseStation.GetComponent<MeshRenderer>().enabled = false;
                    //    SceneManager.LoadScene("StoryMode Chapter 3", LoadSceneMode.Additive);
                    //}
                    //GameObject ground = Instantiate(groundPlane, defenseStation.transform.position, Quaternion.identity);
                }
            }
        }
        /// <summary>
        /// Check and update the application lifecycle.
        /// </summary>
        private void _UpdateApplicationLifecycle()
        {
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                //Application.Quit();
                SceneManager.LoadScene("menu");
            }

            // Only allow the screen to sleep when not tracking.
            if (Session.Status != SessionStatus.Tracking)
            {
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
            }
            else
            {
                Screen.sleepTimeout = SleepTimeout.NeverSleep;
            }

            if (m_IsQuitting)
            {
                return;
            }

            // Quit if ARCore was unable to connect and give Unity some time for the toast to appear.
            if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
            {
                _ShowAndroidToastMessage("Camera permission is needed to run this application.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
            else if (Session.Status.IsError())
            {
                _ShowAndroidToastMessage("ARCore encountered a problem connecting.  Please start the app again.");
                m_IsQuitting = true;
                Invoke("_DoQuit", 0.5f);
            }
            if (Input.touchCount == 1)
            {
                Touch touch2 = Input.GetTouch(0);

                if (touch2.phase == TouchPhase.Ended)
                {
                    touchCount += 1;
                }


                if (touchCount == 1)
                {
                    NewTime = Time.time + MaxDoubleTime;
                }
                else if (touchCount == 2 && Time.time < NewTime)
                {
                    //double Tab section..

                    autoRotation();
                    touchCount = 0;
                }
            }
            if (Time.time > NewTime)
            {
                touchCount = 0;
            }
        }
Example #26
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            _QuitOnConnectionErrors();

            // Check that motion tracking is tracking.
            if (Session.Status != SessionStatus.Tracking)
            {
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
                if (!m_IsQuitting && Session.Status.IsValid())
                {
                    SearchingForPlaneUI.SetActive(true);
                }

                return;
            }

            Screen.sleepTimeout = SleepTimeout.NeverSleep;

            // Iterate over planes found in this frame and instantiate corresponding GameObjects to visualize them.
            Session.GetTrackables <TrackedPlane>(m_NewPlanes, TrackableQueryFilter.New);
            for (int i = 0; i < m_NewPlanes.Count; i++)
            {
                // Instantiate a plane visualization prefab and set it to track the new plane. The transform is set to
                // the origin with an identity rotation since the mesh for our prefab is updated in Unity World
                // coordinates.
                GameObject planeObject = Instantiate(TrackedPlanePrefab, Vector3.zero, Quaternion.identity,
                                                     transform);
                planeObject.GetComponent <TrackedPlaneVisualizer>().Initialize(m_NewPlanes[i]);
            }

            // Hide snackbar when currently tracking at least one plane.
            Session.GetTrackables <TrackedPlane>(m_AllPlanes);
            bool showSearchingUI = true;

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

            SearchingForPlaneUI.SetActive(showSearchingUI);

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

            if (Input.touchCount > 1)
            {
                clear();
                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))
            {
                var andyObject = Instantiate(AndyAndroidPrefab, hit.Pose.position, hit.Pose.rotation);

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

                // Andy should look at the camera but still be flush with the plane.
                if ((hit.Flags & TrackableHitFlags.PlaneWithinPolygon) != TrackableHitFlags.None)
                {
                    // Get the camera position and match the y-component with the hit position.
                    Vector3 cameraPositionSameY = FirstPersonCamera.transform.position;
                    cameraPositionSameY.y = hit.Pose.position.y;

                    // Have Andy look toward the camera respecting his "up" perspective, which may be from ceiling.
                    andyObject.transform.LookAt(cameraPositionSameY, andyObject.transform.up);
                }

                // Make Andy model a child of the anchor.
                andyObject.transform.Rotate(new Vector3(0, 180, 0));
                andyObject.transform.localScale = new Vector3(0.01f, 0.01f, 0.01f);
                andyObject.transform.parent     = anchor.transform;

                texts.Add(andyObject);

                StartCoroutine(Upload((TextMesh)andyObject.GetComponent(typeof(TextMesh))));
            }
        }
Example #27
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            if (m_IsInstantMsg)
            {
                return;
            }

            // Check that motion tracking is tracking.
            if (Session.Status != SessionStatus.Tracking)
            {
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
                if (!m_IsQuitting && Session.Status.IsValid())
                {
                    InitialMessage.SetActive(true);
                }

                m_ControlObject                  = null;
                m_ButtonRemove.interactable      = false;
                m_ButtonCreateTable.interactable = false;
                m_ButtonCreateChair.interactable = false;
                m_RotationObject.SetActive(false);
                return;
            }

            Screen.sleepTimeout = SleepTimeout.NeverSleep;

            // Iterate over planes found in this frame and instantiate corresponding GameObjects to visualize them.
            Session.GetTrackables <TrackedPlane> (m_NewPlanes, TrackableQueryFilter.New);
            for (int i = 0; i < m_NewPlanes.Count; i++)
            {
                // Instantiate a plane visualization prefab and set it to track the new plane. The transform is set to
                // the origin with an identity rotation since the mesh for our prefab is updated in Unity World
                // coordinates.
                GameObject planeObject = Instantiate(TrackedPlanePrefab, Vector3.zero, Quaternion.identity, transform);
                planeObject.GetComponent <TrackedPlaneVisualizer> ().Initialize(m_NewPlanes [i]);
            }

            // Disable the snackbar UI when no planes are valid.
            Session.GetTrackables <TrackedPlane> (m_AllPlanes);
            bool showSearchingUI = true;

            for (int i = 0; i < m_AllPlanes.Count; i++)
            {
                if (m_AllPlanes [i].TrackingState == TrackingState.Tracking)
                {
                    showSearchingUI = false;
                    m_ButtonCreateTable.interactable = true;
                    m_ButtonCreateChair.interactable = true;
                    break;
                }
            }

            InitialMessage.SetActive(showSearchingUI);
            if (showSearchingUI == false)
            {
                if (m_ControlObjects.Count > 0)
                {
                    ARMessage.SetActive(false);
                }
                else
                {
                    ARMessage.SetActive(true);
                    m_ControlObject = null;
                }
            }

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

            Touch touch = Input.GetTouch(0);

            //if (Frame.Raycast (touch.position.x, touch.position.y, raycastFilter, out hit))
            if (Frame.Raycast(Screen.width / 2, Screen.height / 2, raycastFilter, out hit))
            {
                m_CurrentPosition = hit.Pose.position;
                //m_CurrentRotation = hit.Pose.rotation;
                //if (firstCreate) {
                //    m_ControlObject.transform.localPosition = hit.Pose.position;
                //}
            }

            //if (touch.phase == TouchPhase.Ended) {
            //firstCreate = false;
            //}


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

            if (m_ButtonUIRect.Contains(touch.position))
            {
                return;
            }

            if (Input.touchCount == 1 && touch.phase == TouchPhase.Began)
            {
                Vector2    pos = touch.position;
                RaycastHit hitOjbect;
                Ray        ray = Camera.main.ScreenPointToRay(pos);
                if (Physics.Raycast(ray, out hitOjbect, 50.0f))
                {
                    if (m_RotationObject == hitOjbect.collider.gameObject)
                    {
                        m_IsSelectRotObj   = true;
                        m_BeginRotPosition = pos;
                    }
                    else
                    {
                        m_ControlObject             = hitOjbect.collider.gameObject;
                        m_ButtonRemove.interactable = true;
                        m_IsSelectRotObj            = false;
                    }
                }
                else
                {
                    m_IsSelectRotObj            = false;
                    m_ControlObject             = null;
                    m_ButtonRemove.interactable = false;
                }
            }

            if (m_ControlObject == null)
            {
                m_RotationObject.SetActive(false);
                return;
            }
            else
            {
                m_RotationObject.SetActive(true);
            }

            if (m_IsSelectRotObj)
            {
                if (touch.phase == TouchPhase.Moved)
                {
                    float d = Vector2.Distance(m_BeginRotPosition, touch.position) / 50.0f;
                    if (m_BeginRotPosition.x - touch.position.x < 0)
                    {
                        d *= -1;
                    }
                    m_ControlObject.transform.localEulerAngles += new Vector3(0.0f, d, 0.0f);
                }
            }

            if (m_Cancel)
            {
                m_Cancel = false;
                return;
            }

            if (Frame.Raycast(touch.position.x, touch.position.y, raycastFilter, out hit))
            {
                if (m_IsSelectRotObj == false)
                {
                    m_ControlObject.transform.localPosition  = hit.Pose.position;
                    m_RotationObject.transform.localPosition = hit.Pose.position;
                    m_RotationObject.transform.localRotation = hit.Pose.rotation;
                }
            }
        }
Example #28
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            _QuitOnConnectionErrors();

            // Check that motion tracking is tracking.
            if (Session.Status != SessionStatus.Tracking)
            {
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
                if (!m_IsQuitting && Session.Status.IsValid())
                {
                    SearchingForPlaneUI.SetActive(true);
                }

                return;
            }

            Screen.sleepTimeout = SleepTimeout.NeverSleep;

            //This variable only for check the object is placed or not
            //if placed then stoip the surface detection
            //else continue the surface detection


            Session.GetTrackables <DetectedPlane>(m_NewPlanes, TrackableQueryFilter.New);
            for (int i = 0; i < m_NewPlanes.Count; i++)
            {
                // Instantiate a plane visualization prefab and set it to track the new plane. The transform is set to
                // the origin with an identity rotation since the mesh for our prefab is updated in Unity World
                // coordinates.
                GameObject planeObject = Instantiate(TrackedPlanePrefab, Vector3.zero, Quaternion.identity,
                                                     transform);
                planeObject.GetComponent <DetectedPlaneVisualizer>().Initialize(m_NewPlanes[i]);
            }



            // Hide snackbar when currently tracking at least one plane.
            Session.GetTrackables <DetectedPlane>(m_AllPlanes);
            bool showSearchingUI = true;

            for (int i = 0; i < m_AllPlanes.Count; i++)
            {
                if (m_AllPlanes[i].TrackingState == TrackingState.Tracking)
                {
                    showSearchingUI = false;
                    //showDisplay = true;
                    break;
                }
            }

            SearchingForPlaneUI.SetActive(showSearchingUI);


            //m_ObjectPrefeb.SetActive(showDisplay);


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

            // 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))
            {
                if (currentNumberOfObjects < numberOfObjectsAllowed)
                {
                    currentNumberOfObjects = currentNumberOfObjects + 1;
                    var DisplayObject = Instantiate(MyDisplayCanvas, hit.Pose.position, hit.Pose.rotation);

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

                    // Andy should look at the camera but still be flush with the plane.
                    if ((hit.Flags & TrackableHitFlags.PlaneWithinPolygon) != TrackableHitFlags.None)
                    {
                        // Get the camera position and match the y-component with the hit position.
                        Vector3 cameraPositionSameY = FirstPersonCamera.transform.position;
                        cameraPositionSameY.y = hit.Pose.position.y;

                        // Have object look toward the camera respecting his "up" perspective, which may be from ceiling.
                        DisplayObject.transform.LookAt(cameraPositionSameY, DisplayObject.transform.up);
                    }

                    DisplayObject.transform.parent = anchor.transform;
                }
            }
        }
Example #29
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            _QuitOnConnectionErrors();

            // Check that motion tracking is tracking.
            if (Session.Status != SessionStatus.Tracking)
            {
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
                if (!m_IsQuitting && Session.Status.IsValid())
                {
                    SearchingForPlaneUI.SetActive(true);
                }

                return;
            }

            Screen.sleepTimeout = SleepTimeout.NeverSleep;

            // Iterate over planes found in this frame and instantiate corresponding GameObjects to visualize them.
            Session.GetTrackables <DetectedPlane>(m_NewPlanes, TrackableQueryFilter.New);
            for (int i = 0; i < m_NewPlanes.Count; i++)
            {
                // Instantiate a plane visualization prefab and set it to track the new plane. The transform is set to
                // the origin with an identity rotation since the mesh for our prefab is updated in Unity World
                // coordinates.
                GameObject planeObject = Instantiate(TrackedPlanePrefab, Vector3.zero, Quaternion.identity,
                                                     transform);
                planeObject.GetComponent <DetectedPlaneVisualizer>().Initialize(m_NewPlanes[i]);
            }

            // Hide snackbar when currently tracking at least one plane.

            Session.GetTrackables <DetectedPlane>(m_AllPlanes);
            bool showSearchingUI = true;

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

            SearchingForPlaneUI.SetActive(showSearchingUI);

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

            // 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))
            {
                if (currentNumberOfObjects < numberOfObjectsAllowed)
                {
                    currentNumberOfObjects = currentNumberOfObjects + 1;

                    var catObject = Instantiate(m_ObjectPrefeb, hit.Pose.position, hit.Pose.rotation);

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

                    // Andy should look at the camera but still be flush with the plane.
                    if ((hit.Flags & TrackableHitFlags.PlaneWithinPolygon) != TrackableHitFlags.None)
                    {
                        // Get the camera position and match the y-component with the hit position.
                        Vector3 cameraPositionSameY = FirstPersonCamera.transform.position;
                        cameraPositionSameY.y = hit.Pose.position.y;

                        // Have Andy look toward the camera respecting his "up" perspective, which may be from ceiling.
                        catObject.transform.LookAt(cameraPositionSameY, catObject.transform.up);
                    }

                    // Make Andy model a child of the anchor.
                    catObject.transform.parent = anchor.transform;
                }


                /*
                 *
                 *              if (Input.touchCount == 2||currentNumberOfObjects==numberOfObjectsAllowed)
                 *              {
                 *
                 *                      //store the both touch
                 *
                 *                      Touch touch1 = Input.GetTouch(0);
                 *                      Touch touch2 = Input.GetTouch(1);
                 *
                 *                      //Find the position of the previous fream of each touch
                 *                      Vector2 touch1PrePos = touch1.position - touch1.deltaPosition;
                 *                      Vector2 touch2PrePos = touch2.position - touch2.deltaPosition;
                 *
                 *                      //find the magnitude of the vector
                 *                      float prevTouchDeltaMag = (touch1PrePos - touch2PrePos).magnitude;
                 *                      float touchDeltaMag = (touch1.position - touch2.position).magnitude;
                 *                      //find the difference betwwen the magnitude
                 *
                 *                      float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
                 *
                 *                      // Change the scale based on the change in distance between the touches.
                 *
                 *                      FirstPersonCamera.fieldOfView += deltaMagnitudeDiff * ZoomSpeed;
                 *                      FirstPersonCamera.fieldOfView = Mathf.Clamp(FirstPersonCamera.fieldOfView, .1f, 179.9f);
                 *
                 *              }
                 */
            }

            //if there are two touch on the screen
            //To check the zooming option
        }
Example #30
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            _QuitOnConnectionErrors();

            // Check that motion tracking is tracking.
            if (Session.Status != SessionStatus.Tracking)
            {
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
                if (!m_IsQuitting && Session.Status.IsValid())
                {
                    SearchingForPlaneUI.SetActive(true);
                }

                return;
            }

            Screen.sleepTimeout = SleepTimeout.NeverSleep;

            ////Iterate over planes found in this frame and instantiate corresponding GameObjects to visualize them.
            //Session.GetTrackables<TrackedPlane>(m_NewPlanes, TrackableQueryFilter.New);
            //for (int i = 0; i < m_NewPlanes.Count; i++)
            //{
            //    Instantiate a plane visualization prefab and set it to track the new plane.The transform is set to
            //     the origin with an identity rotation since the mesh for our prefab is updated in Unity World
            //     coordinates.
            //    GameObject planeObject = Instantiate(TrackedPlanePrefab, Vector3.zero, Quaternion.identity,
            //        transform);
            //    planeObject.GetComponent<TrackedPlaneVisualizer>().Initialize(m_NewPlanes[i]);
            //}

            // Hide snackbar when currently tracking at least one plane.
            Session.GetTrackables <DetectedPlane>(m_AllPlanes);
            bool showSearchingUI = true;

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

            SearchingForPlaneUI.SetActive(showSearchingUI);

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

            // 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) && !clicked)
            {
                clicked = true;
                DetectedPlaneGenerator.SetActive(false);
                ShowObjects(hit);
            }
        }