예제 #1
0
        /// <summary>
        /// Swaps prefabs for game object
        ///
        /// action to take: 1-> put in new plant
        ///                 2-> harvest plant
        ///                 3-> grow new plant
        ///                 4-> wither plant
        /// </summary>
        public void Swap(GameObject tile, int plantModel, int plantType, int action)
        {
            string value;

            if (tileModels.TryGetValue(plantModel, out value))
            {
                //make new tile, copy components of old tile
                GameObject newTile = (GameObject)Instantiate(Resources.Load(value));

                //copy box collider
                newTile.AddComponent <BoxCollider>();
                GetCopyOf(tile.GetComponent <BoxCollider>(), newTile.GetComponent <BoxCollider>(), tile.GetComponent <BoxCollider>().GetType());
                newTile.GetComponent <BoxCollider>().size   = tile.GetComponent <BoxCollider>().size;
                newTile.GetComponent <BoxCollider>().center = tile.GetComponent <BoxCollider>().center;

                //copy mesh renderer and destory the old one
                MeshRenderer m = newTile.AddComponent <MeshRenderer>() as MeshRenderer;
                GetCopyOf(tile.GetComponent <MeshRenderer>(), m, tile.GetComponent <MeshRenderer>().GetType());
                DestroyImmediate(tile.GetComponent <MeshRenderer>());

                TileState newTileState = newTile.AddComponent <TileState>();

                switch (action)
                {
                //put new plant
                case 1:
                    newTileState.PutPlant(plantType, value);
                    break;

                //harvest plant
                case 2:
                    newTileState.Harvest(value);
                    break;

                //growth
                case 3:
                    GetCopyOf(tile.GetComponent <TileState>(), newTileState, newTileState.GetType());
                    newTileState.PlantModel = value;
                    break;

                //wither
                case 4:
                    newTileState.PlantModel  = value;
                    newTileState.IsWatered   = false;
                    newTileState.WateredLast = tile.GetComponent <TileState>().WateredLast;
                    break;

                default:
                    break;
                }

                newTile.transform.parent        = tile.transform.parent;
                newTile.transform.localPosition = tile.transform.localPosition;
                newTile.transform.localRotation = tile.transform.localRotation;
                newTile.transform.localScale    = tile.transform.localScale;
                DestroyImmediate(tile);
                tile = newTile;
            }
        }
예제 #2
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);



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


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

                farmCreated = true;
            }



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

                mSelected.color = Color.yellow;
            }

            try
            {
                CheckWaterLevel();
                _ShowAndroidToastMessage("Check Water OK!");
            }
            catch (Exception e)
            {
                //_ShowAndroidToastMessage("Water code crashed");
            }
            try
            {
                CheckPlantStage();
                _ShowAndroidToastMessage("Check Plant OK!");
            }
            catch (Exception e)
            {
                //_ShowAndroidToastMessage("Check plant crashed");
            }

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

                StorageInventory storage = plantButton.GetComponent <StorageInventory>();



                plantButton.onClick.AddListener(() =>
                {
                    //                    Plant(selectedTile, -1);
                    storage.OpenInventory();
                });
                waterButton.onClick.AddListener(() =>
                {
                    TileState oldState = selectedTile.GetComponent <TileState>();
                    TileState copy     = null;
                    GetCopyOf(oldState, copy, oldState.GetType());
                    DestroyImmediate(oldState);
                    TileState newState = selectedTile.AddComponent <TileState>();
                    GetCopyOf(copy, newState, copy.GetType());
                    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, 0);
                            storage.OpenInventory();
                        }
                        catch (Exception e)
                        {
                            _ShowAndroidToastMessage("Inventory Button listener crashed");
                        }
                    });

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

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

                    seedButtons[3].onClick.AddListener(() =>
                    {
                        try
                        {
                            _ShowAndroidToastMessage("Selected item at " + 3);
                            Plant(selectedTile, 3);
                            storage.OpenInventory();
                        }
                        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.localScale;
            //            newScale += percentageChange * newScale;

            //            farmObject.transform.localScale = newScale;

            //        }

            //    }
        }