Esempio n. 1
0
        public void LoadMap(ContentManager contentManager, int id)
        {
            _tiledMap     = contentManager.Load <TiledMap>(String.Format("maps/Map{0}", id));
            _currentMapId = id;
            var tsx = (int)TileSize.X;
            var tsy = (int)TileSize.Y;

            _tileColliderBoxes = new List <Rectangle>();
            var blockedLayer = _tiledMap.GetLayer <TiledTileLayer>("Block");

            if (blockedLayer != null)
            {
                foreach (var tile in blockedLayer.Tiles)
                {
                    if (tile.Id != 0)
                    {
                        _tileColliderBoxes.Add(new Rectangle(tile.X * tsx, tile.Y * tsy, tsx, tsy));
                    }
                }
            }

            _spikes = new List <Rectangle>();
            var spikesLayer = _tiledMap.GetLayer <TiledTileLayer>("Spikes");

            if (spikesLayer != null)
            {
                foreach (var tile in spikesLayer.Tiles)
                {
                    if (tile.Id != 0)
                    {
                        _spikes.Add(new Rectangle(tile.X * tsx, tile.Y * tsy, tsx, tsy));
                    }
                }
            }
        }
Esempio n. 2
0
        public override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);

            GraphicsDevice.Clear(Color.Black);

            var viewMatrix       = _camera.GetViewMatrix();
            var projectionMatrix = Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width,
                                                                      GraphicsDevice.Viewport.Height, 0, 0f, -1f);

            // painter's algorithm; just draw things in the expected order

            var backgroundLayer = _map.GetLayer("background");

            _mapRenderer.Draw(backgroundLayer, ref viewMatrix, ref projectionMatrix);

            var solidsLayer = _map.GetLayer("solids");

            _mapRenderer.Draw(solidsLayer);

            var decorationsLayer = _map.GetLayer("decorations");

            _mapRenderer.Draw(decorationsLayer, ref viewMatrix, ref projectionMatrix);

            _entityComponentSystem.Draw(gameTime);

            var decorations2Layer = _map.GetLayer("decorations2");

            _mapRenderer.Draw(decorations2Layer, ref viewMatrix, ref projectionMatrix);

            var deadliesLayer = _map.GetLayer("deadlies");

            _mapRenderer.Draw(deadliesLayer, ref viewMatrix, ref projectionMatrix);
        }
Esempio n. 3
0
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

            //draw the tiles and plants layer of the tiled map on the screen
            tiledMapRenderer.Draw(tiledMap.GetLayer("tiles"));
            tiledMapRenderer.Draw(tiledMap.GetLayer("plants"));

            //draw the player image in position of the player object of the tiled map
            spriteBatch.Draw(playerImage, playerPosition, Color.White);

            //draw the trees layer of the tiled map after the player so the player can move behind the trees for example
            tiledMapRenderer.Draw(tiledMap.GetLayer("trees"));

            //draw message
            string text = "a map made in Tiled with object layer to set position of player image";

            spriteBatch.DrawString(font, text, new Vector2(10, 10), Color.White);

            spriteBatch.End();

            base.Draw(gameTime);
        }
Esempio n. 4
0
        private void InitializeFreeCellMatrix()
        {
            freeCellMatrix = new BitMatrix(map.Width, map.Height);
            var floors = map.GetLayer <TiledMapTileLayer>("Floor");
            var walls  = map.GetLayer <TiledMapTileLayer>("WallLayer");

            // непроходимая рамка по краю карты
            for (int i = 0; i < map.Width; i++)
            {
                freeCellMatrix[i, 0] = false;
                freeCellMatrix[i, map.Height - 1] = false;
            }

            for (int i = 0; i < map.Height; i++)
            {
                freeCellMatrix[0, i]             = false;
                freeCellMatrix[map.Width - 1, i] = false;
            }

            for (ushort x = 1; x < map.Width - 1; x++)
            {
                for (ushort y = 1; y < map.Height - 1; y++)
                {
                    freeCellMatrix[x, y] =
                        !floors.GetTile(x, y).IsBlank&&
                        walls.GetTile((ushort)(x - 1), (ushort)(y - 1)).IsBlank;
                }
            }
        }
Esempio n. 5
0
        public void LoadContent(ContentManager contentManager)
        {
            Song song = contentManager.Load <Song>("Music/FarmScene");

            MediaPlayer.Volume = 0.1f;
            MediaPlayer.Play(song);
            MediaPlayer.IsRepeating = true;
            startingLoc             = contentManager.Load <TiledMap>("Scenes Maps/Farm");
            obstaclesLayerFromMap   = startingLoc.GetLayer <TiledMapObjectLayer>("obstaclesLayerFromMap").Objects;
            collisionsLayerFromMap  = startingLoc.GetLayer <TiledMapObjectLayer>("collisionLayerFromMap").Objects;
            entitiesLayerFromMap    = startingLoc.GetLayer <TiledMapObjectLayer>("entitiesLayerFromMap").Objects;
            transitionsLayerFromMap = startingLoc.GetLayer <TiledMapObjectLayer>("transitionsLayerFromMap").Objects;

            LoadTrees();
            LoadEnemies();
            foreach (TiledMapObject collisionObjectFromMap in collisionsLayerFromMap)
            {
                collisionsObjectList.Add(new CollisionsObject(collisionObjectFromMap.Position, new Vector2(collisionObjectFromMap.Position.X + collisionObjectFromMap.Size.Width, collisionObjectFromMap.Position.Y + collisionObjectFromMap.Size.Height)));
            }

            foreach (Obstacles obstacle in obstaclesList)
            {
                obstacle.LoadContent(contentManager);
            }
            player.LoadContent(contentManager);
            attackSprite = contentManager.Load <Texture2D>("Attacks Textures/ball");

            foreach (Entity entity in entitiesList)
            {
                entity.LoadContent(contentManager);
            }
        }
Esempio n. 6
0
        public override void LoadContent()
        {
            base.LoadContent();

            var viewportAdapter = new BoxingViewportAdapter(Window, GraphicsDevice, 800, 480);

            _camera = new Camera2D(viewportAdapter);

            _map         = Content.Load <TiledMap>("level-1");
            _mapRenderer = new TiledMapRenderer(GraphicsDevice);

            _entityComponentSystem = new EntityComponentSystem();
            _entityFactory         = new EntityFactory(_entityComponentSystem, Content);

            var service    = new TiledObjectToEntityService(_entityFactory);
            var spawnPoint = _map.GetLayer <TiledMapObjectLayer>("entities").Objects.Single(i => i.Type == "Spawn").Position;

            _entityComponentSystem.RegisterSystem(new PlayerMovementSystem());
            _entityComponentSystem.RegisterSystem(new EnemyMovementSystem());
            _entityComponentSystem.RegisterSystem(new CharacterStateSystem(_entityFactory, spawnPoint));
            _entityComponentSystem.RegisterSystem(new BasicCollisionSystem(gravity: new Vector2(0, 1150)));
            _entityComponentSystem.RegisterSystem(new ParticleEmitterSystem());
            _entityComponentSystem.RegisterSystem(new AnimatedSpriteSystem());
            _entityComponentSystem.RegisterSystem(new SpriteBatchSystem(GraphicsDevice, _camera)
            {
                SamplerState = SamplerState.PointClamp
            });

            service.CreateEntities(_map.GetLayer <TiledMapObjectLayer>("entities").Objects);
        }
Esempio n. 7
0
        public void LoadContent(ContentManager content)
        {
            // TODO: fazer carregar o Level2, chamar o Luiz
            map         = content.Load <TiledMap>("Map1");
            mapRenderer = new TiledMapRenderer(graphics.GraphicsDevice, map);

            var objectsLayer = map.GetLayer <TiledMapObjectLayer>("Object Layer 1");
            var wallLayer    = map.GetLayer <TiledMapTileLayer>("Wall Layer");

            foreach (var i in objectsLayer.Objects)
            {
                if (i.Type == "Yoda")
                {
                    Player yoda = new Player(i);
                    entities.Add(yoda);
                }

                if (i.Type == "Enemy1")
                {
                    Enemy1 enemy1 = new Enemy1(i);
                    entities.Add(enemy1);
                }
            }

            foreach (var i in wallLayer.Tiles)
            {
                wallTiles.Add(i);
            }

            entities.ForEach(entity => { entity.Load(content); });
        }
Esempio n. 8
0
File: Game1.cs Progetto: educrod/rpg
        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            player_Sprite = Content.Load <Texture2D>("Player/player");
            playerDown    = Content.Load <Texture2D>("Player/playerDown");
            playerUp      = Content.Load <Texture2D>("Player/playerUp");
            playerLeft    = Content.Load <Texture2D>("Player/playerLeft");
            playerRight   = Content.Load <Texture2D>("Player/playerRight");

            eyeEnemy_Sprite   = Content.Load <Texture2D>("Enemies/eyeEnemy");
            snakeEnemy_Sprite = Content.Load <Texture2D>("Enemies/snakeEnemy");

            bush_Sprite = Content.Load <Texture2D>("Obstacles/bush");
            tree_Sprite = Content.Load <Texture2D>("Obstacles/tree");

            bullet_Sprite = Content.Load <Texture2D>("Misc/bullet");
            heart_Sprite  = Content.Load <Texture2D>("Misc/heart");

            player.animations[0] = new AnimatedSprite(playerDown, 1, 4);
            player.animations[1] = new AnimatedSprite(playerUp, 1, 4);
            player.animations[2] = new AnimatedSprite(playerLeft, 1, 4);
            player.animations[3] = new AnimatedSprite(playerRight, 1, 4);

            myMap = Content.Load <TiledMap>("Misc/gameMap");
            mapRenderer.LoadMap(myMap);

            TiledMapObject[] allEnemies = myMap.GetLayer <TiledMapObjectLayer>("enemies").Objects;
            foreach (var en in allEnemies)
            {
                string type;
                en.Properties.TryGetValue("Type", out type);
                if (type == "Snake")
                {
                    Enemy.enemies.Add(new Snake(en.Position));
                }
                else if (type == "Eye")
                {
                    Enemy.enemies.Add(new Eye(en.Position));
                }
            }
            TiledMapObject[] allObstacles = myMap.GetLayer <TiledMapObjectLayer>("obstacles").Objects;

            foreach (var obj in allObstacles)
            {
                string type;
                obj.Properties.TryGetValue("Type", out type);
                if (type == "Tree")
                {
                    Obstacle.obstacles.Add(new Tree(obj.Position));
                }
                else if (type == "Bush")
                {
                    Obstacle.obstacles.Add(new Bush(obj.Position));
                }
            }
        }
Esempio n. 9
0
        public void Draw(Microsoft.Xna.Framework.GameTime gameTime, Microsoft.Xna.Framework.Graphics.SpriteBatch spriteBatch)
        {
            foreach (var layer in _map.Layers.Where(l => l.Name != "UpperLayer"))
            {
                layer.IsVisible = true;
            }
            _map.GetLayer("UpperLayer").IsVisible = false;

            _map.Draw(_camera.GetViewMatrix());
        }
Esempio n. 10
0
        private void CheckCollision()
        {
            if (testlevel.ObjectLayers.Count == 0)
            {
                throw new Exception("Level hat keine Kollisionsebene.");
            }

            var collisionLayer = testlevel.GetLayer <TiledMapObjectLayer>("CollisionLayer");

            if (collisionLayer == null)
            {
                throw new Exception("Level hat keinen Layer mit dem Namen CollisionLayer.");
            }

            if (collisionLayer.Objects.Length == 0 || !collisionLayer.Objects.Any(t => t is TiledMapPolylineObject))
            {
                throw new Exception("Keine Polyline Objects...");
            }

            foreach (var obj in collisionLayer.Objects.Where(t => t is TiledMapPolylineObject))
            {
                var pointsObject = (TiledMapPolylineObject)obj;

                for (int i = 0; i < pointsObject.Points.Length - 1; i++)
                {
                    var currentPoint = pointsObject.Points[i] + pointsObject.Position;
                    var nextPoint    = pointsObject.Points[i + 1] + pointsObject.Position;

                    if ((spieler.Position.X + (spieler.Animationen.Aktuell.Breite / 2)) >= currentPoint.X && (spieler.Position.X + (spieler.Animationen.Aktuell.Breite / 2)) < nextPoint.X)
                    {
                        float linieY = SolveLinearEquation(currentPoint, nextPoint, (spieler.Position.X + (spieler.Animationen.Aktuell.Breite / 2)));
                        if ((spieler.Position.Y + spieler.Animationen.Aktuell.Höhe) > linieY && (spieler.Position.Y + spieler.Animationen.Aktuell.Höhe) < (linieY + testlevel.TileHeight))
                        {
                            spieler.Position = new Vector2(spieler.Position.X, linieY - spieler.Animationen.Aktuell.Höhe);
                            spieler.Velocity = new Vector2(0, Spieler.Geschwindigkeit);
                        }
                    }

                    foreach (var gegner in Gegner)
                    {
                        if ((gegner.Position.X + (gegner.Animationen.Aktuell.Breite / 2)) >= currentPoint.X && (gegner.Position.X + (gegner.Animationen.Aktuell.Breite / 2)) < nextPoint.X)
                        {
                            float linieY = SolveLinearEquation(currentPoint, nextPoint, (gegner.Position.X + (gegner.Animationen.Aktuell.Breite / 2)));
                            if ((gegner.Position.Y + gegner.Animationen.Aktuell.Höhe) > linieY && (gegner.Position.Y + gegner.Animationen.Aktuell.Höhe) < (linieY + testlevel.TileHeight))
                            {
                                gegner.Position = new Vector2(gegner.Position.X, linieY - gegner.Animationen.Aktuell.Höhe);
                                gegner.Velocity = new Vector2(gegner.Velocity.X, Spieler.Geschwindigkeit);
                            }
                        }
                    }
                }
            }
        }
Esempio n. 11
0
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            //load font
            font = Content.Load <SpriteFont>("Font");

            //load the tiled map
            tiledMap = Content.Load <TiledMap>("map1");

            //load the player image
            playerImage = Content.Load <Texture2D>("p1_front");

            //our tiled map comes with an object layer and we have the player position selected on the layer
            //get the object layer of the tiled map called "objects"
            TiledMapObject[] tiledObjects = tiledMap.GetLayer <TiledMapObjectLayer>("objects").Objects;
            //go through each object on the objects layer
            foreach (TiledMapObject objects in tiledObjects)
            {
                //find the object called "player" and get the position, we are going to use this to draw player image in that position
                if (objects.Name == "player")
                {
                    playerPosition = objects.Position;
                }
            }
        }
Esempio n. 12
0
File: Map.cs Progetto: TomSavas/Cask
        public override void Draw(GameTime gameTime, Camera camera)
        {
            _mapRenderer ??= new TiledMapRenderer(camera.GraphicsDevice);
            _mapRenderer.Draw(_map.GetLayer(""), camera.GetViewMatrix(), Matrix.Identity);

            base.Draw(gameTime, camera);
        }
Esempio n. 13
0
        private void GenerateTileMap()
        {
            _tiledMap         = _game.Content.Load <TiledMap>("Test");
            _tiledMapRenderer = new TiledMapRenderer(_game.GraphicsDevice, _tiledMap);

            _mapWidth  = _tiledMap.WidthInPixels;
            _mapHeight = _tiledMap.HeightInPixels;

            _collisionComponent = new CollisionComponent(new RectangleF(0, 0, _mapWidth, _mapHeight));

            TiledMapTileLayer collidables = _tiledMap.GetLayer <TiledMapTileLayer>("Collidable");

            if (collidables != null)
            {
                foreach (TiledMapTile t in collidables.Tiles)
                {
                    // Global Identifier 0 means tile is empty
                    if (t.GlobalIdentifier == 0)
                    {
                        continue;
                    }

                    Vector2 pos = Vector2.Zero;

                    pos.X = t.X * collidables.TileWidth;
                    pos.Y = t.Y * collidables.TileHeight;

                    Size2 size = new Size2(collidables.TileWidth, collidables.TileHeight);

                    Wall w = new Wall(pos, size);
                    _collisionComponent.Insert(w);
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch   = new SpriteBatch(GraphicsDevice);
            map           = Content.Load <TiledMap>("test1");
            mapWidth      = map.Width;
            mapHeight     = map.Height;
            tileWidth     = map.TileWidth;
            collisionGrid = new int[mapHeight, mapWidth];
            var tileLayer = map.GetLayer <TiledMapTileLayer>("Tile Layer 1");

            for (int i = 0; i < mapHeight; i++)
            {
                for (int j = 0; j < mapWidth; j++)
                {
                    System.Diagnostics.Debug.Write((int)Char.GetNumericValue(tileLayer.GetTile((ushort)j, (ushort)i).ToString()[18]) + " ,");
                    collisionGrid[i, j] = (int)Char.GetNumericValue(tileLayer.GetTile((ushort)j, (ushort)i).ToString()[18]);
                }
                System.Diagnostics.Debug.WriteLine("");
            }
            //foreach (int i in collisionGrid)
            //{
            //    System.Diagnostics.Debug.Write("{0} ", i.ToString());
            //}
            collisionMap = new CollisionMap(collisionGrid, map.TileHeight);
            mapRenderer  = new TiledMapRenderer(GraphicsDevice, map);
            // TODO: use this.Content to load your game content here
            Vector2 playerPosition = new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X, 0);

            player.Initialize(Content.Load <Texture2D>("Graphics\\basicchar"), playerPosition, 0);
            camera.Pos = new Vector2(playerPosition.X, playerPosition.Y);
        }
Esempio n. 15
0
        public override void Draw(GameTime gameTime)
        {
            // This game has a blue background. Why? Because!
            ScreenManager.GraphicsDevice.Clear(ClearOptions.Target, Color.CornflowerBlue, 0, 0);

            // Our player and enemy are both actually just text strings.
            var spriteBatch = ScreenManager.SpriteBatch;

            spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp);

            _mapRenderer.Draw(
                _isShowingMap2 ? _testMap2.GetLayer("LevelGraphics") : _testMap1.GetLayer("LevelGraphics"));

            spriteBatch.DrawString(_font, "Tomas is Awesome", new Vector2(100f, 20f), Color.Green);

            if (_isShowingCollision && !_isShowingMap2)
            {
                foreach (var collisionObject in _testMap1.ObjectLayers[0].Objects.Where(o => o.Type == "Rectangle"))
                {
                    spriteBatch.DrawRectangle(collisionObject.Position, collisionObject.Size, Color.Pink);
                }
                //TODO: Figure out how to draw polygons from the ObjectLayer's Object collection.
                // the one we're trying to draw has a Name and Type == "Slope", and has a Position and collection of Point objects that are offsets from the Position
            }

            spriteBatch.End();

            // If the game is transitioning on or off, fade it out to black.
            if (TransitionPosition > 0 || _pauseAlpha > 0)
            {
                float alpha = MathHelper.Lerp(1f - TransitionAlpha, 1f, _pauseAlpha / 2);
                ScreenManager.FadeBackBufferToBlack(alpha);
            }
        }
Esempio n. 16
0
        public Dungeon(World world, TiledMap map, TiledMapRenderer mapRenderer)
        {
            this.world       = world;
            this.map         = map;
            this.mapRenderer = mapRenderer;
            if (map.Width % Room.NumTilesWidth != 0 || map.Height % Room.NumTilesHeight != 0)
            {
                throw new ArgumentException(
                          $"Invalid dimensions ({map.Width} x {map.Height}) for map \"{map.Name}\". Map dimensions must be a multiple of ({Room.NumTilesWidth} x {Room.NumTilesHeight}).");
            }
            var bottomLayer = map.GetLayer <TiledMapTileLayer>(BottomLayerName);

            if (bottomLayer == null)
            {
                throw new ArgumentException($"Map \"{map.Name}\" doesn't contain a tile layer named \"{BottomLayerName}\"");
            }
            this.rooms = new Room[map.Width / Room.NumTilesWidth, map.Height / Room.NumTilesHeight];
            for (int j = 0; j < this.rooms.GetLength(1); ++j)
            {
                for (int i = 0; i < this.rooms.GetLength(0); ++i)
                {
                    int x = i * Room.NumTilesWidth;
                    int y = j * Room.NumTilesHeight;
                    if (IsRoomEmpty(bottomLayer, x, y))
                    {
                        continue;
                    }
                    this.rooms[i, j] = new Room(new Point(i, j));
                }
            }
            var objectLayer = map.GetLayer <TiledMapObjectLayer>(CollisionLayerName);

            if (objectLayer == null)
            {
                throw new ArgumentException($"Map \"{map.Name}\" doesn't contain an object layer named \"{CollisionLayerName}\"");
            }
            foreach (TiledMapObject obj in objectLayer.Objects)
            {
                Rectangle immovable = new Rectangle((int)obj.Position.X, (int)obj.Position.Y, (int)obj.Size.Width, (int)obj.Size.Height);
                Room      room      = this.RoomContains(immovable.Center);
                if (room == null)
                {
                    throw new ArgumentException($"Couldn't find room containing object {obj}");
                }
                room.Immovables.Add(immovable);
            }
        }
Esempio n. 17
0
        private void InitObjects()
        {
            Log.Debug("Creating objects for " + this + ".");

            var layer = map.GetLayer <TiledMapObjectLayer>("object");

            if (layer == null)
            {
                Log.Warn(this + " has no 'object' layer.");
                return;
            }

            foreach (var obj in layer.Objects)
            {
                var bounds = new Rectangle((int)obj.Position.X, (int)obj.Position.Y, (int)obj.Size.Width, (int)obj.Size.Height);

                if (obj.Properties.GetString("type") == "Group")
                {
                    InitGroup(obj, bounds);
                }
                else
                {
                    if (!Enum.TryParse(obj.Properties.GetString("type"), out ObjectType type))
                    {
                        Log.Error("Unknown object type '" + obj.Properties.GetString("type") + "' at " + bounds + ".");
                        continue;
                    }

                    switch (type)
                    {
                    case ObjectType.Link:
                    {
                        var target = Get(obj.Properties.GetString("target"));
                        if (target == null)
                        {
                            Log.Error("Object at " + bounds + " has an invalid target '" + obj.Properties.GetString("target") + "'.");
                            continue;
                        }
                        objects.Add(ObjectData.CreateLink(bounds, target));
                        break;
                    }

                    case ObjectType.Info:
                    {
                        var text = obj.Properties.GetString("text");
                        if (text == null)
                        {
                            Log.Error("Object at " + bounds + " has an no text.");
                            continue;
                        }
                        objects.Add(ObjectData.CreateInfo(bounds, text));
                        break;
                    }
                    }

                    Log.Debug("Added " + objects[objects.Count - 1] + ".");
                }
            }
        }
Esempio n. 18
0
        protected override void Draw(GameTime gameTime)
        {
            //GraphicsDevice.Clear(Color.CornflowerBlue);//not needed if drawing a map, silly!

            spriteBatch.Begin(samplerState: SamplerState.LinearClamp);

            mapRenderer.Draw(map.GetLayer("Base"), camera.GetViewMatrix(fixedFactor));          //draws fixed layer
            mapRenderer.Draw(map.GetLayer("Background"), camera.GetViewMatrix(parallaxFactor)); //draws parallax layer
            mapRenderer.Draw(map.GetLayer("Foreground"), camera.GetViewMatrix());               //draws foreground layer
            //mapRenderer.Draw(map, camera.GetViewMatrix());//OLD, draws all map layers

            //DRAW SPRITES HERE

            spriteBatch.End();

            base.Draw(gameTime);
        }
Esempio n. 19
0
 public Level(TiledMap map)
 {
     Map = map;
     map.Properties.TryGetValue("MapName", out MapName);
     ObjectLayer      = map.GetLayer <TiledMapObjectLayer>("GameObjects");
     NavigationMatrix = new int[map.Width, map.Height];
     ElevationMatrix  = new int[map.Width, map.Height];
     Characters       = new List <Character>();
 }
Esempio n. 20
0
        /// <summary>
        /// Goes through the current level file and loads all of the collision objects, so that they can be returned and added to the list of active GameObjects. Note that all collision object must be on a layer
        /// named "collision" that is set to be an object layer, and not a normal tile layer (normal tiles don't have a position member).
        /// </summary>
        /// <returns></returns>
        public List <GameObject> getCollisionObjects()
        {
            List <GameObject> collisionObjects = new List <GameObject>();

            TiledMapObjectLayer objectLayer = currentMap.GetLayer <TiledMapObjectLayer>("collision"); //Get the collision layer to start with

            TiledMapLayer debugLayer = currentMap.GetLayer <TiledMapLayer>("collision");

            Console.WriteLine(debugLayer.ToString());

            GameObject tempObject; //Make an object reference to hold objects we'll construct later, and then add properties to

            try
            {
                foreach (TiledMapPolygonObject tile in objectLayer.Objects) //Go through all of the tiles in the map
                {
                    tempObject = new GameObject();
                    tempObject.transform.SetPosition(tile.Position); //Set the collision object's position

                    //Get the vertices of this collision object
                    Vector2[] vertices;
                    vertices = new Vector2[tile.Points.Count()]; //Set the vertices to be the same count as that of the tile object's
                    for (int i = 0; i < tile.Points.Count(); i++)
                    {
                        vertices[i] = new Vector2(tile.Points[i].X, tile.Points[i].Y); //The Points are already the displacement from an origin, so this will match the Hitbox constructor later
                    }
                    Hitbox hitbox = new Hitbox(vertices, tempObject);                  //Create a hitbox for this tile
                    tempObject.AddComponent(hitbox);                                   //Give the tile the hitbox
                    tempObject.AddComponent(new CollisionComponent(null, hitbox));     //Add collision to the tile with the given hitbox and no physics component

                    collisionObjects.Add(tempObject);                                  //Now that the tile object has collision and a hitbox mask, add it to the list of GameObjects that we want to return
                }
            }

            catch (Exception e) //In case the collision layer is null
            {
                Console.WriteLine("Error encountered in getCollisionObjects(): " + e.Message);
            }

            //DEBUG Let's make sure that it's correctly adding the tile objects
            Console.WriteLine("Number of collision objects = " + collisionObjects.Count);

            return(collisionObjects);
        }
Esempio n. 21
0
        public TiledMapComponent(TiledMap tiledMap, string collisionLayerName = null, bool shouldCreateColliders = true)
        {
            this.TiledMap          = tiledMap;
            _shouldCreateColliders = shouldCreateColliders;

            if (collisionLayerName != null)
            {
                CollisionLayer = tiledMap.GetLayer <TiledTileLayer>(collisionLayerName);
            }
        }
Esempio n. 22
0
        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            _playerTexture    = Content.Load <Texture2D>("ball");
            _map              = Content.Load <TiledMap>("Plazas/sample");
            _tiledMapRenderer = new TiledMapRenderer(GraphicsDevice, _map);
            _borders          = _map.GetLayer <TiledMapTileLayer>("Obstacles");
            _objects          = _map.GetLayer <TiledMapObjectLayer>("Objects");

            var pos = _objects?.Objects?.FirstOrDefault(o =>
            {
                o.Properties.TryGetValue("player", out string playerPos);
                return(int.Parse(playerPos) == 1);
            });

            _startPosition = pos.Position;
        }
Esempio n. 23
0
        public void CheckForCollision(TiledMap map)
        {
            // Collision with bottom of map
            if (this.BoundingRect.Bottom > map.HeightInPixels)
            {
                this.position.Y = map.HeightInPixels - texture.Height;
                this.velocity.Y = 0;
                onGround        = true;
            }
            // Collision with top of map
            if (this.BoundingRect.Top < 0)
            {
                this.position.Y = 0;
                this.velocity.Y = 0;
            }
            // Collision with top of map
            if (this.BoundingRect.Left < 0)
            {
                this.position.X = 0;
                this.velocity.X = 0;
            }
            // Collision with top of map
            if (this.BoundingRect.Right > map.WidthInPixels)
            {
                this.position.X = map.WidthInPixels - texture.Width;
                this.velocity.X = 0;
            }


            // Check for collision using collision layer
            TiledTileLayer layer = (TiledTileLayer)map.GetLayer("Collision");

            foreach (var tile in layer.Tiles)
            {
                if (
                    ((tile.X * 32) > this.BoundingRect.Right) ||
                    ((tile.Y * 32) > this.BoundingRect.Bottom) ||
                    (((tile.X * 32) + 32) < this.BoundingRect.Left) ||
                    (((tile.Y * 32) + 32) < this.BoundingRect.Top)
                    )
                {
                    continue;
                }


                var region = map.GetTileRegion(tile.Id);
                if (region != null && region.Texture.Name == "Tilesets/collision" &&
                    (region.X + region.Y == 35))
                {
                    this.position.Y = (tile.Y * 32) - this.BoundingRect.Height;
                    this.velocity.Y = 0;
                    onGround        = true;
                }
            }
        }
Esempio n. 24
0
        protected override void LoadContent()
        {
            base.LoadContent();

            var viewportAdapter = new BoxingViewportAdapter(Window, GraphicsDevice, 800, 480);

            _camera = new Camera2D(viewportAdapter);
            Services.AddService(_camera);

            _spriteBatch = new SpriteBatch(GraphicsDevice);
            Services.AddService(_spriteBatch);

            _map           = Content.Load <TiledMap>("level-1");
            _mapRenderer   = new TiledMapRenderer(GraphicsDevice);
            _entityFactory = new EntityFactory(_ecs, Content);

            var service    = new TiledObjectToEntityService(_entityFactory);
            var spawnPoint = _map.GetLayer <TiledMapObjectLayer>("entities").Objects.Single(i => i.Type == "Spawn").Position;

            service.CreateEntities(_map.GetLayer <TiledMapObjectLayer>("entities").Objects);
        }
Esempio n. 25
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            _map = Content.Load <TiledMap>("level01");

            _entityComponentSystem.RegisterSystem(new CollisionSystem());
            _entityComponentSystem.RegisterSystem(new SpriteBatchSystem(GraphicsDevice, _camera));
            _entityComponentSystem.RegisterSystem(new PlayerMovementSystem());

            _objectToEntityService.createEntities(_map.GetLayer <TiledMapObjectLayer>("entities").Objects);
        }
Esempio n. 26
0
        public void Draw(SpriteBatch spriteBatch)
        {
            Matrix transform = _camera.GetViewMatrix();

            _tiledMapRenderer.Draw(_tiledMap.GetLayer("Space"), transform);
            _tiledMapRenderer.Draw(_tiledMap.GetLayer("ShipFloor"), transform);
            _tiledMapRenderer.Draw(_tiledMap.GetLayer("Collidable"), transform);

            spriteBatch.Begin(transformMatrix: transform, samplerState: SamplerState.PointClamp);
            // Draws all game objects to screen
            foreach (IEntity entity in _entities)
            {
                entity.Draw(spriteBatch);
            }
            _player.Draw(spriteBatch);

            spriteBatch.End();

            _tiledMapRenderer.Draw(_tiledMap.GetLayer("UpperLayer"), transform);

            // HUD Section
            spriteBatch.Begin(samplerState: SamplerState.PointClamp);
            _playerInventoryHud.Draw(spriteBatch);
            _toolboxInventoryHud.Draw(spriteBatch);
            _healthBar.Draw(spriteBatch);
            spriteBatch.DrawString(_font, _brokenList, new Vector2(50f, 100f), Color.White);
            spriteBatch.End();
        }
Esempio n. 27
0
        public Map(TiledMap tiles)
        {
            this.Tiles = tiles;
            this.Name  = tiles.Name.Substring(tiles.Name.LastIndexOf('/') + 1);
            this.Scale = (tiles.TileWidth + tiles.TileHeight) / 2;

            this.IsInside   = this.Tiles.Properties.ContainsKey("Inside") && bool.Parse(this.Tiles.Properties["Inside"]);
            this.NightColor = !this.IsInside ? new Color(220, 220, 150) : new Color(150, 150, 120);

            var objects = tiles.GetLayer <TiledMapObjectLayer>("StaticObjects");

            if (objects != null)
            {
                foreach (var obj in objects.Objects)
                {
                    var mapPos = (obj.Position / this.Scale).ToPoint();
                    switch (obj.Type)
                    {
                    case "Teleporter":
                        this.StaticObjects.Add(mapPos, new Teleporter(this, mapPos, obj.Size,
                                                                      obj.Properties["Destination"],
                                                                      new Point(int.Parse(obj.Properties["DestX"]), int.Parse(obj.Properties["DestY"])),
                                                                      obj.Properties.ContainsKey("Interaction") && bool.Parse(obj.Properties["Interaction"])));
                        break;
                    }
                }
            }

            foreach (var layer in this.Tiles.TileLayers)
            {
                for (var x = 0; x < layer.Width; x++)
                {
                    for (var y = 0; y < layer.Height; y++)
                    {
                        var tile = this[layer.Name, x, y];
                        if (tile.HasValue && !tile.Value.IsBlank)
                        {
                            var props = this.GetTileProperties(tile.Value, "LightColor", "LightRadius", "LightType");
                            if (props[0] != null && props[1] != null)
                            {
                                var size = float.Parse(props[1], NumberFormatInfo.InvariantInfo) * 2F;
                                this.LightSources.Add(new LightSource(
                                                          new Vector2(x + 0.5F, y + 0.5F) * this.Scale,
                                                          new Size2(size, size) * this.Scale,
                                                          new Color(uint.Parse(props[0].Substring(1), NumberStyles.HexNumber)),
                                                          props[2]));
                            }
                        }
                    }
                }
            }
        }
Esempio n. 28
0
        public bool WaterCollision(Point p)
        {
            const string layerName  = "Water-Layer";
            var          waterLayer = Map.GetLayer <TiledTileLayer>(layerName);
            var          collision  = false;

            if (waterLayer != null)
            {
                var waterCollision = new TiledCollisionSystem(_possibleMovements, Map, layerName);
                collision = waterCollision.CheckCollision(p);
            }
            return(collision);
        }
Esempio n. 29
0
 public void Draw(GraphicsDevice graphicsDevice)
 {
     graphicsDevice.SamplerStates[0] = SamplerState.PointClamp;
     graphicsDevice.RasterizerState  = RasterizerState.CullNone;
     tiledMapRenderer.Draw(startingLoc.GetLayer("1"), playerCamera.Transform);
     tiledMapRenderer.Draw(startingLoc.GetLayer("Special layer"), playerCamera.Transform);
     spriteBatch.Begin(transformMatrix: playerCamera.Transform, sortMode: SpriteSortMode.FrontToBack, depthStencilState: DepthStencilState.DepthRead, blendState: BlendState.AlphaBlend);
     DrawLayer();
     spriteBatch.End();
     spriteBatch.Begin(depthStencilState: DepthStencilState.DepthRead, blendState: BlendState.AlphaBlend);
     player.gui.showPlayerHP(spriteBatch);
     for (int i = 2; i < 8; i++)
     {
         tiledMapRenderer.Draw(startingLoc.GetLayer(i.ToString()), playerCamera.Transform);
     }
     spriteBatch.End();
     //foreach (PlayerAttack playerAttack in PlayerAttack.playerAttacks){
     //    spriteBatch.Draw(attackSprite, new Rectangle((int)playerAttack.position.X, (int)playerAttack.position.Y, 16, 16), null, Color.White, 0, Vector2.Zero, SpriteEffects.None, layerDepth: 0.01f);
     //    //     if (Obstacles.didCollide(playerAttack.position, playerAttack.Radius))
     //    //         playerAttack.Collided = true;
     //}
 }
Esempio n. 30
0
        public void Draw(SpriteBatch spriteBatch)
        {
            tiledRenderer.Draw(Camera2D.GetTransformMatrix(), null, null, 0f);

            for (int i = 0; i < objects.Count; i++)
            {
                objects[i].Draw(spriteBatch);
            }

#if DEBUG
            for (int i = 0; i < tileCollisionsDoor.Count; i++)
            {
                spriteBatch.Draw(tileTexture, tileCollisionsDoor[i].Rectangle, Color.Green);
            }
#endif
            spriteBatch.End();

            spriteBatch.Begin();
            if (tiledMap.GetLayer("Overlay") != null)
            {
                tiledRenderer.Draw(tiledMap.GetLayer("Overlay"), Camera2D.GetTransformMatrix(), null, null, 1f);
            }
        }