public bool isAdj(GridBlock blk){
		if(blk == up || blk == down || blk == left || blk == right){
			return true;
		} else{
			return false;
		}
	}
	/// <summary>
	/// Calls the GUI to display this action on the game.
	/// </summary>
	/// <param name="gui">GUI.</param>
	public override void displayUserSelection(){
		if(unit.movmentRemaning() <= 0){
			Debug.Log("no movment actions remaning");
			return;
		}
		unitBlock = unit.getVirtualBlockHeadLocation();
		checkAndDisplayPossibleUserActions();
	}
	public GridBlock getVirtualBlockHeadLocation(){
		//Check if unit is destroyed.
		if(blockList.Count == 0)
			return null;
		if(virtualBlockHead == null)
			virtualBlockHead = blockList.First.Value;
		return virtualBlockHead;
	}
	private bool possibleMoveLocation(GridBlock block){
		bool canMove = true;
		if(block == null)
			return false;
		// True if no unit installed.
		canMove = block.unitInstalled == null;
		return canMove;
	}
	//Constructor for AI.
	public AttackScript(UnitScript u, GridBlock attackLocation) : this(u){
		this.attackLocation = attackLocation;


		if(attackLocation.unitInstalled == null)
			Debug.LogWarning("No unit to attack!");

		SerializedCompletedAction sac = new SerializedCompletedAction();
		sac.locationToPerformAction = attackLocation.gridLocation;
		sac.actionAmountInt = unit.getAttackPower();
		loadAction(sac);

		u.addActionToQueue(this);
	}
    public void RemoveObjectFromGrid(GameObject gameObject, Vector2Int gridLocation)
    {
        GridBlock origin = FindGridBlockByLocation(gridLocation);

        if (origin.objectsOnBlock.Count > 0)
        {
            for (int i = origin.objectsOnBlock.Count - 1; i >= 0; i--)
            {
                if (gameObject == origin.objectsOnBlock[i])
                {
                    origin.objectsOnBlock.RemoveAt(i);
                    return;
                }
            }
        }
    }
Exemple #7
0
    public void SetGrid(GridBlock moveFrom, List <Enums.GridBlockType> favTerrain, int moveDistance, int minAttackDistance, int maxAttackDistance)
    {
        bool saveParams = true;

        if (Unpassable || (!Utility.TrueNull(CurrentUnit) && CurrentUnit.IsEnemy(Enums.Player.Player1)) || _unitsMovingThrough.Any(uC => uC != null && uC.IsEnemy(Enums.Player.Player1)))
        {
            moveDistance = -1;
        }

        if (moveFrom == null)
        {
            moveDistance += (favTerrain.Contains(this.Type) ? 1 : MovementCost);
        }

        moveDistance = Mathf.Clamp(moveDistance - (favTerrain.Contains(this.Type) ? 1 : MovementCost), -1, 9999); // If this terrain is favorable to the unit, only subtract one.

        if (moveDistance >= 0)
        {
            _gridParams.ActiveSpace = Enums.ActiveSpace.Move;
            _gridParams.ShowMoveSpace(moveFrom?.Position);
        }
        else if (maxAttackDistance > 0)
        {
            _gridParams.ActiveSpace = Enums.ActiveSpace.Attack;
            _gridParams.ShowAttackSpace(moveFrom?.Position);
            maxAttackDistance--;
        }
        else
        {
            _gridParams.Reset();
            saveParams = false;
        }

        //if (moveFrom == null)
        //    text.text = "";
        //text.text += $"{gameObject.name}::: moveDis:{moveDistance}, minAttack:{minAttackDistance}, maxAttack:{maxAttackDistance}, neighbors:{Neighbors.Count()} |||||| ";

        if (saveParams)
        {
            _gridParams.FavorableTerrain  = favTerrain;
            _gridParams.MoveDistance      = moveDistance;
            _gridParams.MinAttackDistance = minAttackDistance;
            _gridParams.MaxAttackDistance = maxAttackDistance;
        }

        _pM.UpdateBlockGrid(GridPosition, this, saveParams);
    }
Exemple #8
0
        protected virtual void CalculateBounds(ref ShortPoint location, out BoundingBoxExt bounds, out Vector2 origin)
        {
            var blockSize = BlockSize;
            int left, top, right, bottom;

            GridBlock.CalculateEdges(ref blockSize, ref location, out left, out top, out right, out bottom);

            var     size = CellSize;
            var     topLeft = new Vector3(left * size.X, top * size.Y, 0);
            var     bottomRight = new Vector3(right * size.X, bottom * size.Y, 0);
            Vector3 min, max;

            Vector3.Min(ref topLeft, ref bottomRight, out min);
            Vector3.Max(ref topLeft, ref bottomRight, out max);

            bounds = new BoundingBoxExt(min, max);
            origin = topLeft.XY();
        }
Exemple #9
0
    public void UpdateBlockGrid(Vector2 pos, GridBlock gB, bool showOnGrid)
    {
        var grid = PlayerInfo.BlockGrid;

        if (pos.x < grid.GetLength(0) && pos.y < grid.GetLength(0))
        {
            if (showOnGrid)
            {
                PlayerInfo.ActiveGrid.Add(gB);
            }
            else
            {
                PlayerInfo.ActiveGrid.Remove(gB);
                gB = null;
            }
            PlayerInfo.BlockGrid[(int)pos.x, (int)pos.y] = gB;
        }
    }
Exemple #10
0
    public void Resize(int numCols, int numRows)
    {
        if (_grid == null)
        {
            _grid = new GridBlock[numRows * numCols];
        }
        GridBlock[] newGrid = new GridBlock[numRows * numCols];
        int         minX    = Math.Min(_cols, numCols);
        int         minY    = Math.Min(_rows, numRows);

        for (int i = 0; i < minY; i++)
        {
            Array.Copy(_grid, i * _rows, newGrid, i * numRows, minX);
        }
        _grid = newGrid;
        _rows = numRows;
        _cols = numCols;
    }
	//Constructor for AI.
	public MoveScript(UnitScript u, GridBlock b) : this(u){
		bool validMove = false;
		adjBlocks = new GridBlock[4];
		for(int i = 0; i < adjBlocks.Length; i++){
			adjBlocks[i] = u.getBlockList().First.Value.getAdj(i);
			if(b == adjBlocks[i])
				validMove = true;
		}

		if(!validMove)
			Debug.LogWarning("Move not valid!");

		SerializedCompletedAction sac = new SerializedCompletedAction();
		sac.locationToPerformAction = b.gridLocation;
		loadAction(sac);

		u.addActionToQueue(this);
	}
Exemple #12
0
        /// <summary>
        /// Cria os dados para ser colocados no grid.
        /// </summary>
        private void CreateDataFromBlockList()
        {
            var blocks = IpBlockList.IpBlocked;
            var list   = new List <string>();

            foreach (var block in blocks.Values)
            {
                list.Add(block.Ip + "");
                list.Add(block.Time + "");
                list.Add(block.AccessCount + "");
                list.Add(block.AttemptCount + "");
                list.Add(block.Permanent.ToString());
            }

            FillData(ref list);

            GridBlock.Sort(GridBlock.Columns[0], ListSortDirection.Ascending);
        }
Exemple #13
0
    public bool GridMatrixContains(GridBlock gB)
    {
        var matrix  = PlayerInfo.BlockGrid;
        int mLength = matrix.GetLength(0);

        for (int i = 0; i < mLength; i++)
        {
            for (int ii = 0; ii < mLength; ii++)
            {
                if (matrix[i, ii] == gB)
                {
                    return(true);
                }
            }
        }

        return(false);
    }
Exemple #14
0
    private void GetNextPoint()
    {
        var currentPoint  = _nextPoint;
        var possiblePoint = _movePositions.Peek();

        if (possiblePoint == null || possiblePoint.Position.GridDistance(Position) > 1) // Make sure the next point is one point away, this should trigger VERY rarely
        {
            var orderedNeighbors = CurrentGridBlock.Neighbors.OrderByDistance(possiblePoint);
            foreach (GridBlock gB in orderedNeighbors)
            {
                if (gB.Position.GridDistance(possiblePoint.Position) <= 1)
                {
                    possiblePoint = gB;
                    break;
                }
            }
        }
        else
        {
            _movePositions.Dequeue();                                                                                                            // point is fine go ahead and remove it from queue
        }
        if (currentPoint != null && _movePositions.IsEmpty() && possiblePoint.CurrentUnit != null && !possiblePoint.CurrentUnit.IsEnemy(Player)) // if this is the last point in the queue make sure it's not empty
        {
            if (currentPoint.CurrentUnit == this)                                                                                                // Last spot is taken and current spot is safe to stay at
            {
                _nextPoint = null;
                return;
            }
            else // current spot isn't safe so find a new spot
            {
                FindGoodPreviousSpot();
                GetNextPoint();
                return;
            }
        }

        _nextPoint         = possiblePoint;
        Moving             = true;
        _minimapIcon.color = Player == Enums.Player.Player1 ? Colors.Player_Moving : Colors.Enemy_Moving;
        _unitState         = Enums.UnitState.Moving;
        BoxCollider.size   = ColliderSizeMoving;
        _animator.SetBool("Moving", true);
        LookAt(possiblePoint.Position);
    }
Exemple #15
0
    //Check all the tiles of the gridblock
    //If a tile is the type of Vacant, then it will be cleared
    //If a tile is the type of Vestige, then a 1x1 gridblock will be created
    //and the new gridblock will fall to the bottom of the grid or be obstructed
    //by other tiles and stop right there
    public void ActivateVestiges()
    {
        List <GridBlock> vestiges = new List <GridBlock>();

        /*
         * // Clear all of the Vacant Tiles.
         * for (int r = 0; r < block.GetHeight(); r++)
         * {
         *  for (int c = 0; c < block.GetWidth(); c++)
         *  {
         *      if (GetTileType(r, c) == TileData.TileType.Vacant)
         *      {
         *          Clear(r, c);
         *      }
         *  }
         * }
         */

        for (int r = 0; r < block.GetHeight(); r++)
        {
            for (int c = 0; c < block.GetWidth(); c++)
            {
                if (GetTileType(r, c) == TileData.TileType.Regular)
                {
                    Block b = new Block(1, 1);
                    b.Fill(0, 0, TileData.TileType.Vestige);
                    int       vestigeRow = row + r;
                    int       vestigeCol = col + c;
                    GridBlock gb         = grid.WriteBlock(vestigeRow, vestigeCol, b);
                    vestiges.Add(gb);
                }
            }
        }

        vestiges.Sort((y, x) => x.GetRow().CompareTo(y.GetRow()));

        /*foreach (GridBlock gb in vestiges)
         * {
         *  gb.MoveRepeatedly(Enums.Direction.Down);
         * }*/

        // Remove this GridBlock from the Grid since it has been broken into smaller GridBlocks.
        grid.RemoveGridBlock(this);
    }
        private void HandleFaceSelect()
        {
            Event      e = Event.current;
            RaycastHit hit;

            if (EditorUtils.SceneViewMouseRaycast(GetHashCode(), e, out hit))
            {
                if ((e.type == EventType.MouseDown && e.button == 0))
                {
                    GridBlock block = hit.collider.GetComponent <GridBlock>();
                    if (block == null)
                    {
                        return;
                    }

                    Deselect();
                    _squareSel[0] = new FaceSelection(block, hit.normal);


                    _selectedQuad = FindQuad();
                    e.Use();
                }
                else if (e.type == EventType.MouseDrag && e.button == 0)
                {
                    GridBlock block = hit.collider.GetComponent <GridBlock>();
                    if (block == null)
                    {
                        return;
                    }

                    _squareSel[1] = new FaceSelection(block, hit.normal);


                    _selectedQuad = FindQuad();
                    e.Use();
                }
            }
            else if (e.type == EventType.MouseDown && e.button == 0) // Click on nothing
            {
                Deselect();
                e.Use();
            }
        }
Exemple #17
0
 private void Reset()
 {
     Log($"---------- {MethodBase.GetCurrentMethod().Name} ----------");
     Select(false);
     Hover(false);
     _collisionTarget = null;
     _nextPoint       = null;
     _prevPositions.Clear();
     _tasked     = false;
     Moved       = false;
     Moving      = false;
     Attacked    = false;
     _movingBack = false;
     Target      = null;
     PlusActionText?.gameObject.SetActive(false);
     BoxCollider.size = ColliderSizeIdle;
     ResetLook();
     Log("----------------------------------------");
 }
    private Arrow SpawnArrow(int x, int z, Arrow.arrowType typeOfArrow)
    {
        GridBlock gb = GetGridBlock(x, z);

        if (gb.isOccupied || gb.hasItem)
        {
            return(null);
        }

        GameObject prefab;

        switch (typeOfArrow)
        {
        case Arrow.arrowType.Quadruple:
            prefab = arrows_prefabs[2];
            break;

        case Arrow.arrowType.Double:
            prefab = arrows_prefabs[1];
            break;

        case Arrow.arrowType.Single:
        default:
            prefab = arrows_prefabs[0];
            break;
        }
        GameObject arrowPrefab = Instantiate(prefab, getGridBlockPosition(x, z, 0.8f), Quaternion.identity) as GameObject;
        Arrow      a           = arrowPrefab.GetComponent <Arrow> ();

        a.grid_ref         = GetComponent <TheGrid> ();
        a.rhythmSystem_ref = rhythmSystem_ref;
        a.gridBlockOwner   = gb;
        a.arrow_type       = typeOfArrow;
        rhythmSystem_ref.getRhythmNoteToPoolEvent().AddListener(a.IncreaseCount);
        a.x = gb.X;
        a.y = gb.Y;
        a.z = gb.Z;

        gb.hasItem = true;
        itemList.Add(a);

        return(a);
    }
Exemple #19
0
    //public void CancelMove()
    //{
    //    Log($"---------- {MethodBase.GetCurrentMethod().Name} ----------");
    //    _animator.SetBool("Moving", false);
    //    _movePositions.Clear();
    //    transform.position = _originalPoint.Position;
    //    _nextPoint = null;
    //    _prevPositions.Clear();
    //    Moved = false;
    //    Moving = false;
    //    _bC.size = ColliderSizeIdle;
    //    ResetLook();
    //    Log("----------------------------------------");
    //}

    public bool CheckAttack(GridBlock target = null, bool ignoreDistance = false)
    {
        Log($"---------- {MethodBase.GetCurrentMethod().Name} ----------");
        if (Target == null && target == null && _collisionTarget == null)
        {
            Log("No target found");
            Log("----------------------------------------");
            return(false);
        }

        if (target != null)
        {
            Target  = target;
            _tasked = true;
        }

        UnitController tempTarget = null;

        if (_attackTarget != null)
        {
            tempTarget = _attackTarget;
        }
        else if (_collisionTarget != null && _collisionTarget.CurrentGridBlock != null)
        {
            tempTarget = _collisionTarget.CurrentGridBlock.CurrentUnit;
        }

        var checkDis = tempTarget != null ? tempTarget.Position : new Vector2(999, 999);
        var dis      = Position.GridDistance(checkDis);

        if (tempTarget != null && ((dis <= MaxAttackDistance && dis >= MinAttackDistance) || ignoreDistance))
        {
            Log("Target found");
            ReadyAttack(tempTarget.Position);
            Log("----------------------------------------");
            return(true);
        }

        Log("Target not the right distance to attack");
        Log("----------------------------------------");
        return(false);
    }
Exemple #20
0
    private void GetUnit(GridBlock gB)
    {
        if (CursorState == Enums.CursorState.Default)
        {
            UnitController tmpUnit = gB.CurrentUnit;

            if (tmpUnit != null && (tmpUnit.Player != Player || tmpUnit.OnCooldown || tmpUnit.Moving))
            {
                Log($"Current unit {tmpUnit.gameObject.name} is not applicable");
                tmpUnit = null;
            }
            else if (tmpUnit != null)
            {
                Log($"Current unit {tmpUnit.gameObject.name}");
                tmpUnit.Hover(true);
            }

            CurrentUnit = tmpUnit;
        }
    }
Exemple #21
0
    GridBlock CreateBlock(int x, int y, int size)
    {
        GridBlock b =         //Vertical
                      Instantiate(blockPrefab,
                                  transform.position + new Vector3(x * unitDist, -y * unitDist, 0),
                                  Quaternion.identity)
                      .GetComponentInChildren <GridBlock>();

        b.posX = x;
        b.posY = y;
        b.size = size;

        blocks.Add(b);

        b.transform.SetParent(blockParent);

        b.transform.localScale = new Vector3(unitDist, unitDist, unitDist);

        return(b);
    }
Exemple #22
0
    public IEnumerable <GridBlock> GetRangeSpaces(GridBlock start, int minDis, GridBlock target = null, List <OrderedGridBlock> gridDis = null)
    {
        bool org = false;

        if (gridDis == null)
        {
            gridDis = new List <OrderedGridBlock>();
            target  = this;
            org     = true;
        }

        var orderedNeighbors = target.Neighbors.OrderByDistance(start, minDis <= 1).ToList();
        var nonUsedNeighbors = orderedNeighbors.Except(gridDis.Select(g => g.GridBlock).ToList()).ToList();

        foreach (var n in nonUsedNeighbors)
        {
            var dis = n.Position.GridDistance(start.Position);
            gridDis.Add(new OrderedGridBlock(n, dis));
        }

        if (minDis > 1)
        {
            minDis--;
            foreach (GridBlock g in nonUsedNeighbors)
            {
                g.GetRangeSpaces(start, minDis, g, gridDis);
            }
        }

        if (org && gridDis != null && gridDis.Count > 0)
        {
            var orderedList = gridDis.OrderBy(g => g.OrderedValue).ToList();
            var lowestVal   = orderedList.FirstOrDefault().OrderedValue;
            var trimmedList = orderedList.Where(x => x.OrderedValue == lowestVal);
            return(trimmedList.Select(tL => tL.GridBlock));
        }
        else
        {
            return(null);
        }
    }
Exemple #23
0
    private void OnTriggerEnter2D(Collider2D collision)
    {
        Log($"---------- {MethodBase.GetCurrentMethod().Name} ----------");
        var            gO = collision.gameObject;
        GridBlock      gB = gO.GetComponent <GridBlock>();
        UnitController uC = gO.GetComponent <UnitController>();

        if (gB != null)
        {
            Log("Gridblock entered");
            if (gB.CurrentUnit != null && _movePositions.IsEmpty() && !gB.CurrentUnit.IsEnemy(Player))
            {
                Log("Destination block is occupied, find new block");
                FindGoodPreviousSpot();
            }

            if (CurrentGridBlock == null) // This only triggers at the beggining of the scene
            {
                gB.SetCurrentUnit(this);
            }

            CurrentGridBlock = gB;
        }
        else if (!OnCooldown && uC != null && uC.IsEnemy(Player)) // Collided with an enemy
        {
            Log("Collided with enemy unit");
            Blocked = true;
            var colDir = uC.Position - Position;
            var roundX = Utility.RoundAwayFromZero(colDir.x);
            var roundY = Utility.RoundAwayFromZero(colDir.y);

            if (roundX == _lookX && roundY == _lookY && Type != Enums.UnitType.Range) // If the unit is facing the unit that it collided with and the unit is not ranged.
            {
                //Target = uC.CurrentGridBlock;
                _collisionTarget = uC;
                DeleteSavedPath();
                ReadyAttack(collision.gameObject.transform.position);
            }
        }
        Log("----------------------------------------");
    }
    private void PlaceWorldObject(GridBlock block)
    {
        if (block == null || canceled)
        {
            return;
        }
        if (block.HasWorldObject || block.TileType == TileType.Wall)
        {
            return;
        }
        Instance.GridHighlighter.SetActive(false);
        Instance.CurrentlyPlacing.Value = false;
        Placer.ApplyPlacement(Player.Reference, block, Camera.Reference.ScreenPointToRay(MousePosition.Value).GetPosOnY());
        Placer.OnApplyPlacement.Trigger();
        Callback.Trigger(true);

        if (RemovePlacingOnPlace.Value)
        {
            Placer = null;
        }
    }
    public void OnGridBlockClick(GridBlock block)
    {
        if (Placer == null || block.TileType == TileType.Wall)
        {
            return;
        }

        if (!MapVal.Neighbours(Player.Reference.GridPosition.X, Player.Reference.GridPosition.Y).ContainsPos(block.Position))
        {
            if (!MovePlayerToClickPosAndPlace.Value)
            {
                return;
            }
            MovePlayerToClickPos(block);
            tempBlock = block;
        }
        else
        {
            PlaceWorldObject(block);
        }
    }
    // Score points for the player
    public void Score(Player p)
    {
        if (p == null || _GridBlockList == null)
        {
            return;
        }

        if (GetGridBlockList().Count == 0 || GetGridBlockList() == null)
        {
            print("gridBlockCount vazio ou null!");
        }

        int result = 0;

        //clear all blocks painted with the player's color
        foreach (GridBlock gb in GetGridBlockList())
        {
            if (gb.owner == null)
            {
                continue;
            }
            if (gb.owner.ID == p.ID)
            {
                gb.changeColor(GridBlock.gridBlockColor.White);
                gb.changeOwner(null);
                gb.isLocked = false;
                result++;
            }
        }

        result *= p.multiplier;

        Vector3 pos = p.transform.position;

        pos.y += p.GetComponent <Renderer> ().bounds.size.y + 0.0f;
        SpawnScoreFloatingText(pos, result.ToString(), GridBlock.getColorOfGridBlockColor(p.gridColor));
        p.score += result;

        p.multiplierCombo = 0;
    }
Exemple #27
0
    private void FindGoodPreviousSpot()
    {
        Log($"---------- {MethodBase.GetCurrentMethod().Name} ----------");
        _movePositions.Clear();

        foreach (var pos in _prevPositions)
        {
            _movePositions.Enqueue(pos);
            if (pos.CurrentUnit == null || pos.CurrentUnit == this)
            {
                break;
            }
        }

        _prevPositions.Clear();
        if (_nextPoint != null)
        {
            _prevPositions.Push(_nextPoint);
            _nextPoint = null;
        }
        Log("----------------------------------------");
    }
Exemple #28
0
        private void ClearLines(List <int> rows)
        {
            // top rws first (lowest y)
            rows.Sort();

            // for each line, check if all blocks are not white
            // if so, increase score and move all blocks from above down
            foreach (int i in rows)
            {
                bool clean             = true;
                System.Drawing.Color c = System.Drawing.Color.FromArgb(128, 255, 255, 255);
                for (int j = 0; j < 10; j++)
                {
                    GridBlock gb = this.grid[j, i];
                    clean &= gb.Color != c;
                }

                if (clean)
                {
                    // increase score
                    this.score += this.level;

                    for (int k = i; k > 0; k--)
                    {
                        // bring down each block
                        for (int x = 0; x < 10; x++)
                        {
                            this.grid[x, k].Color = this.grid[x, k - 1].Color;
                        }
                    }

                    for (int x = 0; x < 10; x++)
                    {
                        this.grid[x, 0].Color = c;
                    }
                }
            }
        }
    protected override IEnumerator AnimationCoroutine(GridBlock target)
    {
        if (launchedRailgunProjectile != null)
        {
            ParticleSystem ps       = gameObject.GetComponent <ParticleSystem>();
            Vector3        rotation = new Vector3(player.rotation.x, player.rotation.y, player.rotation.z);

            var shape = ps.shape;
            shape.rotation = rotation;
            ps.Play();

            // D = s * t
            Vector3 currentWorldLocation = launchedRailgunProjectile.transform.position;
            Vector3 targetWorldLocation  = new Vector3(target.location.x, target.location.y, 0.0f);

            float distance        = Vector3.Distance(currentWorldLocation, targetWorldLocation);
            float startTime       = Time.time;
            float percentTraveled = 0.0f;

            while (percentTraveled <= 1.0f)
            {
                float traveled = (Time.time - startTime) * railAnimateSpeed;
                percentTraveled = traveled / distance;  // Interpolator for Vector3.Lerp

                launchedRailgunProjectile.transform.position =
                    Vector3.Lerp
                    (
                        currentWorldLocation,
                        targetWorldLocation,
                        percentTraveled
                    );

                yield return(null);
            }

            Destroy(launchedRailgunProjectile);
        }
    }
Exemple #30
0
    private void DrawBlock(GridBlock block)
    {
        Vector2 size       = new Vector2(200, 100);
        Rect    windowRect = new Rect(lastClickPoint, size);

        GUILayout.Window(2, windowRect, (id) =>
        {
            string soilType = block.Data.soiltype.ToString();
            if (GUILayout.Button(soilType))
            {
                block.Data.CycleSoil();
            }

            // Tempetature
            GUIHelper.HorizontalGroup
            (
                () =>
            {
                GUILayout.Label("Temperature:");
                string temp = GUILayout.TextField(block.Data.Temperature.ToString(CultureInfo.InvariantCulture));
                float.TryParse(temp, out block.Data.Temperature);
            }
            );

            // Soil Depth
            GUIHelper.HorizontalGroup
            (
                () =>
            {
                GUILayout.Label("Soil Depth:");
                block.Data.depth = GUILayout.HorizontalSlider(block.Data.depth, 0, 10);
            }
            );
        },
                         block.GetPrettyCoords()
                         );
    }
Exemple #31
0
    override protected IEnumerator AnimationCoroutine(GridBlock targetBlock)
    {
        ParticleSystem ps = GetComponent <ParticleSystem>();

        foreach (GameObject target in targetBlock.objectsOnBlock)
        {
            Hazard hazardTest = target.GetComponent <Hazard>();
            if (hazardTest != null)
            {
                var trigger = ps.trigger;
                trigger.enabled = true;

                trigger.SetCollider(0, target.GetComponent <Collider>());
                trigger.radiusScale = 0.5f;

                ps.Play();
                yield return(new WaitForSeconds(2.0f));

                ps.Stop();

                break;
            }
        }
    }
Exemple #32
0
        // Move along Path
        void FollowPath()
        {
            if (path.Count > 0)
            {
                GridBlock block = path.First().block;
                float distance = Vector3.Distance(transform.position, block.position);
                if (distance <= distanceTolerance)
                {
                    entity.SetBlock(block);
                    finalPath.RemoveAt(0);
                    nodePath.RemoveAt(0);
                    StopMove();
                }
                else
                {
                    MoveTo(block.position);
                }

                if (path.Count <= 0)
                {
                    MoveTo(transform.position);
                }
            }
        }
	//TODO work on unit overlap
	/// <summary>
	/// Display unit's projected movement through this block.
	/// </summary>
	/// <param name="cameFrom">Block this unit is coming from.</param>
	/// <param name="isGoingTo">Block this unit is going to.</param>
	///<returns> A refrence to the spriteControlers for moveArmIn (0) and moveArmOut (1)
	/// when the action is preformed set there color to Color.Clear</returns>
	public SpriteControler[] displayMoveOnQueue(GridBlock cameFrom, GridBlock isGoingTo){

		SpriteControler moveArmIn = null;
		SpriteControler moveArmOut = null;

		for(int i = 0; i < 4; i++){
			if(isGoingTo.getAdj(i) == cameFrom){
				moveArmOut = cameFrom.spriteDisplayScript.movementDirections[i];
				// Faster than mod 4.
				i += 2;
				if(i > 3){
					i -= 4;
				}
				moveArmIn = isGoingTo.spriteDisplayScript.movementDirections[i];
				break;
			}
		}
		//TODO Make move arm in add out visible using color.
		if(moveArmIn == null || moveArmOut == null){
			Debug.LogError("cameFrom and isGoingTo were not adjacent!\n" +
			"null was returned to the action");
			return null;
		}
		moveArmIn.setColor(Color.white);
		moveArmOut.setColor(Color.white);

		SpriteControler[] sc = { moveArmIn, moveArmOut };

		return sc;
	}
	public void setAdj(Direction dir, GridBlock block){
		switch(dir){
		case Direction.UP:
			up = block;
			break;
		case Direction.DOWN:
			down = block;
			break;
		case Direction.LEFT:
			left = block;
			break;
		default:
			right = block;
			break;
		}
	}
	/// <summary>
	/// Sets the posible attack locations.
	/// Valid locations will be flound within this script
	/// </summary>
	/// <param name="attackLocations">Attack locations.</param>
	public void setPossibleAttackLocations(GridBlock[] attackLocations){
		possibleAttackLocations = attackLocations;
	}
	public override void loadAction(SerializedCompletedAction s){
		attackStrength = s.actionAmountInt;
		attackLocation = unit.grid.gridLocationToGameGrid(s.locationToPerformAction);
	}
	/// <summary>
	/// Sets the attack location.
	/// </summary>
	/// <param name="attackLocation">Attack location.</param>
	private void setAttackLocation(GridBlock attackLocation){
		this.attackLocation = attackLocation;
	}
	/// <summary>
	/// This is called when a user has selected their action location.
	/// </summary>
	/// <param name="blockSelected">Block selected.</param>
	public abstract void userSelectedAction(GridBlock blockSelected);
	private void displayCloseRangeAttackAnimation(GridBlock animationLocation){
		GameObject closeAttack = unit.instantiationHelper(AnimationHolder.Instance.getAnimationFromName("close attack"));
		actionTime = closeAttack.GetComponent<IGetAnimationTimeToFin>().getAnimationTime();
		closeAttack.transform.SetParent(animationLocation.transform, false);
		closeAttack.transform.localPosition = new Vector3();
		closeAttack.transform.position = closeAttack.transform.position + new Vector3(0f, 1f, 0f);
	}
	/// <summary>
	/// Called when the grid block creates the unit.
	/// </summary>
	/// <param name="startLocation">Start location.</param>
	public virtual void spawnUnit(CreatePlayGrid gm, GridBlock startLocation, Team t){
		grid = gm;
		blockList = new LinkedList<GridBlock>();
		//set base unit stats so they can be adjusted at runtime
		maxProgramLength = unitInfo.maxLength;
		maximumMovment = unitInfo.maxMove;
		movmentActionsRemaning = maximumMovment;
		currentMaxPosibleAttackActions = unitInfo.maxAttackActions;
		currentAttacksRemaning = currentMaxPosibleAttackActions;
		currentAttackPower = unitInfo.attackPow;
		team = t;
		team.addAlly(this);
		team.addSpawn();

		blockList.AddLast(startLocation);
		float spawnTime = spawnAnimation();
		Invoke("checkAllDisplay", spawnTime);
		timerStartup();
		Invoke("startTimerTick", spawnTime);
	}
	/// <summary>
	/// Resets the action queue and the maximum alowed move and attack actions.
	/// </summary>
	public void resetActionQueue(bool overRideIsActing){
		if(!overRideIsActing && isActing)
			return;
		foreach( ActionScript actions in actionList ){
			actions.removeActionRepresentationDisplay();
		}
		actionList.Clear();
		virtualBlockHead = null;
		resetAttackActionsToCurrentMax();
		resetMovmentActionsToCurrentMax();
	}
	/// <summary>
	/// Displaythe unit movement animation.
	/// </summary>
	/// <returns>The unit movement animation time.</returns>
	/// <param name="location">Location the unit is moving to.</param>
	public float displayUnitMovementAnimation(GridBlock locationStart, GridBlock locationEnd){
		UnitMoveAnimatior moveAnimation = Instantiate(AnimationHolder.Instance.getAnimationFromName("unit move")).GetComponent<UnitMoveAnimatior>();
		moveAnimation.transform.SetParent(locationStart.transform, false);
		moveAnimation.setParticalColor(getUnitColor());
		moveAnimation.setMovmentDirection(locationStart, locationStart.blockAdjDirection(locationEnd));
		moveAnimation.transform.SetParent(null);
		Invoke("checkAllDisplay", moveAnimation.getAnimationTime());
		return moveAnimation.getAnimationTime();
	}
	public GridBlock[] getAttackLocations(){
		GridBlock[] x = new GridBlock[attackLocations.Length];

		for(int i = 0; i < attackLocations.Length; i++){

			//Make sure virtual head block exists.
			if(getVirtualBlockHeadLocation() != null)
				x[i] = grid.gridLocationToGameGrid(getVirtualBlockHeadLocation().gridLocation + attackLocations[i]);
		}

		return x;
	}
	/// <summary>
	/// Move the unit's head by adding a unit block to the given new location. Will remove the last block if the unit is already at its max length.
	/// </summary>
	/// <returns>Success of unit's move action.</returns>
	/// <param name="newLocation">The block to move unit head to.</param>
	public bool addBlock(GridBlock newLocation, bool animate){
		GridBlock oldLocation = getCurrentBlockHeadLocation();
		bool movedSuccess;
		//check if grid space is already occupied
		if(newLocation.unitInstalled == null){
			//check if unit is already at its max length
			if(getLength() >= MaxProgramLength){
				//remove a block from the end
				removeBlock();
			}
			//add a new unit block to given location
			blockList.AddFirst(newLocation);
			newLocation.unitInstalled = this;
			movedSuccess = true;
		} else{
			movedSuccess = false;
		}
		if(animate && movedSuccess){
			//TODO unitMoving animation
			float animationTime = displayUnitMovementAnimation(oldLocation, newLocation);
			Invoke("checkAllDisplay", animationTime);
		} else{
			checkAllDisplay();
		}

		return movedSuccess;
	}
	/// <summary>
	/// This is called when a user has selected their actions location.
	/// This tells other blocks to stop waiting for input
	/// </summary>
	/// <param name="blockSelected">Block selected.</param>
	public override void userSelectedAction(GridBlock blockSelected){
		for(int i = 0; i < adjBlocks.Length; i++){
			if(adjBlocks[i] == blockSelected){
				locationToPreformAction = adjBlocks[i];
			}
		}
		removeUserSelectionDisplay();
		displayFinishedAction();
		unit.virtualBlockHead = locationToPreformAction;
		unit.addActionToQueue(this);
		unit.moveActionAdded();
	}
Exemple #46
0
		public MoveTree(GridBlock startGB, int depth) {
			finalPositions = new LinkedList<Position>();
			this.start = new Position(startGB, depth, null, finalPositions);
		}
Exemple #47
0
 public Selection(GridBlock block, Vector3 normal)
 {
     Block = block;
     face  = new Face(block.GetComponent <MeshFilter>().sharedMesh, normal);
 }
Exemple #48
0
		/// <summary>
		/// Initializes a new position.
		/// </summary>
		/// <param name="gridBlock">Grid block of position.</param>
		/// <param name="depth">Remaining depth to traverse.</param>
		/// <param name="prevPos">Previous position in traversal.</param>
		/// <param name="finalPositions">The final positions list of the move tree.</param>
		public Position(GridBlock gridBlock, int depth, Position prevPos, LinkedList<Position> finalPositions) {
			this.gridBlock = gridBlock;
			//Decrease the number of remaining moves.
			depth--;
			adjPos = new Position[4];
			//Only get adjacent positions if more moves remain.
		if(depth > 0 && gridBlock != null) {
				//For each adjacent gridblock.
				for(int i = 0; i < 4; i++) {
					//Get the adjacent gridblock, if it exists.
					GridBlock adjGridBlock = gridBlock.getAdj(i);
					//Check if the adjacent gridblock exists, and if it can be occupied.
					if(adjGridBlock != null && adjGridBlock.unitInstalled == false)
						//Set the adjacent gridblock as a space that can be moved to.
						adjPos[i] = new Position(adjGridBlock, depth, this, finalPositions);
				}
			} else {
				//If no more moves remain, add to final positions.
				finalPositions.AddLast(this);
			}
		}
Exemple #49
0
 public void Init(GridBlock grid)
 {
     GridBlock = grid;
 }
	/// <summary>
	/// called by the unit when it moves
	/// </summary>
	/// <param name="">.</param>
	public void setMovmentDirection(GridBlock currentGridBlockTmp, Direction movmentDirection){
		currentGridBlock = currentGridBlockTmp;
		gridBlockMovingTo = currentGridBlockTmp.getAdj(movmentDirection);
		switch(movmentDirection){
		case Direction.UP:
			transform.Translate(0, 0, 0.7f);
			break;
		case Direction.DOWN:
			transform.Translate(0, 0, -0.7f);
			break;
		case Direction.LEFT:
			transform.Translate(-0.7f, 0, 0);
			break;
		case Direction.RIGHT:
			transform.Translate(0.7f, 0, 0);
			break;
		default:
			break;
		}
		directionMoving = movmentDirection;
	}
Exemple #51
0
 public void ExecuteAttackAnimation(GridBlock gridBlock)
 {
     weaponInventory[indexSelectedWeapon].StartAnimationCoroutine(gridBlock);
 }
	public override void loadAction(SerializedCompletedAction s){
		locationToPreformAction = unit.grid.gridLocationToGameGrid(s.locationToPerformAction);
	}
Exemple #53
0
    void Update()
    {
        if (CooldownTimer <= 0)
        {
            if (PlusAction > 0)
            {
                PlusAction          -= Time.deltaTime;
                PlusActionText.alpha = PlusAction / PLUSACTIONTIME;
            }
            else if (PlusAction <= 0 && _unitState == Enums.UnitState.PlusAction && !_selected)
            {
                _unitState = Enums.UnitState.Idle;
            }

            //if (_unitState == Enums.UnitState.Idle && CurrentGridBlock != null && CurrentGridBlock.CurrentUnit != this) // This is a redundency in case the gridblock is out of sync with the current unit
            //    CurrentGridBlock.CurrentUnit = this;

            if ((_nextPoint != null || _movePositions.Count > 0) && _unitState != Enums.UnitState.Attacking && _unitState != Enums.UnitState.Hurt)
            {
                if (_nextPoint == null)
                {
                    GetNextPoint();
                }

                Vector2 moveVector = Vector2.MoveTowards(transform.position, _nextPoint.Position, Speed * Time.deltaTime);
                _minimapIcon.rectTransform.anchoredPosition = Utility.UITilePosition(_minimapIcon.rectTransform, transform);

                transform.position = moveVector;
                if (transform.position.V2() == _nextPoint.Position)
                {
                    Log("Arrived at point");
                    _prevPositions.FirstOrDefault()?.Path_Delete(this);
                    _prevPositions.Push(_nextPoint);

                    if (CurrentGridBlock.CurrentUnit == null && _attackWhenInRange && _attackTarget != null && Position.GridDistance(_attackTarget.Position) <= MaxAttackDistance && CurrentGridBlock?.CurrentUnit == this)
                    {
                        DeleteSavedPath();
                        _nextPoint = null;
                    }
                    else if (!_movePositions.IsEmpty())
                    {
                        Log("Get next point");
                        GetNextPoint();
                    }
                    else
                    {
                        if (CurrentGridBlock != _nextPoint) // Arrived at the last point, make sure it's the currentgridblock
                        {
                            CurrentGridBlock = _nextPoint;
                        }
                        Log("Last move");
                        _nextPoint = null;
                    }

                    if (_movePositions.IsEmpty() && _nextPoint == null)
                    {
                        if (CurrentGridBlock.CurrentUnit == null)
                        {
                            Log($"Ends move");
                            Moving = false;
                            Moved  = true;

                            CurrentGridBlock.SetCurrentUnit(this);
                            _unitState = Enums.UnitState.Idle;
                        }
                        else
                        {
                            FindGoodPreviousSpot();
                        }
                    }
                }
            }

            if (!_attack && Target != null && _movePositions.IsEmpty() && _nextPoint == null)
            {
                Log($"checks for attack");
                CheckAttack();
            }

            if (!_selected && !Moving && _animator.GetBool("Moving"))
            {
                _animator.SetBool("Moving", false);
            }

            if (_attack && !_animator.GetCurrentAnimatorStateInfo(0).IsName("Launch") && !Attacked)
            {
                Log($"attacks");
                Attack();
            }

            if (_nextPoint == null && _unitState == Enums.UnitState.Idle && _tasked && !Moving && !_attack && (Moved || Attacked))
            {
                Log($"goes on cooldown");
                if (!Utility.TrueNull(CurrentGridBlock.CurrentUnit) && CurrentGridBlock.CurrentUnit != this)
                {
                    FindGoodPreviousSpot();
                }
                else
                {
                    GoOnCooldown();
                }
            }
        }

        if (CooldownTimer > 0)
        {
            CooldownTimer -= Time.deltaTime;
            if (CooldownTimer <= 0)
            {
                Log($"Come of cooldown");
                if (Type == Enums.UnitType.Melee)
                {
                    CooldownReduction?.gameObject.SetActive(false);
                }

                if (UnitManager?.AvailableUnits <= 0)
                {
                    _cC?.SetPosition(transform.position);
                }

                _animator.SetBool("Cooldown", OnCooldown = false);
                _minimapIcon.color = Player == Enums.Player.Player1 ? Colors.Player_Idle : Colors.Enemy_Idle;

                if (OffCooldownObject != null)
                {
                    Log("Create cooldown object");
                    Instantiate(OffCooldownObject, transform.position, Quaternion.identity);
                }

                if (Player != Enums.Player.Player1) // This is for non player units to make sure all units are looped through
                {
                    UnitManager?.AddUnit(this);
                }

                _unitState = Enums.UnitState.Idle;
            }
        }

        if (Player != Enums.Player.Player1 && _nextPoint == null && _unitState == Enums.UnitState.Idle && !OnCooldown && !Moving && !Moved && !Attacked)
        {
            if (!UnitManager.PlayerInfo.Units.Contains(this))
            {
                Log($"added to unit list");
                UnitManager.AddUnit(this);
            }
        }
    }
	public void enableOnGridBlock(GridBlock gb){
		gameObject.SetActive(true);
		currentGridblock = gb;
	}
	public override void userSelectedAction(GridBlock blockSelected){
		//Remove the selection display.
		removeUserSelectionDisplay();
		//Set attack location.
		attackLocation = blockSelected;
		//Display the finished action.
		displayFinishedAction();
		//Add the action to the queue.
		unit.addActionToQueue(this);
		//The unit can no longer attack.
		unit.useAttackAction();
	}
	// All sprite layers are created on load to minimize the impact of changing sprites
	/// <summary>Start this instance.</summary>
	void Start(){ 
		spriteInfo = GetComponentInParent<CreatePlayGrid>();
		attachedGridBlock = GetComponent<GridBlock>();

		//Initialize unit sprite.
		unitSprite = Instantiate(spriteInfo.spritePrefab).GetComponent<SpriteControler>();
		unitSprite.transform.SetParent(transform);
		unitSprite.transform.localPosition = new Vector3(0, 0, 0.1f);
		unitSprite.name = "Unit Sprite";

		//Initialize unit head sprite.
		headSprite = Instantiate(spriteInfo.spritePrefab).GetComponent<SpriteControler>();
		headSprite.transform.SetParent(transform);
		headSprite.transform.localPosition = new Vector3(0, 0, 0.2f);
		headSprite.name = "Head Sprite";

		//Initialize action sprites and use state.
		actionSprites = new SpriteControler[MAX_ACTIONS_ON_THIS_BLOCK];
		actionUsed = new bool[MAX_ACTIONS_ON_THIS_BLOCK];
		for(int x = 0; x < MAX_ACTIONS_ON_THIS_BLOCK; x++){
			actionSprites[x] = Instantiate(spriteInfo.spritePrefab).GetComponent<SpriteControler>();
			actionSprites[x].transform.SetParent(transform);
			actionSprites[x].transform.localPosition = new Vector3(0, 0, 0.3f + x * 0.05f);
			actionSprites[x].name = "Action Sprite " + x;
		}

		//Initialize movement directions.
		movementDirections = new SpriteControler[4];
		string[] directionNames = { "up", "right", "down", "left" };
		for(int x = 0; x < 4; x++){
			movementDirections[x] = Instantiate(spriteInfo.spritePrefab).GetComponent<SpriteControler>();
			movementDirections[x].transform.SetParent(transform);
			movementDirections[x].transform.localPosition = new Vector3(0, 0, 2.5f);

			//Rotating each movement arm.
			Quaternion rot = movementDirections[x].transform.localRotation;
			rot.eulerAngles = new Vector3(0.0f, 0.0f, 90.0f * x); //UNDONE check to see if rotation is correct
			movementDirections[x].transform.localRotation = rot;

			movementDirections[x].name = "Movment Direction " + directionNames[x];
			// Sprites for this controller are always the same.
			movementDirections[x].setSprite(spriteInfo.spritesAndColors.sprite_moveLine);
			//The color for this sprite is Alpha only.
			movementDirections[x].setColor(Color.clear);
		}

		//Initialize movement circle.
		movementCircle = Instantiate(spriteInfo.spritePrefab).GetComponent<SpriteControler>();
		movementCircle.transform.SetParent(transform);
		movementCircle.transform.localPosition = new Vector3(0, 0, 2.5f);
		movementCircle.name = "Movement Circle";

		//Initialize right connection.
		rightConnection = Instantiate(spriteInfo.spritePrefab).GetComponent<SpriteControler>();
		rightConnection.transform.SetParent(transform);
		rightConnection.transform.localPosition = new Vector3(conectionLocation, 0, 0.1f);
		rightConnection.name = "Right Conection";

		//Initialize above connection.
		aboveConnection = Instantiate(spriteInfo.spritePrefab).GetComponent<SpriteControler>();
		aboveConnection.transform.SetParent(transform);
		aboveConnection.transform.localPosition = new Vector3(0, -conectionLocation, 0.1f);
		aboveConnection.transform.Rotate(0f, 0f, 90f);
		aboveConnection.name = "Above Conection";

		//Initialize move sprite.
		moveSprite = Instantiate(spriteInfo.spritePrefab).GetComponent<SpriteControler>();
		moveSprite.transform.SetParent(transform);
		moveSprite.transform.localPosition = new Vector3(0, 0, 0.2f);
		moveSprite.name = "Move Sprite";

	}
	public Direction blockAdjDirection(GridBlock block){
		if(block == up){
			return Direction.UP;
		} else if(block == down){
			return Direction.DOWN;
		} else if(block == left){
			return Direction.LEFT;
		} else if(block == right){
			return Direction.RIGHT;
		} else{
			return Direction.UP;
		} 
	}
	//TODO long range attack animation not done
	private float displayLongRangeAttackAnimation(GridBlock animationLocation){
		GameObject farAttackOut = unit.instantiationHelper(AnimationHolder.Instance.getAnimationFromName("far attack out")); // diplayed on the units block
		GameObject farAttackIn = unit.instantiationHelper(AnimationHolder.Instance.getAnimationFromName("far attack in")); // diplayed on the animationLocation
		float delay = farAttackOut.GetComponent<IGetAnimationTimeToFin>().getAnimationTime();
		actionTime = farAttackIn.GetComponent<IGetAnimationTimeToFin>().getAnimationTime();
		farAttackOut.transform.SetParent(unit.getCurrentBlockHeadLocation().transform, false);
		farAttackOut.transform.localPosition = new Vector3();
		farAttackOut.transform.position = farAttackOut.transform.position + new Vector3(0f, 1f, 0f);

		farAttackIn.transform.SetParent(animationLocation.transform, false);
		farAttackIn.transform.localPosition = new Vector3();
		farAttackIn.transform.position = farAttackOut.transform.position + new Vector3(0f, 1f, 0f);

		return delay;
	}