Example #1
0
        /// <summary>
        /// Moves the selected unit to the clicked location, assuming the location
        /// is within range of the unit.
        /// </summary>
        /// <param name="level"> The level. </param>
        private void MoveUnit(Level level)
        {
            if (InputHandler.LeftMouseClicked()
                && this.unitSelected
                && !this.justClicked)
            {
                // Note! MouseState.X is the horizontal position and MouseState.Y is the vertical position.
                // I want Y to be the horizontal coordinate (the width) and X to be the vertical coordinate
                // (the height), so tileY is using the X values and tileX is using the Y values.
                var tileY = (int)(InputHandler.MouseState.X + level.Camera.Position.X) / Engine.TileHeight;
                var tileX = (int)(InputHandler.MouseState.Y + level.Camera.Position.Y) / Engine.TileWidth;

                var tempVector = new Vector(tileX, tileY);

                // Checks if the chosen tile is occupied or not.
                if (!level.LevelMap.IsOccupied(tileX, tileY)
                    && this.selectedUnit.CanTraverse(level.LevelMap.GetCollisionType(tileX, tileY))
                    && this.selectedUnit.PointWithinMoveRange(tempVector))
                {
                    var pathToTarget = level.LevelMap.FindShortestPathWithinReach(this.selectedUnit, tempVector).Count;
                    if (pathToTarget != 0 && pathToTarget <= this.selectedUnit.MoveRange)
                    {
                        // Removes the unit from the list, as we need to change the
                        // position of the unit.
                        this.PlayerUnits.Remove(this.selectedUnit);

                        // Notifies the map that the unit is disappearing from its current
                        // location.
                        level.LevelMap.MoveUnitAway(this.selectedUnit, level);

                        // Changes the unit's location.
                        this.selectedUnit.Location = (Vector)tempVector.Clone();
                        this.selectedUnit.MoveUnit();

                        // Notifies the map that the unit has arrived at its target
                        // location and adds the unit to the unit list again.
                        level.LevelMap.MoveUnitToNewPosition(this.selectedUnit);
                        this.PlayerUnits.Add(this.selectedUnit);

                        this.unitSelected = false;
                        this.selectedUnit = null;
                    }
                }

                // Ensures that other parts in the update method won't be triggered.
                this.justClicked = true;
            }
        }