예제 #1
0
    /// <summary>
    /// Gets proper next folder's position. Used to spawn folders in available positions.
    /// </summary>
    /// <returns>KeyValuePair of vertices used to calculate spawn position and spawn position.</returns>
    /// <param name="currentVertexFollowed">Current vertex followed.</param>
    public KeyValuePair <VertexController[], Vector2> GetNextFolderPosition(VertexController currentVertexFollowed)
    {
        int currentVertexIndex          = currentVertexFollowed.transform.GetSiblingIndex();
        int nextVertexIndex             = (currentVertexIndex + 1) % this.transform.childCount;
        VertexController nextVertex     = this.transform.GetChild(nextVertexIndex).GetComponent <VertexController>();
        int nextNextVertexIndex         = (currentVertexIndex + 2) % this.transform.childCount;
        VertexController nextNextVertex = this.transform.GetChild(nextNextVertexIndex).GetComponent <VertexController>();

        float   availableSpaceScale   = 0.5f;
        Vector2 availableSpaceVertex1 = currentVertexFollowed.transform.position + (nextVertex.transform.position - currentVertexFollowed.transform.position) * (1f - availableSpaceScale) / 3f;

        availableSpaceVertex1 += (Vector2)(nextNextVertex.transform.position - currentVertexFollowed.transform.position) * (1f - availableSpaceScale) / 3f;

        Vector2 availableSpaceVertex2 = nextVertex.transform.position + (currentVertexFollowed.transform.position - nextVertex.transform.position) * (1f - availableSpaceScale) / 3f;

        availableSpaceVertex2 += (Vector2)(nextNextVertex.transform.position - nextVertex.transform.position) * (1f - availableSpaceScale) / 3f;

        Vector2 availableSpaceVertex3 = nextNextVertex.transform.position + (currentVertexFollowed.transform.position - nextNextVertex.transform.position) * (1f - availableSpaceScale) / 3f;

        availableSpaceVertex3 += (Vector2)(nextVertex.transform.position - nextNextVertex.transform.position) * (1f - availableSpaceScale) / 3f;

        // Debug lines drawing, uncomment to debug this method
        //Debug.DrawLine(availableSpaceVertex1, availableSpaceVertex2, Color.white, 3f);
        //Debug.DrawLine(availableSpaceVertex2, availableSpaceVertex3, Color.white, 3f);
        //Debug.DrawLine(availableSpaceVertex3, availableSpaceVertex1, Color.white, 3f);

        VertexController[] returnList = { currentVertexFollowed, nextVertex, nextNextVertex };

        return(new KeyValuePair <VertexController[], Vector2>(returnList, Math3d.GetRandomPointInsideTriangle(availableSpaceVertex1, availableSpaceVertex2, availableSpaceVertex3)));
    }
예제 #2
0
    public override void Init()
    {
        this.model             = base.model as TriangleModel;
        model.verticesModelVec = new List <VertexModel>();

        for (int i = 0; i != model.view.transform.childCount; ++i)
        {
            VertexModel vertexModel = new VertexModel();

            vertexModel.componentsAssetID   = model.componentsAssetID;
            vertexModel.codeSnippetsAssetID = model.codeSnippetsAssetID;

            vertexModel.name   = "Vertex";
            vertexModel.parent = model;

            VertexView       vertexView       = model.view.transform.GetChild(i).gameObject.GetComponent_AutoAdd <VertexView>();
            VertexController vertexController = new VertexController();
            GameResourceManager.Instance.CombineMVC(vertexModel, vertexView, vertexController);

            vertexModel.OnPositionUpdated += InitTriangle;
            vertexModel.OnColorUpdated    += (Color => InitTriangle(Vector3.zero));

            model.verticesModelVec.Add(vertexModel);
        }

        InitTriangle(Vector3.zero);
    }
예제 #3
0
    /// <summary>
    /// Instantiate army object and send it from origin to target
    /// </summary>
    /// <param name="origin">Vertex A</param>
    /// <param name="target">Vertex B</param>
    /// <param name="amount">Army power to send</param>
    public void SendArmy(int origin, int target, int amount)
    {
        GameObject       vertexA = GameObject.Find($"vertex{origin}");
        VertexController originVertexController = vertexA.GetComponent <VertexController>();

        if (originVertexController.ArmyPower >= amount && amount > 0)
        {
            // Substract army power from the origin
            originVertexController.ArmyPower -= amount;

            // Position for new army object
            Vector3 spawnPosition = vertexA.gameObject.transform.position;
            spawnPosition.y = 0.25f;

            // Instantiate army object
            GameObject     newArmy        = Instantiate(ArmyObjectPrefab, spawnPosition, Quaternion.identity);
            ArmyController armyController = newArmy.GetComponent <ArmyController>();

            // Set army controller data
            armyController.Owner               = originVertexController.Owner;
            armyController.ArmyPower           = amount;
            armyController.OriginVertexIndexId = origin;
            armyController.TargetVertexIndexId = target;
        }
    }
예제 #4
0
    public void AssignMover(VertexController ctrller)
    {
        if (ctrller.mType == MyMesh.MeshType.Quad)              // quad vertex
        {
            mQuadVertexMover.SetActive(true);

            // if quad or cylinder
            if (prevQuadCtrller)
            {
                prevQuadCtrller.Unselected();
            }
            prevQuadCtrller = ctrller;

            ctrller.Selected(mQuadVertexMover);
        }
        else
        {
            mCylinderVertexMover.SetActive(true);
            if (prevCylinderCtrller)
            {
                prevCylinderCtrller.Unselected();
            }
            prevCylinderCtrller = ctrller;

            ctrller.Selected(mCylinderVertexMover);
        }
    }
예제 #5
0
    /// <summary>
    /// Check if player selects spell and first vertex (vertex to affect by spell)
    /// And cast spell then substract mana
    /// </summary>
    void CastPlayerSpell()
    {
        if (SelectedVertexA != null && SelectedVertexB == null && SpellToCast != -1)
        {
            switch (SpellToCast)
            {
            case 0:
                CastOffensiveSpell(SelectedVertexA);
                Mana[1] -= 100;
                break;

            case 1:
                CastEarthquakeSpell(SelectedVertexA);
                Mana[1] -= 300;
                break;

            case 2:
                CastTakeoverCast(SelectedVertexA, OwnerType.Player);
                Mana[1] -= 500;
                break;
            }

            SelectedVertexA = null;
            SetPositionOfSunshaft();

            SpellToCast = -1;
            GraphController.ClearSelection();
        }
    }
예제 #6
0
    /// <summary>
    /// Triggered on trigger enter with vertex
    /// </summary>
    /// <param name="vertex">Triggered vertex object</param>
    void CollideWithVertex(GameObject vertex)
    {
        VertexController vertexController = vertex.GetComponent <VertexController>();

        // Check if vertex is different than origin
        if (vertexController.Id != OriginVertexIndexId)
        {
            // Depending on owner of the vertex
            // sum army unit or perform battle
            if (vertexController.Owner == Owner)
            {
                vertexController.ArmyPower += ArmyPower;
            }
            else
            {
                vertexController.ArmyPower -= ArmyPower;

                if (vertexController.ArmyPower <= 0)
                {
                    vertexController.Owner     = Owner;
                    vertexController.ArmyPower = Mathf.Abs(vertexController.ArmyPower);
                }
            }

            Destroy(gameObject);
        }
    }
예제 #7
0
    /// <summary>
    /// Method used to calculate destination position when player jumps.
    /// </summary>
    /// <returns>The player's jump destination position.</returns>
    /// <param name="jumpStartPosition">Jump start position (typically, player's current position).</param>
    /// <param name="currentVertexFollowed">Current vertex that is being followed.</param>
    public Vector2 GetJumpDestinationPosition(Vector2 jumpStartPosition, VertexController currentVertexFollowed)
    {
        int currentVertexIndex  = currentVertexFollowed.transform.GetSiblingIndex();
        int previousVertexIndex = currentVertexIndex - 1;

        previousVertexIndex = previousVertexIndex < 0 ? previousVertexIndex + this.transform.childCount : previousVertexIndex;
        VertexController previousVertex = this.transform.GetChild(previousVertexIndex).GetComponent <VertexController>();
        int nextVertexIndex             = (currentVertexIndex + 1) % this.transform.childCount;
        VertexController nextVertex     = this.transform.GetChild(nextVertexIndex).GetComponent <VertexController>();

        Vector2 line = (nextVertex.transform.position - previousVertex.transform.position).normalized;

        line = line.y < 0 ? -line : line;
        float lineA = Mathf.Tan(Vector2.Angle(line, Vector2.right) * Mathf.Deg2Rad);
        float lineB = jumpStartPosition.y - (lineA * jumpStartPosition.x);

        Vector2 linePoint1 = new Vector2(0, lineB);
        Vector2 linePoint2 = new Vector2(1, lineA + lineB);

        // Debug lines drawing, uncomment to debug this method
        //Debug.DrawLine(previousVertex.transform.position, nextVertex.transform.position, Color.green, 3f);
        //Debug.DrawLine(linePoint1, linePoint2, Color.red, 3f);
        //Debug.DrawLine(jumpStartPosition + Vector2.left, jumpStartPosition + Vector2.right, Color.white, 3f);
        //Debug.DrawLine(jumpStartPosition + Vector2.down, jumpStartPosition + Vector2.up, Color.white, 3f);

        Vector3 intersectionPoint = Vector3.zero;

        Math3d.LineLineIntersection(out intersectionPoint, currentVertexFollowed.transform.position, (nextVertex.transform.position - currentVertexFollowed.transform.position).normalized, linePoint1, (linePoint2 - linePoint1).normalized);

        return(intersectionPoint);
    }
예제 #8
0
 public void UpdateAllVertexInstancesSelectable()
 {
     foreach (Vertex vertex in vertices)
     {
         GameObject       vertexInstance   = vertex.instance;
         VertexController vertexController = vertexInstance.GetComponent <VertexController>();
         vertexController.SetSelectable(vertexInstancesSelectable);
     }
 }
예제 #9
0
    /// <summary>
    /// Remove 100 army power for choosen vertex
    /// </summary>
    /// <param name="vertex"></param>
    public void CastOffensiveSpell(VertexController vertex)
    {
        vertex.ArmyPower -= 100;

        if (vertex.ArmyPower < 1)
        {
            vertex.ArmyPower = 1;
        }

        Instantiate(FireParticlesPrefab, vertex.transform.position, Quaternion.identity);
    }
예제 #10
0
    /// <summary>
    /// Send army from this vertex to another (if possible)
    /// </summary>
    public void SendArmy(int targetVertexIndexId, int amount)
    {
        foreach (GameObject connection in Connections)
        {
            VertexController connectedVertex = connection.GetComponent <VertexController>();

            if (targetVertexIndexId == connectedVertex.Id && amount <= ArmyPower - 1)
            {
                _graphController.SendArmy(Id, targetVertexIndexId, amount);
            }
        }
    }
예제 #11
0
    /// <summary>
    /// Substract half of the army power from vertex
    /// And change owner to the spell caster
    /// </summary>
    /// <param name="vertex"></param>
    /// <param name="whoCast"></param>
    public void CastTakeoverCast(VertexController vertex, OwnerType whoCast)
    {
        vertex.ArmyPower -= (int)Mathf.Floor(vertex.ArmyPower * 0.5f);

        if (vertex.ArmyPower < 1)
        {
            vertex.ArmyPower = 1;
        }

        vertex.Owner = whoCast;
        Instantiate(TakeoverParticlesPrefab, vertex.transform.position, Quaternion.identity);
    }
예제 #12
0
    void Start()
    {
        if (_gameplayController == null)
        {
            _gameplayController = GameObject.FindWithTag("Mechanism").GetComponent <GameplayController>();
        }

        // Load JSON and parse it
        TextAsset levelConfigContent = Resources.Load <TextAsset>("Config/levels");

        LevelConfig = JsonUtility.FromJson <LevelConfig>(levelConfigContent.text);

        // Get level index to render
        int levelToPlay = PlayerPrefs.GetInt("LevelToPlayIndex", 0);

        // Instantiate vertex for every entry in the LevelConfig
        foreach (VertexConfig vertexConfig in LevelConfig.levels[levelToPlay].verticies)
        {
            // Instantiate and set position based on coordinates
            GameObject newVertex = Instantiate(VertexObjectPrefab, new Vector3(vertexConfig.x * 1f, 0.5f, -vertexConfig.y * 1f), Quaternion.identity);

            // Get vertex controller from new vertex
            VertexController vertexController = newVertex.GetComponent <VertexController>();

            // And set values based on Vertex Config from Level Config
            vertexController.Id = vertexConfig.id;
            vertexController.X  = vertexConfig.x;
            vertexController.Y  = vertexConfig.y;

            vertexController.Owner = (OwnerType)vertexConfig.owner;
            vertexController.Type  = (VertexType)vertexConfig.type;

            vertexController.ArmyPower = vertexConfig.power;
            vertexController.Level     = vertexConfig.level;

            // Set meta-data, name and tag name used for future identifying vertex
            newVertex.tag  = "Vertex";
            newVertex.name = $"vertex{vertexConfig.id}";
        }

        // Set edges between vertices
        foreach (EdgeConfig connection in LevelConfig.levels[levelToPlay].edges)
        {
            GameObject vertexA = GameObject.Find($"vertex{connection.a}");
            GameObject vertexB = GameObject.Find($"vertex{connection.b}");

            vertexA.GetComponent <VertexController>().Connections.Add(vertexB);
            vertexB.GetComponent <VertexController>().Connections.Add(vertexA);

            SpawnRoad(vertexA.transform.position, vertexB.transform.position);
        }
    }
예제 #13
0
 /// <summary>
 /// Method used to fetch next vertex which should be used for player movement
 /// </summary>
 /// <returns>The next vertex which will be followed by the player</returns>
 /// <param name="currentVertexFollowed">Current vertex.</param>
 public VertexController GetNextVertexToFollow(VertexController currentVertexFollowed = null)
 {
     if (currentVertexFollowed)
     {
         int currentVertexIndex = currentVertexFollowed.transform.GetSiblingIndex();
         currentVertexIndex = (currentVertexIndex + 1) % this.transform.childCount;
         return(this.transform.GetChild(currentVertexIndex).GetComponent <VertexController>());
     }
     else
     {
         return(this.transform.childCount > 0 ? this.transform.GetChild(0).GetComponent <VertexController>() : null);
     }
 }
예제 #14
0
 /// <summary>
 /// Method used to fetch previous vertex which was followed before current one
 /// </summary>
 /// <returns>The previous vertex which was followed in the past</returns>
 /// <param name="currentVertexFollowed">Current vertex.</param>
 public VertexController GetPreviousVertexFollowed(VertexController currentVertexFollowed = null)
 {
     if (currentVertexFollowed)
     {
         int previousVertexIndex = currentVertexFollowed.transform.GetSiblingIndex();
         previousVertexIndex = previousVertexIndex - 1;
         previousVertexIndex = previousVertexIndex < 0 ? (previousVertexIndex + this.transform.childCount) : previousVertexIndex;
         return(this.transform.GetChild(previousVertexIndex).GetComponent <VertexController>());
     }
     else
     {
         return(this.transform.childCount > 0 ? this.transform.GetChild(0).GetComponent <VertexController>() : null);
     }
 }
예제 #15
0
    void UpdateNormals(Vector3[] v, Vector3[] n)
    {
        for (int i = 0; i < v.Length; i++)
        {
            Vector3 endpoint1 = v[i];
            Vector3 endpoint2 = v[i] + (normalLength * n[i]);

            Vector3 normVisualVector = endpoint2 - endpoint1;
            Vector3 vectorPos        = v[i] + (normVisualVector * 0.5f);

            VertexController vertexScript = mControllers[i].GetComponent <VertexController>();
            vertexScript.DisplayNormal(vectorPos, normVisualVector);
        }
    }
예제 #16
0
    public void setupLevel()
    {
        GameObject[] edges = GameObject.FindGameObjectsWithTag("Edge");
        foreach (GameObject edge in edges)
        {
            ElectricalElementController controller = edge.GetComponent <ElectricalElementController>();
            if (controller != null)
            {
                controller.Delete();
            }
        }
        GameObject[] vertices = GameObject.FindGameObjectsWithTag("Vertex");
        foreach (GameObject vertex in vertices)
        {
            VertexController controller = vertex.GetComponent <VertexController>();
            if (controller != null)
            {
                controller.spawnNewWire();
            }
        }
        TextAsset levelJSON = Resources.Load <TextAsset>(levelFiles[level]);
        LevelData levelData = JsonUtility.FromJson <LevelData>(levelJSON.ToString());

        setupObject(battery, levelData.battery, levelData.batteryCoords, levelData.batteryRot);
        setupObject(bulb, levelData.bulb, levelData.bulbCoords, levelData.bulbRot);
        setupObject(resistor, levelData.resistor, levelData.resistorCoords, levelData.resistorRot);
        setupObject(toggle, levelData.toggle, levelData.toggleCoords, levelData.toggleRot);
        screen.material = instructions[level];
        ui.SetActive(true);
        if (level == 0)
        {
            ui.GetComponent <UIController>().PrevActive(false);
        }
        else
        {
            ui.GetComponent <UIController>().PrevActive(true);
        }

        if (level == levelFiles.Length - 1)
        {
            ui.GetComponent <UIController>().NextActive(false);
        }
        else
        {
            ui.GetComponent <UIController>().NextActive(true);
        }
    }
예제 #17
0
    /// <summary>
    /// Substract 50 army power from each vertex of vertex owner
    /// </summary>
    /// <param name="vertex"></param>
    public void CastEarthquakeSpell(VertexController vertex)
    {
        foreach (VertexController tempVertex in VertexList)
        {
            if (tempVertex.Owner == vertex.Owner)
            {
                tempVertex.ArmyPower -= 50;

                if (tempVertex.ArmyPower < 1)
                {
                    tempVertex.ArmyPower = 1;
                }

                Instantiate(EarthQuakeParticlesPrefab, tempVertex.transform.position, Quaternion.identity);
            }
        }
    }
예제 #18
0
 /// <summary>
 /// Method used to spawn new folder in proper position (according to current shape and player's position)
 /// </summary>
 /// <param name="currentDestinationVertex">Current destination vertex which is followed by player.</param>
 public FolderController SpawnFolder(VertexController currentDestinationVertex)
 {
     // NOTE: For now, only one folder possible at the same time!
     for (int i = 0; i < this.transform.childCount; i++)
     {
         this.transform.GetChild(i).GetComponent <FolderController>().Deactivate();
     }
     for (int i = 0; i < this.transform.childCount; i++)
     {
         if (this.transform.GetChild(i).GetComponent <FolderController>().IsFolderInPool())
         {
             this.transform.GetChild(i).GetComponent <FolderController>().Activate(ShapeController.instance.GetNextFolderPosition(currentDestinationVertex));
             return(this.transform.GetChild(i).GetComponent <FolderController>());
         }
     }
     return(null);
 }
예제 #19
0
    /// <summary>
    /// Check if owner of vertex has sufficient amount of honey
    /// Then upgrade or not vertex by increasing vertex level
    /// </summary>
    /// <param name="vertex">Vertex to upgrade</param>
    public void UpgradeVertex(VertexController vertex)
    {
        if (vertex.Level < 5 && Honey[(int)vertex.Owner] >= vertex.Level * 25)
        {
            Honey[(int)vertex.Owner] -= vertex.Level * 25;
            vertex.Level++;
            vertex.SetViewObject();

            if (vertex.Level == 5)
            {
                SelectedVertexA = null;
                SelectedVertexB = null;
                SetPositionOfSunshaft();
            }

            Instantiate(UpgradeParticlesPrefab, vertex.transform.position, Quaternion.identity);
        }
    }
예제 #20
0
        public void SelectionTransformDirection(Vector3 directionVector)
        {
            GameObject mockController = new GameObject();

            mockController.transform.position = Vector3.zero;

            GameObject       instanceOfOrigin = selectedVertices.First().vertex.instance;
            VertexController vertexController = instanceOfOrigin.GetComponent <VertexController>();

            vertexController.SelectionDragStart(mockController.transform, 0, instanceOfOrigin, false, true);
            BroadcastDragStart(mockController.transform, 0, instanceOfOrigin, true);

            mockController.transform.position = mockController.transform.position + directionVector;

            vertexController.SelectionDragUpdate(mockController.transform, 0, instanceOfOrigin, false);
            BroadcastDragUpdate(mockController.transform, 0, instanceOfOrigin);
            vertexController.SelectionDragEnd(mockController.transform, 0, instanceOfOrigin, false);
            BroadcastDragEnd(mockController.transform, 0, instanceOfOrigin);
        }
예제 #21
0
        public GameObject CreateVertexInstanceByLocalPosition(Vector3 localPosition)
        {
            Vector3 position = mesh.transform.TransformPoint(localPosition);

            //Debug.Log("MeshController#CreateVertices localPosition="+localPosition+",position=" + position+",this.transform.position=" + this.transform.position);
            GameObject vertexInstance = InstantiateOrGetFromPool(position, mesh.transform.rotation);

            vertexInstance.transform.parent = mesh.transform;
            vertexInstance.GetComponent <Selectable>().Initialize();
            if (hideVertices)
            {
                vertexInstance.SetActive(false);
            }
            VertexController vertexController = vertexInstance.GetComponent <VertexController>();

            vertexController.SetSelectable(vertexInstancesSelectable);
            vertexController.SetStickySelected(false);
            vertexController.CreateFromLocalPosition(localPosition, mesh, false);
            return(vertexInstance);
        }
예제 #22
0
    public override void Init()
    {
        // DO NOT trigger base init, or it will create component for texture quad

        this.model = base.model as TextureQuadModel;

        verticesPos      = new Vector3[4];
        verticesTexcoord = new Vector2[4];
        indexes          = new int[6] {
            0, 3, 2, 0, 2, 1
        };

        model.verticesModelVec = new List <VertexModel>();

        for (int i = 0; i != model.view.transform.childCount; ++i)
        {
            // TODO: refactor
            int         index       = i;
            VertexModel vertexModel = new VertexModel();
            vertexModel.componentsAssetID   = model.componentsAssetID; // set the vertex components id
            vertexModel.codeSnippetsAssetID = model.codeSnippetsAssetID;
            vertexModel.name   = "Vertex";
            vertexModel.parent = model;

            VertexView       vertexView       = model.view.transform.GetChild(i).gameObject.GetComponent_AutoAdd <VertexView>();
            VertexController vertexController = new VertexController();
            GameResourceManager.Instance.CombineMVC(vertexModel, vertexView, vertexController);

            vertexModel.OnPositionUpdated += ((pos) => UpdateVertexPos(index, pos));
            vertexModel.OnTexcoordUpdated += ((texcoord) => UpdateVertexTexcoord(index, texcoord));
            model.verticesModelVec.Add(vertexModel);
        }

        for (int i = 0; i != model.view.transform.childCount; ++i)
        {
            verticesPos[i]      = model.verticesModelVec[i].position;
            verticesTexcoord[i] = model.verticesModelVec[i].texcoord;
        }
        UpdateVertexData();
    }
예제 #23
0
    //Script to toggle the control points for vertices on/off
    void ToggleControllers(bool state)
    {
        foreach (GameObject controller in mControllers)
        {
            MeshRenderer     controlRend   = controller.GetComponent <MeshRenderer>();
            VertexController controlScript = controller.GetComponent <VertexController>();

            controlRend.enabled   = state;
            controlScript.enabled = state;

            if (controller == selectedController)
            {
                controlScript.ToggleAxes(state);
            }
            else
            {
                controlScript.ToggleAxes(false);
            }

            controlScript.ToggleNormal(state);
        }
    }
예제 #24
0
 public void AssignMover()
 {
     MyMesh.MeshType type = GetActiveMesh().mType;
     if (type == MyMesh.MeshType.Quad)
     {
         mQuadVertexMover.SetActive(false);
         if (prevQuadCtrller)
         {
             prevQuadCtrller.Unselected();
             prevQuadCtrller = null;
         }
     }
     else
     {
         mCylinderVertexMover.SetActive(false);
         if (prevCylinderCtrller)
         {
             prevCylinderCtrller.Unselected();
             prevCylinderCtrller = null;
         }
     }
 }
예제 #25
0
    //Script to tell the mesh which vertex is currently selected
    public void SetSelectedVert(GameObject vertex)
    {
        foreach (GameObject controller in mControllers)
        {
            VertexController controlScript = controller.GetComponent <VertexController>();

            //If the current game object in the loop is the newly selected vertex,
            //update its color. If not, set it to the default color (white)
            if (GameObject.ReferenceEquals(controller, vertex))
            {
                selectedController = controller;
                MeshRenderer controlRenderer = controller.GetComponent <MeshRenderer>();
                controlRenderer.material = selectedMaterial;
                controlScript.ToggleAxes(true);
            }
            else
            {
                MeshRenderer controlRenderer = controller.GetComponent <MeshRenderer>();
                controlRenderer.material = defaultMaterial;
                controlScript.ToggleAxes(false);
            }
        }
    }
예제 #26
0
    /// <summary>
    /// Moves units between vertices depending on vertex state
    /// </summary>
    void MoveAI()
    {
        foreach (VertexController vertex in _gameplayController.VertexList)
        {
            // Check if current vertex isn't player or wild
            if (vertex.Owner != OwnerType.Player && vertex.Owner != OwnerType.Wild)
            {
                // Check if vertex has neighbour,
                // if not then switch to second state
                List <VertexController> enemyNeighbours = new List <VertexController>();

                foreach (GameObject connection in vertex.Connections)
                {
                    VertexController connectedVertex = connection.GetComponent <VertexController>();

                    if (vertex.Owner != connectedVertex.Owner)
                    {
                        // First state, use Dijkstra to
                        enemyNeighbours.Add(connectedVertex);
                    }
                }

                // Sort list of enemy vertices to find vertex with lowest army power (weight)
                List <VertexController> sortedEnemyNeighbours = enemyNeighbours.OrderBy(o => o.ArmyPower).ToList();

                if (enemyNeighbours.Count > 0)
                {
                    foreach (VertexController enemyVertex in sortedEnemyNeighbours)
                    {
                        // Check if vertex has sufficient amount of army power to move
                        if (vertex.ArmyPower > enemyVertex.ArmyPower * 1.3f)
                        {
                            vertex.SendArmy(enemyVertex.Id, (int)(enemyVertex.ArmyPower * 1.3f));
                        }
                    }
                }

                // Second state, use Breadth-first search algorithm to determine where to move units
                if (enemyNeighbours.Count == 0)
                {
                    List <VertexController> verticesWithEnemyNeighbours = new List <VertexController>();

                    // Search for all vertices of current vertex
                    foreach (VertexController tempVertex in _gameplayController.VertexList)
                    {
                        if (tempVertex.Owner == vertex.Owner)
                        {
                            bool hasEnemyNeighbours = false;

                            foreach (GameObject connectedToEnemyVertex in tempVertex.Connections)
                            {
                                if (connectedToEnemyVertex.GetComponent <VertexController>().Owner != tempVertex.Owner)
                                {
                                    hasEnemyNeighbours = true;
                                }
                            }

                            if (hasEnemyNeighbours)
                            {
                                verticesWithEnemyNeighbours.Add(tempVertex);
                            }
                        }
                    }

                    // Function, which returns shortes path between this vertex and picked
                    Func <int, IEnumerable <int> > shortestPath = ShortestPath(_graph, vertex.Id);

                    int indexOfVertexToTraverse             = -1;
                    int armyPowerOfVertexToTraverse         = int.MaxValue;
                    int jumpDistanceToNearestMatchingVertex = int.MaxValue;

                    foreach (VertexController tempVertex in verticesWithEnemyNeighbours)
                    {
                        // Shortest path to tempVertex
                        List <int> pathJumps = shortestPath(tempVertex.Id).ToList();

                        if (pathJumps.Count < jumpDistanceToNearestMatchingVertex)
                        {
                            jumpDistanceToNearestMatchingVertex = pathJumps.Count;
                            indexOfVertexToTraverse             = pathJumps[1];
                            armyPowerOfVertexToTraverse         = tempVertex.ArmyPower;
                        }
                        else if (pathJumps.Count == jumpDistanceToNearestMatchingVertex && armyPowerOfVertexToTraverse > tempVertex.ArmyPower)
                        {
                            jumpDistanceToNearestMatchingVertex = pathJumps.Count;
                            indexOfVertexToTraverse             = pathJumps[1];
                            armyPowerOfVertexToTraverse         = tempVertex.ArmyPower;
                        }
                    }

                    // If found vertex to traverse, then send army
                    if (indexOfVertexToTraverse != -1)
                    {
                        // Print result
                        Debug.Log($"From {vertex.Id} to {indexOfVertexToTraverse}");

                        if (vertex.ArmyPower > 1)
                        {
                            vertex.SendArmy(indexOfVertexToTraverse, vertex.ArmyPower - 1);
                        }
                    }
                }
            }
        }
    }
예제 #27
0
    // Update is called once per frame
    void Update()
    {
        if (!UIController.instance || !UIController.instance.GameStarted)
        {
            return;
        }

        if (this.GetComponent <PolygonCollider2D>().enabled)
        {
            // Calculating jump position
            if (currentDestinationJumpPoint == Vector2.zero)
            {
                currentDestinationJumpPoint = ShapeController.instance.GetJumpDestinationPosition(this.transform.position, currentDestinationVertex);
                Vector3 vectorToTarget = currentDestinationJumpPoint - (Vector2)this.transform.position;
                currentDestinationRotation  = Quaternion.AngleAxis(Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg, Vector3.forward);
                currentDestinationRotation *= Quaternion.Euler(Vector3.back * 114f);
            }

            // Calculating folder's touch checkpoint
            if (!oddVertexFollowing && currentFolder != null)
            {
                if (currentFolderCheckPoint == Vector2.zero)
                {
                    currentFolderCheckPoint = Math3d.ProjectPointOnLineSegment(this.transform.position, currentDestinationJumpPoint, currentFolder.transform.position);
                    if (Math3d.PointOnWhichSideOfLineSegment(this.transform.position, currentDestinationJumpPoint, currentFolderCheckPoint) != 0)
                    {
                        currentFolderCheckPoint = Vector2.one;
                    }
                }

                // Checking miss conditions
                if (currentFolderCheckPoint == Vector2.one || Vector2.Distance(currentFolderCheckPoint, this.transform.position) <= Time.deltaTime * Speed)
                {
                    // Folder missed!
                    if (currentFolder.isActive)
                    {
                        currentFolder.Deactivate();

                        // Shape modification (previous vertex translation)
                        float            distance = Vector2.Distance(this.transform.position, currentFolder.transform.position);
                        VertexController previousDestinationVertex = ShapeController.instance.GetPreviousVertexFollowed(currentDestinationVertex);
                        Vector2          destinationPosition       = (currentDestinationVertex.transform.position - previousDestinationVertex.transform.position).normalized;
                        previousDestinationVertex.TranslateByVector(destinationPosition * distance * 0.75f);
                    }
                }
            }

            // Following jump position
            this.transform.position = Vector2.MoveTowards(this.transform.position, currentDestinationJumpPoint, Time.deltaTime * JumpSpeed);
            this.transform.rotation = Quaternion.Slerp(transform.rotation, currentDestinationRotation, Time.deltaTime * 16f);

            // TODO: Cursor dash effects (shaking, particles... ???)

            // Finishing jump, spawning folder and following next vertex
            if (Vector2.Distance(this.transform.position, currentDestinationJumpPoint) <= Time.deltaTime * Speed)
            {
                currentDestinationVertex.Show();
                currentDestinationVertex   = ShapeController.instance.GetNextVertexToFollow(currentDestinationVertex);
                currentDestinationRotation = Quaternion.identity;
                oddVertexFollowing         = !oddVertexFollowing;
                if (UIController.instance.GameInteractive && oddVertexFollowing)
                {
                    currentFolder = FoldersPoolController.instance.SpawnFolder(currentDestinationVertex);
                }
                this.transform.position = currentDestinationJumpPoint;
                this.GetComponent <PolygonCollider2D>().enabled = false;
            }
        }
        else
        {
            // Following next vertex
            if (currentDestinationVertex == null || Vector2.Distance(this.transform.position, currentDestinationVertex.transform.position) < Time.deltaTime)
            {
                if (currentDestinationVertex != null)
                {
                    if (!currentDestinationVertex.isHidden)
                    {
                        UIController.instance.FireGameOver();
                    }

                    this.transform.position = currentDestinationVertex.transform.position;
                    currentDestinationVertex.Show();
                }
                currentDestinationVertex   = ShapeController.instance.GetNextVertexToFollow(currentDestinationVertex);
                currentDestinationRotation = Quaternion.identity;
                oddVertexFollowing         = !oddVertexFollowing;
                if (UIController.instance.GameInteractive && oddVertexFollowing)
                {
                    currentFolder = FoldersPoolController.instance.SpawnFolder(currentDestinationVertex);
                }
            }
            this.transform.position = Vector2.MoveTowards(this.transform.position, currentDestinationVertex.transform.position, Time.deltaTime * Speed);
            this.transform.rotation = Quaternion.Slerp(transform.rotation, currentDestinationRotation, Time.deltaTime * 16f);

            // User input for jumping
            if (Input.GetMouseButtonDown(0))
            {
                ShapeController.instance.GetNextVertexToFollow(currentDestinationVertex).Hide();
                currentDestinationJumpPoint = Vector2.zero;
                currentFolderCheckPoint     = Vector2.zero;
                this.GetComponent <PolygonCollider2D>().enabled = true;
            }
        }
    }
예제 #28
0
    void ProcessMouseEvent()
    {
        // L ALT camera ctrl
        if (Input.GetKey(KeyCode.LeftAlt))
        {
            if (EventSystem.current.IsPointerOverGameObject())
            {
                return;
            }

            // LMB
            if (Input.GetMouseButtonDown(0))
            {
                mCamera.LMBPress(Input.mousePosition);
            }
            else if (Input.GetMouseButton(0))
            {
                mCamera.LMBMove(Input.mousePosition);
            }
            else if (Input.GetMouseButtonUp(0))
            {
                mCamera.LMBRelease();
            }

            //RMB
            else if (Input.GetMouseButtonDown(1))
            {
                mCamera.RMBPress(Input.mousePosition);
            }
            else if (Input.GetMouseButton(1))
            {
                mCamera.RMBMove(Input.mousePosition);
            }
            else if (Input.GetMouseButtonUp(1))
            {
                mCamera.RMBRelease();
            }

            // wheel
            else if (Mathf.Abs(Input.GetAxis("Mouse ScrollWheel")) > 0.00000001)
            {
                mCamera.MouseScroll(Input.GetAxis("Mouse ScrollWheel"));
            }
        }

        // L CTRL vertices ctrl switch
        if (Input.GetKey(KeyCode.LeftControl))
        {
            mActiveMesh.EnableControllers();
            mActiveMesh.EnableNormals();

            if (EventSystem.current.IsPointerOverGameObject())
            {
                //mActiveMesh.DisableControllers();
                //mActiveMesh.DisableNormals();
                return;
            }


            if (Input.GetMouseButtonDown(0))
            {
                RaycastHit hitInfo = new RaycastHit();

                // clickable objects are on layer 9
                bool hit = Physics.Raycast(mCamera4RayCast.ScreenPointToRay(
                                               Input.mousePosition), out hitInfo, Mathf.Infinity, 1 << 9);

                // click on vertex ctrller or mover
                if (hit)
                {
                    GameObject hitObject = hitInfo.transform.gameObject;

                    VertexController vController = hitObject.GetComponent <VertexController>();
                    // click on vertex ctrl
                    if (vController != null && vController.mAvailable)
                    {
                        // switch mover on
                        mWorld.AssignMover(vController);
                    }

                    // click on mover axis
                    else
                    {
                        mSelectedVertexTranslate = hitObject.GetComponent <VertexTranslate>();
                        if (mSelectedVertexTranslate != null)
                        {
                            // set initial translate position


                            Vector3 point    = new Vector3();
                            Vector2 mousePos = new Vector2
                            {
                                x = Input.mousePosition.x,
                                y = Input.mousePosition.y
                                    //mCamera4RayCast.pixelHeight -
                            };

                            point = mCamera4RayCast.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y,
                                                                                   mCamera4RayCast.nearClipPlane));
                            mSelectedVertexTranslate.LMBPress(point);
                        }
                    }
                }
                else
                {
                    // switch mover off
                    mWorld.AssignMover();
                }
            }
            // drag support
            else if (Input.GetMouseButton(0))
            {
                if (mSelectedVertexTranslate)
                {
                    Vector3 point    = new Vector3();
                    Vector2 mousePos = new Vector2
                    {
                        x = Input.mousePosition.x,
                        y = Input.mousePosition.y
                            //mCamera4RayCast.pixelHeight -
                    };

                    point = mCamera4RayCast.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y,
                                                                           mCamera4RayCast.nearClipPlane));

                    mSelectedVertexTranslate.LMBMove(point);
                }
            }
            // release LMB
            else if (Input.GetMouseButtonUp(0))
            {
                if (mSelectedVertexTranslate != null)
                {
                    mSelectedVertexTranslate.LMBRelease();
                }
                mSelectedVertexTranslate = null;
            }
        }
        // release LCTRL
        else
        {
            mActiveMesh.DisableControllers();
            mActiveMesh.DisableNormals();
        }
    }