예제 #1
0
        /// <summary>
        /// Method called every frame
        /// </summary>
        /// <param name="input">Input</param>
        /// <param name="gameTime">GameTime</param>
        public override void Update(Input input, GameTime gameTime)
        {
            if (creditsMode)
            {
                //One time changes
                if (MonoGearGame.FindEntitiesOfType <GameUI>()[0].Enabled)
                {
                    // Disable UI, spawn credits and set other things
                    MonoGearGame.FindEntitiesOfType <GameUI>()[0].Enabled = false;
                    MonoGearGame.FindEntitiesOfType <GameUI>()[0].Visible = false;

                    MonoGearGame.SpawnLevelEntity(new Credits());

                    instanceTexture = playerSprite;
                    Health          = 1;
                }

                // Move right on the screen
                Position        += Speed * new Vector2(1, 0) * (float)gameTime.ElapsedGameTime.TotalSeconds;
                Rotation         = MathHelper.ToRadians(90);
                forwardSpeed     = Speed;
                jeepSound.Volume = 0;
                // Required for tank range detection
                player.Position = Position;

                // Camera tracking
                if (Position.X < 28000)
                {
                    Camera.main.Position = Position;
                }

                return;
            }

            // Handles driving and input
            base.Update(input, gameTime);

            // Speed based volume
            float minVolume = 0.75f;

            if (Entered)
            {
                if (instanceTexture != playerSprite)
                {
                    instanceTexture = playerSprite;
                }
                jeepSound.Volume = minVolume + (1.0f - minVolume) * Math.Abs(forwardSpeed) / Speed;
            }
            else
            {
                if (instanceTexture != jeepSprite)
                {
                    instanceTexture = jeepSprite;
                }
                jeepSound.Volume = minVolume;
            }

            jeepSound.Position = Position;
        }
예제 #2
0
        /// <summary>
        /// Method that executes when the level is loaded.
        /// </summary>
        public override void OnLevelLoaded()
        {
            base.OnLevelLoaded();

            player = MonoGearGame.FindEntitiesWithTag("Player")[0] as Player;

            //Reset the objectives list and sort in on index
            objectives.Clear();
            objectives.AddRange(MonoGearGame.FindEntitiesOfType <Objective>());
            objectives.Sort((a, b) => a.Index.CompareTo(b.Index));
        }
예제 #3
0
 /// <summary>
 /// Method used to disable the gameover screen
 /// </summary>
 public void DisableGameOver()
 {
     // Find the player
     player         = MonoGearGame.FindEntitiesWithTag("Player")[0] as Player;
     gameOver       = false;
     Visible        = false;
     player.Enabled = true;
     player.Visible = true;
     MonoGearGame.FindEntitiesOfType <GameUI>()[0].Enabled = true;
     MonoGearGame.FindEntitiesOfType <GameUI>()[0].Visible = true;
 }
예제 #4
0
파일: Tank.cs 프로젝트: bramkelder/MonoGear
        /// <summary>
        /// Fires tank main gun by spaning a missile
        /// </summary>
        public void FireCannon()
        {
            var missile = new Missile(MonoGearGame.FindEntitiesOfType <Player>()[0].Collider);

            missile.Rotation = Rotation;

            missile.Position = Position + Forward * 88;

            MonoGearGame.SpawnLevelEntity(missile);

            var sound = MonoGearGame.GetResource <SoundEffect>("Audio/AudioFX/Tank_shot").CreateInstance();

            sound.Volume = 0.5f * SettingsPage.Volume * SettingsPage.EffectVolume;
            sound.Play();
        }
예제 #5
0
        /// <summary>
        /// Method that updates the game
        /// </summary>
        /// <param name="input">Input</param>
        /// <param name="gameTime">GameTime</param>
        public override void Update(Input input, GameTime gameTime)
        {
            base.Update(input, gameTime);

            Collider collider;
            var      pos   = Position;
            var      delta = Forward * Speed * (float)gameTime.ElapsedGameTime.TotalSeconds;

            Move(delta);

            bool hitTilemap;

            // Check if the bullet collides with anything
            if (Collider.CollidesAny(out collider, out hitTilemap, originCollider))
            {
                Position = pos;
                // Set the speed to 0
                Speed = 0.0f;

                // Check if the bullet collides with a player
                if (!hitTilemap && collider.Entity.Tag == "Player")
                {
                    var player = collider.Entity as Player;
                    // Decrease the player's health by 1
                    player.Health -= 1.0f;
                }

                // Find everything that can be destroyed
                var things = MonoGearGame.FindEntitiesOfType <IDestroyable>();
                foreach (var thing in things)
                {
                    // Damage the thing if it gets hit
                    var dis = thing as WorldEntity;
                    if (!hitTilemap && collider.Entity == dis)
                    {
                        thing.Damage(maxDamage);
                    }
                }

                // Destroy if we hit something
                MonoGearGame.DestroyEntity(this);
            }
        }
예제 #6
0
파일: Rock.cs 프로젝트: bramkelder/MonoGear
        /// <summary>
        /// Method that updates the game
        /// </summary>
        /// <param name="input">Input</param>
        /// <param name="gameTime">GameTime</param>
        public override void Update(Input input, GameTime gameTime)
        {
            base.Update(input, gameTime);

            Collider collider;
            var      pos   = Position;
            var      delta = Forward * Speed * (float)gameTime.ElapsedGameTime.TotalSeconds;

            Move(delta);

            bool hitTilemap;

            // Check if the rock collides with anything
            if (Collider.CollidesAny(out collider, out hitTilemap, originCollider))
            {
                Position = pos;
                Speed    = 0.0f;

                var entities = MonoGearGame.FindEntitiesOfType <Guard>();

                // Loop through all guards
                foreach (var guard in entities)
                {
                    // Check if the guard is in range
                    if (Vector2.Distance(Position, guard.Position) < 150)
                    {
                        guard.Interest(Position);
                    }
                }

                Enabled = false;
            }

            if (Speed > 0)
            {
                Speed -= 3;
            }
            else
            {
                Speed = 0;
            }
        }
예제 #7
0
        /// <summary>
        /// Method that updates the game
        /// </summary>
        /// <param name="input">Input</param>
        /// <param name="gameTime">GameTime</param>
        public override void Update(Input input, GameTime gameTime)
        {
            base.Update(input, gameTime);


            // Check if the animation is at its first frame
            if (AnimationCurrentFrame == 1 && !exploded)
            {
                if (player.Enabled)
                {
                    // Calcutate damage based on distance from the explotion
                    var dis = Vector2.Distance(player.Position, Position);
                    if (dis < blastRadius)
                    {
                        player.Health -= maxDamage * (dis / blastRadius);
                    }
                }

                // Find everything that can be destroyed
                var things = MonoGearGame.FindEntitiesOfType <IDestroyable>();
                foreach (var thing in things)
                {
                    // Calcutate damage based on distance from the explotion
                    var dis = Vector2.Distance((thing as WorldEntity).Position, Position);
                    if (dis < blastRadius)
                    {
                        thing.Damage(maxDamage * (dis / blastRadius));
                    }
                }

                // Note that we have exploded
                exploded = true;
            }
            // Destoy the explotion after its done with the animation
            else if (AnimationCurrentFrame == 14)
            {
                MonoGearGame.DestroyEntity(this);
            }
        }
예제 #8
0
        /// <summary>
        /// Loads a level from filename.
        /// </summary>
        /// <param name="resource">The level file name</param>
        /// <returns>Level</returns>
        public static Level LoadLevel(string resource)
        {
            var level = new Level();

            // Run in task because TmxMap needs IO and we can only do that in tasks
            Task.Run(() =>
            {
                // Load data
                var map      = new TmxMap(Path.Combine("Content/Levels", resource + ".tmx"));
                level.Name   = resource;
                level.Width  = map.Width;
                level.Height = map.Height;

                // Get tileset data
                var tileset      = map.Tilesets[0];
                level.TileHeight = tileset.TileHeight;
                level.TileWidth  = tileset.TileWidth;

                // Build dictionary with tile indexes and tile objects
                var tilesetDict = new Dictionary <int, Tile>();
                tilesetDict.Add(0, null);                       // 0 means no tile

                // Load texture
                var tilesetTexture = MonoGearGame.GetResource <Texture2D>(Path.Combine("Levels\\Tilesets", Path.GetFileNameWithoutExtension(tileset.Image.Source)));

                // Create tile objects from tileset data and texture
                int rows  = (int)tileset.TileCount / (int)tileset.Columns;
                bool done = false;
                for (int x = 0; x < tileset.Columns && !done; x++)
                {
                    for (int y = 0; y < rows; y++)
                    {
                        // Check if we are finished with the tiles
                        if (x + y * tileset.Columns > tileset.TileCount)
                        {
                            done = true;
                            break;
                        }

                        // Create new tile
                        Tile tile               = new Tile(tilesetTexture);
                        tile.textureRect.X      = x * tileset.TileWidth;
                        tile.textureRect.Y      = y * tileset.TileHeight;
                        tile.textureRect.Width  = tileset.TileWidth;
                        tile.textureRect.Height = tileset.TileHeight;

                        // Tile index stored for debugging
                        int index      = x + y * (int)tileset.Columns;
                        tile.tilesetId = index;

                        // Load custom tile properties
                        TmxTilesetTile tileData;
                        if (tileset.Tiles.TryGetValue(index, out tileData))
                        {
                            Debug.WriteLine("Loading custom properties for tile " + index);

                            // Load solid
                            string solid;
                            if (tileData.Properties.TryGetValue("solid", out solid))
                            {
                                if (solid == "true")
                                {
                                    tile.Walkable = false;
                                }
                                else
                                {
                                    Debug.WriteLine("Tile is not solid but has the property?");
                                }
                            }

                            // Tile walk sound
                            string sound;
                            if (tileData.Properties.TryGetValue("sound", out sound))
                            {
                                Tile.TileSound soundEnum;
                                if (Enum.TryParse(sound, out soundEnum))
                                {
                                    tile.Sound = soundEnum;
                                }
                                else
                                {
                                    Debug.WriteLine("Unknown TileSound value " + sound);
                                }
                            }
                        }

                        // Add tile to dictionary for later use
                        tilesetDict.Add(tileset.FirstGid + index, tile);
                    }
                }

                // Create combined layer tiles
                level.combinedLayer.tiles = new Tile[map.Width * map.Height];

                // Layers get stored bottom to top, we need top to bottom
                var reversedLayers = map.Layers.Reverse();
                foreach (var layer in reversedLayers)
                {
                    Debug.WriteLine("Loading layer: " + layer.Name);

                    // Add layer
                    var levelLayer   = new LevelLayer();
                    levelLayer.tiles = new Tile[map.Width * map.Height];

                    for (int tileIndex = 0; tileIndex < map.Width * map.Height; tileIndex++)
                    {
                        levelLayer.tiles[tileIndex] = tilesetDict[layer.Tiles[tileIndex].Gid];

                        // Update top layer if:
                        // level layer has a tile AND
                        // top layer is walkable but level is not OR
                        // top layer has no tile
                        if (levelLayer.tiles[tileIndex] != null &&
                            (level.combinedLayer.tiles[tileIndex] == null ||
                             (level.combinedLayer.tiles[tileIndex].Walkable && levelLayer.tiles[tileIndex].Walkable == false)))
                        {
                            level.combinedLayer.tiles[tileIndex] = levelLayer.tiles[tileIndex];
                        }
                    }

                    // Add layer to level
                    level.tileLayers.Add(levelLayer);
                }

                level.tileLayers.Reverse();             // Sort them bottom to top again

                // Load objects
                var groups = map.ObjectGroups;

                // Dictionaries used to link entities together by name
                var guardPaths      = new Dictionary <Guard, string>();
                var carPaths        = new Dictionary <Car, string>();
                var paths           = new Dictionary <string, List <Vector2> >();
                var consoles        = new Dictionary <string, PC>();
                var cameraConsole   = new Dictionary <CCTV, string>();
                var objectives      = new Dictionary <string, Objective>(); // Remains during gameplay due to some triggers needing it
                var pcWithObjective = new Dictionary <PC, string>();
                var driveObjective  = new Dictionary <DrivableVehicle, string>();

                // Loop trough all objects
                foreach (var objectGroup in groups)
                {
                    foreach (var obj in objectGroup.Objects)
                    {
                        // Small fix for spawn position with some entities
                        var halfTileOffset = -new Vector2(-level.TileWidth, level.TileHeight) / 2;

                        // Check type and create appropriate objects and entities
                        WorldEntity entity = null;
                        if (obj.Type == "spawnpoint")
                        {
                            entity          = new SpawnPoint(new Vector2((float)obj.X, (float)obj.Y) + halfTileOffset);
                            entity.Rotation = MathHelper.ToRadians((float)obj.Rotation);
                        }
                        else if (obj.Type == "guard")
                        {
                            entity          = new Guard();
                            entity.Position = new Vector2((float)obj.X, (float)obj.Y) + halfTileOffset;
                            entity.Rotation = MathHelper.ToRadians((float)obj.Rotation);

                            string path;
                            if (obj.Properties.TryGetValue("patrolpath", out path))
                            {
                                guardPaths.Add(entity as Guard, path);
                            }
                        }
                        else if (obj.Type == "car")
                        {
                            entity          = new Car(new Vector2((float)obj.X, (float)obj.Y) + halfTileOffset, null, "Sprites/Car");
                            entity.Rotation = MathHelper.ToRadians((float)obj.Rotation);

                            string path;
                            if (obj.Properties.TryGetValue("path", out path))
                            {
                                carPaths.Add(entity as Car, path);
                            }
                        }
                        else if (obj.Type == "bird")
                        {
                            entity = new Bird()
                            {
                                YResetValue = level.Height * level.TileHeight + 200
                            };
                            entity.Position = new Vector2((float)obj.X, (float)obj.Y) + halfTileOffset;
                            entity.Rotation = MathHelper.ToRadians((float)obj.Rotation);
                        }
                        else if (obj.Type == "helicopter")
                        {
                            entity          = new Helicopter();
                            entity.Position = new Vector2((float)obj.X, (float)obj.Y) + halfTileOffset;
                            entity.Rotation = MathHelper.ToRadians((float)obj.Rotation);

                            string objective;
                            if (obj.Properties.TryGetValue("objective", out objective))
                            {
                                driveObjective.Add(entity as DrivableVehicle, objective);
                            }
                        }
                        else if (obj.Type == "jeep")
                        {
                            entity          = new Jeep();
                            entity.Position = new Vector2((float)obj.X, (float)obj.Y) + halfTileOffset;
                            entity.Rotation = MathHelper.ToRadians((float)obj.Rotation);

                            string objective;
                            if (obj.Properties.TryGetValue("objective", out objective))
                            {
                                driveObjective.Add(entity as DrivableVehicle, objective);
                            }
                            string autoEnter;
                            if (obj.Properties.TryGetValue("autoenter", out autoEnter))
                            {
                                (entity as Jeep).autoenter = true;
                            }
                            string creditmode;
                            if (obj.Properties.TryGetValue("creditmode", out creditmode))
                            {
                                (entity as Jeep).creditsMode = true;
                            }
                        }
                        else if (obj.Type == "tank")
                        {
                            entity          = new Tank();
                            entity.Position = new Vector2((float)obj.X, (float)obj.Y) + halfTileOffset;
                            entity.Rotation = MathHelper.ToRadians((float)obj.Rotation);

                            string objective;
                            if (obj.Properties.TryGetValue("objective", out objective))
                            {
                                driveObjective.Add(entity as DrivableVehicle, objective);
                            }
                            string creditmode;
                            if (obj.Properties.TryGetValue("creditmode", out creditmode))
                            {
                                (entity as Tank).creditsMode = true;
                            }
                        }
                        else if (obj.Type == "objective")
                        {
                            string description;
                            string index;

                            if (obj.Properties.TryGetValue("description", out description))
                            {
                                if (obj.Properties.TryGetValue("index", out index))
                                {
                                    int ind       = Int32.Parse(index);
                                    bool newIndex = true;

                                    foreach (var item in objectives)
                                    {
                                        if (item.Value.Index == ind)
                                        {
                                            newIndex = false;
                                        }
                                    }
                                    if (newIndex)
                                    {
                                        entity = new Objective(description, ind);
                                        objectives.Add(obj.Name, entity as Objective);
                                    }
                                }
                            }
                        }
                        else if (obj.Type == "cctv")
                        {
                            entity          = new CCTV();
                            entity.Position = new Vector2((float)obj.X, (float)obj.Y) + halfTileOffset;
                            entity.Rotation = MathHelper.ToRadians((float)obj.Rotation);

                            string console;
                            if (obj.Properties.TryGetValue("pc", out console))
                            {
                                cameraConsole.Add(entity as CCTV, console);
                            }
                        }
                        else if (obj.Type == "pc")
                        {
                            entity          = new PC();
                            entity.Position = new Vector2((float)obj.X, (float)obj.Y);
                            entity.Rotation = MathHelper.ToRadians((float)obj.Rotation);

                            string objective;
                            if (obj.Properties.TryGetValue("objective", out objective))
                            {
                                pcWithObjective.Add(entity as PC, objective);
                            }

                            if (!consoles.ContainsKey(obj.Name))
                            {
                                consoles[obj.Name] = entity as PC;
                            }
                            else
                            {
                                Debug.WriteLine("Duplicate PC name " + obj.Name);
                            }
                        }
                        else if (obj.Type == "audio")
                        {
                            // Global audio
                            string audio;
                            string loop;
                            string volume;
                            bool willWork = true;

                            if (!obj.Properties.TryGetValue("source", out audio))
                            {
                                willWork = false;
                            }
                            if (!obj.Properties.TryGetValue("loop", out loop))
                            {
                                loop = "true";
                            }
                            if (!obj.Properties.TryGetValue("volume", out volume))
                            {
                                volume = "1";
                            }

                            if (willWork)
                            {
                                var soundEffect      = MonoGearGame.GetResource <SoundEffect>(audio).CreateInstance();
                                soundEffect.IsLooped = (loop == "true");
                                soundEffect.Volume   = float.Parse(volume) * SettingsPage.Volume * SettingsPage.EffectVolume;
                                AudioManager.PlayGlobal(soundEffect);
                                Debug.WriteLine("Added audio " + audio);
                                Debug.WriteLine("With Volume " + soundEffect.Volume);
                            }
                            else
                            {
                                Debug.WriteLine("Could not add audio" + audio);
                            }
                        }
                        else if (obj.Type == "audiosource")
                        {
                            // Positional audio
                            string audio;
                            string range;
                            string volume;

                            if (obj.Properties.TryGetValue("source", out audio))
                            {
                                if (!obj.Properties.TryGetValue("range", out range))
                                {
                                    range = "100";
                                }
                                if (!obj.Properties.TryGetValue("volume", out volume))
                                {
                                    volume = "1";
                                }
                                AudioManager.AddPositionalAudio(MonoGearGame.GetResource <SoundEffect>(audio), float.Parse(volume), float.Parse(range), new Vector2((float)obj.X, (float)obj.Y), true);
                            }
                        }
                        else if (obj.Type == "trigger")
                        {
                            string action;
                            if (obj.Properties.TryGetValue("action", out action))
                            {
                                Action <Collider, IEnumerable <Collider>, IEnumerable <Collider> > actionL = null;
                                if (action == "nextlevel")
                                {
                                    // Action for going to a next level
                                    actionL = (self, previous, current) =>
                                    {
                                        foreach (var col in current)
                                        {
                                            var vehicle = col.Entity as DrivableVehicle;
                                            if (col.Entity.Tag == "Player" || (vehicle != null && vehicle.Entered))
                                            {
                                                if (vehicle != null && vehicle.Entered)
                                                {
                                                    vehicle.Exit();
                                                }
                                                MonoGearGame.NextLevel();
                                            }
                                        }
                                    };
                                }
                                else if (action == "alert")
                                {
                                    // Action for alerting all guards to the players position
                                    actionL = (self, previous, current) =>
                                    {
                                        foreach (var col in current)
                                        {
                                            var vehicle = col.Entity as DrivableVehicle;
                                            if ((col.Entity.Tag == "Player" || (vehicle != null && vehicle.Entered)) && !previous.Contains(col))
                                            {
                                                var guards = MonoGearGame.FindEntitiesOfType <Guard>();
                                                foreach (var guard in guards)
                                                {
                                                    guard.Alert(col.Entity.Position);
                                                }
                                            }
                                        }
                                    };
                                }
                                else if (action == "objective")
                                {
                                    // Action for clearing an objective
                                    string objective;
                                    if (obj.Properties.TryGetValue("objective", out objective))
                                    {
                                        actionL = (self, previous, current) =>
                                        {
                                            foreach (var col in current)
                                            {
                                                var vehicle = col.Entity as DrivableVehicle;
                                                if (col.Entity.Tag == "Player" || (vehicle != null && vehicle.Entered))
                                                {
                                                    Objective ob;
                                                    if (objectives.TryGetValue(objective, out ob))
                                                    {
                                                        GameUI.CompleteObjective(ob);
                                                    }
                                                    else
                                                    {
                                                        Debug.WriteLine("Trgger could not find objective: " + objectives);
                                                    }
                                                }
                                            }
                                        };
                                    }
                                }
                                else
                                {
                                    Debug.WriteLine("Trigger " + obj.Name + " with unknown action " + action);
                                }

                                if (actionL != null)
                                {
                                    var size = new Vector2((float)obj.Width, (float)obj.Height);
                                    entity   = new WorldBoxTrigger(new Vector2((float)obj.X, (float)obj.Y) + size / 2,
                                                                   size,
                                                                   actionL);
                                }
                            }
                            else
                            {
                                Debug.WriteLine("Trigger " + obj.Name + " with no action!");
                            }
                        }
                        else if (obj.Type == "path")
                        {
                            // A patrol path
                            if (!paths.ContainsKey(obj.Name))
                            {
                                paths[obj.Name] = new List <Vector2>();
                                foreach (var point in obj.Points)
                                {
                                    paths[obj.Name].Add(new Vector2((float)point.X + (float)obj.X, (float)point.Y + (float)obj.Y));
                                }
                            }
                            else
                            {
                                Debug.WriteLine("Duplicate path name " + obj.Name);
                            }
                        }

                        if (entity != null)
                        {
                            // Set tag
                            string tag;
                            if (obj.Properties.TryGetValue("tag", out tag))
                            {
                                entity.Tag = tag;
                            }

                            level.AddEntity(entity);
                        }
                    }
                }

                // Assing guard patrol paths
                foreach (var guardPath in guardPaths)
                {
                    List <Vector2> path;
                    if (paths.TryGetValue(guardPath.Value, out path))
                    {
                        guardPath.Key.PatrolPath = path;
                    }
                    else
                    {
                        Debug.WriteLine("Guard requested unknown path " + guardPath.Value);
                    }
                }

                // Assing car paths
                foreach (var carPath in carPaths)
                {
                    List <Vector2> path;
                    if (paths.TryGetValue(carPath.Value, out path))
                    {
                        carPath.Key.SetPath(path);
                    }
                    else
                    {
                        Debug.WriteLine("Car requested unknown path " + carPath.Value);
                    }
                }

                // Assing PC/CCTV
                foreach (var kvPair in cameraConsole)
                {
                    PC pc;
                    if (consoles.TryGetValue(kvPair.Value, out pc))
                    {
                        pc.AddCCTV(kvPair.Key);
                    }
                    else
                    {
                        Debug.WriteLine("CCTV requested unknown PC " + kvPair.Value);
                    }
                }

                // Assing PC/Objective
                foreach (var pc in pcWithObjective)
                {
                    Objective ob;
                    if (objectives.TryGetValue(pc.Value, out ob))
                    {
                        pc.Key.Objective = ob;
                    }
                    else
                    {
                        Debug.WriteLine("PC could not find objective: " + pc.Value);
                    }
                }

                // Assing drive/Objective
                foreach (var drive in driveObjective)
                {
                    Objective ob;
                    if (objectives.TryGetValue(drive.Value, out ob))
                    {
                        drive.Key.objective = ob;
                    }
                    else
                    {
                        Debug.WriteLine("PC could not find objective: " + drive.Value);
                    }
                }
            }).Wait();
            return(level);
        }
예제 #9
0
        /// <summary>
        /// Method that updates the game
        /// </summary>
        /// <param name="input">Input</param>
        /// <param name="gameTime">GameTime</param>
        public override void Update(Input input, GameTime gameTime)
        {
            base.Update(input, gameTime);

            var target = player.Position;

            Rotation = MathExtensions.VectorToAngle(target - Position);
            var distance = Vector2.Distance(Position, target);

            if (distance > 260)
            {
                // Move towards player
                var delta = MathExtensions.AngleToVector(Rotation) * (float)gameTime.ElapsedGameTime.TotalSeconds;

                if (distance > 400)
                {
                    delta *= speed;
                }
                else if (player.CurrentVehicle != null)
                {
                    delta *= player.CurrentVehicle.Speed + 15;
                }
                else
                {
                    delta *= player.Speed + 15;
                }

                Move(delta);
            }

            heliSound.Position = Position;
            // Check if the delay is greater than 0
            if (delay > 0)
            {
                delay -= (float)gameTime.ElapsedGameTime.TotalSeconds;
            }

            // Check if the delay is smaller than 0
            if (delay <= 0 && distance < 320)
            {
                var missile = new Missile(MonoGearGame.FindEntitiesOfType <Player>()[0].Collider);

                // Check what barrel to shoot from
                Vector2 vec = new Vector2(18, 0);
                if (barrelNr == 0)
                {
                    vec.Y = 24;
                }
                if (barrelNr == 1)
                {
                    vec.Y = -24;
                }
                if (barrelNr == 2)
                {
                    vec.Y = 18;
                }
                if (barrelNr == 3)
                {
                    vec.Y = -18;
                }

                missile.Position = Position + Forward * vec.X + Right * vec.Y;
                missile.Rotation = MathExtensions.VectorToAngle(player.Position - missile.Position);

                MonoGearGame.SpawnLevelEntity(missile);

                barrelNr++;
                if (barrelNr > 3)
                {
                    barrelNr = 0;
                }

                var sound = MonoGearGame.GetResource <SoundEffect>("Audio/AudioFX/Helicopter_missile").CreateInstance();
                sound.Volume = 0.5f * SettingsPage.Volume * SettingsPage.EffectVolume;
                sound.Play();

                delay = 1f + 3.0f * (float)MathExtensions.Random.NextDouble();
            }
        }
예제 #10
0
        /// <summary>
        /// Called once per frame
        /// </summary>
        /// <param name="input">input</param>
        /// <param name="gameTime">gametime</param>
        public override void Update(Input input, GameTime gameTime)
        {
            // Animation done by parent class
            base.Update(input, gameTime);

            // Movement delta
            var dx = 0.0f;
            var dy = 0.0f;

            // Use analog sticks or keyboard for movement depending on if we have a gamepad connected
            if (input.PadConnected())
            {
                var sticks = input.GetGamepadState().ThumbSticks;

                dx += sticks.Left.X * Speed;
                dy += sticks.Left.Y * Speed;
            }
            else
            {
                if (input.IsButtonDown(Input.Button.Left))
                {
                    dx -= Speed;
                }
                if (input.IsButtonDown(Input.Button.Right))
                {
                    dx += Speed;
                }
                if (input.IsButtonDown(Input.Button.Up))
                {
                    dy -= Speed;
                }
                if (input.IsButtonDown(Input.Button.Down))
                {
                    dy += Speed;
                }
            }

            // Sneak mode
            if (input.IsButtonDown(Input.Button.Sneak))
            {
                SneakMode = true;
                Speed     = 50;
            }
            else
            {
                SneakMode = false;
                Speed     = 100;
            }

            // Clamp movement speed
            var delta = new Vector2(dx, dy);

            if (delta.LengthSquared() > Speed * Speed)
            {
                delta.Normalize();
                delta *= Speed;
            }

            // Get correct tile sound
            var tilevalue = MonoGearGame.GetCurrentLevel().GetTile(Position)?.Sound;
            SoundEffectInstance tilesound;

            switch (tilevalue)
            {
            case Tile.TileSound.Grass:
                tilesound = walkingSoundGrass;
                break;

            case Tile.TileSound.Water:
                tilesound = walkingSoundWater;
                break;

            case Tile.TileSound.Concrete:
                tilesound = walkingSoundStone;
                break;

            default:
                tilesound = walkingSoundStone;
                break;
            }

            if (tilesound != null && tilesound != walkingSound)
            {
                // stop old sound
                walkingSound.Stop();
                walkingSound = tilesound;
            }

            if (delta.LengthSquared() > 0)
            {
                // Moving
                Rotation         = MathExtensions.VectorToAngle(delta);
                AnimationRunning = true;
                walkingSound.Play();
            }
            else
            {
                // Standing still
                SneakMode             = true;
                AnimationRunning      = false;
                AnimationCurrentFrame = 1;
                walkingSound.Stop();
            }

            // Sneaking is silent
            if (SneakMode)
            {
                walkingSound.Stop();
            }

            // Reduce delay per frame
            if (ThrowingDelay > 0)
            {
                ThrowingDelay -= 1;
            }


            // Throw rock
            if (input.IsButtonPressed(Input.Button.Throw))
            {
                if (ThrowingDelay <= 0)
                {
                    // Spawn rock and play sound
                    var rock = new Rock(MonoGearGame.FindEntitiesOfType <Player>()[0].Collider);
                    rock.Position = Position;
                    rock.Rotation = Rotation;
                    MonoGearGame.SpawnLevelEntity(rock);
                    ThrowingDelay = 45;
                    var sound = MonoGearGame.GetResource <SoundEffect>("Audio/AudioFX/StoneTrow_sound").CreateInstance();
                    sound.Volume = 1 * SettingsPage.Volume * SettingsPage.EffectVolume;
                    sound.Play();
                }
            }

            // Shoot sleep dart
            if (input.IsButtonPressed(Input.Button.Shoot))
            {
                if (DartCount > 0)
                {
                    // Spawn dart and play sound
                    var sleepDart = new SleepDart(MonoGearGame.FindEntitiesOfType <Player>()[0].Collider);
                    sleepDart.Position = Position;
                    sleepDart.Rotation = Rotation;
                    MonoGearGame.SpawnLevelEntity(sleepDart);
                    DartCount--;
                    var sound = MonoGearGame.GetResource <SoundEffect>("Audio/AudioFX/Blowgun").CreateInstance();
                    sound.Volume = 1 * SettingsPage.Volume * SettingsPage.EffectVolume;
                    sound.Play();
                }
            }


            // Check collisions
            if (input.IsKeyDown(Keys.N))
            {
                // Noclip mode for debugging
                Position += delta * (float)gameTime.ElapsedGameTime.TotalSeconds * 10;
            }
            else
            {
                // Check collisions per axis
                var prevPos = Position;
                var deltaX  = new Vector2(delta.X, 0);
                var deltaY  = new Vector2(0, delta.Y);

                Position += deltaX * (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (Collider.CollidesAny())
                {
                    // Reset if we hit anything
                    Position = prevPos;
                }
                prevPos   = Position;
                Position += deltaY * (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (Collider.CollidesAny())
                {
                    // Reset if we hit anything
                    Position = prevPos;
                }
            }

            // Camera tracks player
            Camera.main.Position = new Vector2(Position.X, Position.Y);
        }