コード例 #1
0
        public MapGraphicsComponent(TmxMap Map)
        {
            var tileWidth = Map.Tilesets.Single().TileWidth;
            var tileHeight = Map.Tilesets.Single().TileHeight;
            var tileSpacing = Map.Tilesets.Single().Spacing;
            var tileMargins = Map.Tilesets.Single().Margin;

            texture = new RenderTexture((uint)(Map.Width * tileWidth), (uint)(Map.Height * tileHeight));

            foreach (var layer in Map.Layers)
            {
                foreach (var tile in layer.Tiles)
                {
                    var columns = (int)tileset.Texture.Size.X / (tileWidth + tileSpacing);

                    int x = (tile.Gid - 1) % columns,
                        y = (tile.Gid - 1) / columns;

                    tileset.TextureRect = new IntRect(x * (tileWidth + tileSpacing) + tileMargins,
                                                        y * (tileHeight + tileSpacing) + tileMargins, tileWidth,
                                                        tileHeight);
                    tileset.Position = new Vector2f(tile.X * tileWidth, tile.Y * tileHeight);

                    texture.Draw(tileset);
                }
            }

            texture.Display();
            Sprite = new Sprite(texture.Texture);
        }
コード例 #2
0
        public static Texture2D GetTexture(TmxMap map, List<Texture2D> textures, int gid)
        {
            int tilesetIdx = 0;
            foreach (var tileset in map.Tilesets)
            {
                if (tileset.FirstGid <= gid && gid < tileset.FirstGid + tileset.TileCount)
                {
                    Texture2D originalTexture = textures[tilesetIdx];
                    // tileWidth and tileHeight are in pixels
                    int tileWidth = tileset.TileWidth, tileHeight = tileset.TileHeight;
                    // tilesetWidth measure number of tiles across
                    int tilesetWidth = originalTexture.Width / (tileWidth + tileset.Spacing);

                    int textureID = gid - tileset.FirstGid;
                    int row = (textureID) / tilesetWidth;
                    int column = (textureID) % tilesetWidth;
                    Rectangle sourceRectangle =
                        new Rectangle(tileWidth * column + column * tileset.Spacing,
                                      tileHeight * row + row * tileset.Spacing,
                                      tileWidth, tileHeight);

                    GraphicsDevice graphicsDevice = EntitySystem.BlackBoard.GetEntry<GraphicsDevice>("GraphicsDevice");
                    Texture2D cropTexture = new Texture2D(graphicsDevice, sourceRectangle.Width, sourceRectangle.Height);
                    Color[] data = new Color[sourceRectangle.Width * sourceRectangle.Height];
                    originalTexture.GetData(0, sourceRectangle, data, 0, data.Length);
                    cropTexture.SetData(data);
                    return cropTexture;
                }
                ++tilesetIdx;
            }

            return null;
        }
コード例 #3
0
        public Layer[] LoadObjectLayers(TmxMap tmxMap, ContentManager content)
        {
            var layers = new Layer[tmxMap.ObjectGroups.Count];

            for (int i = 0; i < tmxMap.ObjectGroups.Count; i++)
            {
                OrderedDictionary<string, IGameObject> _gameObjects = new OrderedDictionary<string, IGameObject>();

                foreach (var tmxObject in tmxMap.ObjectGroups[i].Objects)
                {
                    if (tmxObject.Type == "Particle Emitter")
                    {
                        IGameObject gameObject = this.LoadParticleEmitter(tmxObject, content);
                        _gameObjects.Add(tmxObject.Name, gameObject);
                    }
                    else if (tmxObject.Type == "NPC Spawner")
                    {
                        IGameObject gameObject = this.LoadNpcSpawner(tmxObject, _gameObjects, content);
                        _gameObjects.Add(tmxObject.Name, gameObject);
                    }
                }

                layers[i] = new Layer(_gameObjects, tmxMap.ObjectGroups[i].ZOrder);
            }

            return layers;
        }
コード例 #4
0
ファイル: Map.cs プロジェクト: guipaz/stryfe-rpg
        public Map(TmxMap tmxMap, string name)
        {
            this.TmxMap = tmxMap;
            Name = name;

            Width = tmxMap.Width;
            Height = tmxMap.Height;

            Tilesets = new List<Tileset>();
            foreach (TmxTileset tmxTileset in tmxMap.Tilesets)
            {
                Tilesets.Add(new Tileset(tmxTileset));
            }

            Objects = new List<MapObject>();
            foreach (TmxObjectGroup group in tmxMap.ObjectGroups)
            {
                foreach (TmxObject obj in group.Objects)
                {
                    Tileset tileset = GetTileset(obj.Tile != null ? obj.Tile.Gid : -1);

                    if (obj.Type == "npc")
                    {
                        Objects.Add(new NPC(obj, tileset, Name));
                    } else if (obj.Type == "player")
                    {
                        PlayerReference = new Player(obj, tileset);
                        Global.defaultObj = obj;
                        Global.defaultTileset = tileset;
                    } else if (obj.Type == "teleport")
                    {
                        Objects.Add(new Teleport(obj, tileset));
                    }
                    else if (obj.Type == "item")
                    {
                        Objects.Add(new ItemObject(obj, tileset));
                    } else
                    {
                        Objects.Add(new MapObject(obj, tileset, Name));
                    }
                }
            }

            // Populate above layers
            AboveLayers = new List<TmxLayer>();
            foreach (TmxLayer layer in tmxMap.Layers)
            {
                if (layer.Properties.ContainsKey("above") && layer.Properties["above"] == "true")
                    AboveLayers.Add(layer);
            }

            // Gets the song
            if (TmxMap.Properties.ContainsKey("song"))
            {
                song = TmxMap.Properties["song"];
            }

            PopulateCollisions();
        }
コード例 #5
0
ファイル: MapObject.cs プロジェクト: RobKellett/EdgeCandy
        public MapObject(TmxMap map)
        {
            Map = map;
            Graphics = new MapGraphicsComponent(map);

            foreach (var platform in map.ObjectGroups["Solid"].Objects)
                Platforms.Add(new PlatformObject(ConvertUnits.ToSimUnits(platform.X),
                                                 ConvertUnits.ToSimUnits(platform.Y),
                                                 ConvertUnits.ToSimUnits(platform.Width),
                                                 ConvertUnits.ToSimUnits(platform.Height)));

            // "implicit" walls to prevent leaving the screen
            Platforms.Add(new WallObject(ConvertUnits.ToSimUnits(-map.TileWidth),
                                             0,
                                             ConvertUnits.ToSimUnits(map.TileWidth),
                                             ConvertUnits.ToSimUnits(map.Height * map.TileHeight)));

            Platforms.Add(new WallObject(ConvertUnits.ToSimUnits(map.Width * map.TileWidth),
                                             0,
                                             ConvertUnits.ToSimUnits(map.TileWidth),
                                             ConvertUnits.ToSimUnits(map.Height * map.TileHeight)));

            foreach (var candy in map.ObjectGroups["Candy"].Objects)
            {
                CandyKind kind;
                if (Enum.TryParse(candy.Name, out kind))
                {
                    CandyObject cobj;
                    if (kind == CandyKind.Chocolate)
                        cobj = new CandyObject(kind, new Vector2(candy.X, candy.Y), new Vector2(candy.Width, candy.Height));
                    else
                        cobj = new CandyObject(kind, new Vector2(candy.X + candy.Width / 2, candy.Y + candy.Height / 2));
                    Candies.Add(cobj);
                }
            }

            foreach (var obj in map.ObjectGroups["Misc"].Objects)
            {
                if (obj.Name == "Text")
                {
                    Hints.Add(new TextComponent
                              {
                                  Text =
                                      new Text(obj.Properties["Text"], Content.Font, 16)
                                      {
                                          Position = new Vector2f(obj.X, obj.Y)
                                      }
                              });
                }
                else if (obj.Name == "Powerup")
                {
                    Powerups.Add(new PowerupObject(new Vector2f(obj.X + obj.Width / 2, obj.Y + obj.Height / 2)));
                }
                else if (obj.Name == "Spawn")
                    Spawn = new Vector2(ConvertUnits.ToSimUnits(obj.X + obj.Width / 2), ConvertUnits.ToSimUnits(obj.Y + obj.Height / 2));
                else if (obj.Name == "Exit")
                    Exit = new ExitObject(new Vector2(ConvertUnits.ToSimUnits(obj.X + obj.Width/2), ConvertUnits.ToSimUnits(obj.Y + obj.Height/2)));
            }
        }
コード例 #6
0
        public AStarSearcher(TmxMap map, Point dest, Point start)
        {
            _map = map;

            // Setup our start and goal here
            _start = new GraphNode(start, null);
            _end = new GraphNode(dest, null);
        }
コード例 #7
0
        public void VersionTest()
        {
            var mapPath = GetAssetPath("minimal.tmx");

            TmxMap map = new TmxMap(mapPath);
            string version = map.Version;
            Assert.AreEqual(version, "1.0");
        }
コード例 #8
0
ファイル: Map.cs プロジェクト: JohnLamontagne/dominus-engine
        public static Map Load(string filePath, ContentManager content)
        {
            Map map = null;

            var tmxMap = new TmxMap(filePath);

            Console.WriteLine("Loading map file: {0}", filePath);

            var layers = new Layer[tmxMap.Layers.Count + tmxMap.ObjectGroups.Count];

            var tilesets = new Tileset[tmxMap.Tilesets.Count];

            // Load the tilesets.
            for (int i = 0; i < tmxMap.Tilesets.Count; i++)
            {
                tilesets[i] = new Tileset(tmxMap.Tilesets[i], content);
            }

            for (int i = 0; i < tmxMap.Layers.Count; i++)
            {
                var tmxLayer = tmxMap.Layers[i];

                var graphicsDevice = (content.ServiceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService).GraphicsDevice;

                var tiles = new Tile[tmxLayer.Tiles.Count];

                for (int b = 0; b < tmxLayer.Tiles.Count; b++)
                {
                    tiles[b] = LoadTile(tmxLayer, tmxLayer.Tiles[b], tilesets, content, graphicsDevice);
                }

                layers[i] = new Layer(tiles, tmxMap.Layers[i].ZOrder);
            }

            MapObjectLoader gameObjectLoader = new MapObjectLoader();
            Layer[] objectLayers = gameObjectLoader.LoadObjectLayers(tmxMap, content);

            // Copy the objectLayers array to the layers array, starting at the first available slot, which is at the end of the tile layers.
            Array.Copy(objectLayers, 0, layers, tmxMap.Layers.Count, objectLayers.Length);

            // Sort the layers properly.
            Array.Sort(layers, (a, b) => a.ZOrder.CompareTo(b.ZOrder));

            map = new Map()
            {
                _layers = layers,
                _size = new Point(tmxMap.Width, tmxMap.Height),
                _spawnInformation = gameObjectLoader
            };

            Console.WriteLine("Finished loading map file: {0}", filePath);

            return map;
        }
コード例 #9
0
        public TiledMapComponent(string mapFile, string tilesetLocation)
        {
            Map = new TmxMap(mapFile);
            Textures = new List<Texture2D>();

            ContentManager Content = EntitySystem.BlackBoard.GetEntry<ContentManager>("ContentManager");
            foreach (var tileset in Map.Tilesets)
            {
                Textures.Add(Content.Load<Texture2D>(tilesetLocation + tileset.Name));
            }
        }
コード例 #10
0
        public void Init(TmxMap tileMap)
        {
            _TileMap = tileMap;
            _width = _TileMap.Width;
            _height = _TileMap.Height;

            if (tiles != null)
                tiles = null;

            SetupMap();
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: wow4all/Walker
    static void Main(string[] args)
    {
      if (args.Length < 2)
      {
        Console.WriteLine("Usage: tmxc source dest");
        return;
      }

      try
      {
        _map = new TmxMap(args[0]);
      }
      catch
      {
        Console.WriteLine($"Failed to open map file '{args[0]}'");
        return;
      }

      var walkerMap = new Map();

      foreach (var tileset in _map.Tilesets)
      {
        var walkerTileset = new Tileset(tileset.Name, tileset.Image.Source)
        {
          Margin = tileset.Margin,
          Spacing = tileset.Spacing,
          TileCount = (int)tileset.TileCount,
          TileWidth = tileset.TileWidth,
          TileHeight = tileset.TileHeight,
          FirstGid = tileset.FirstGid
        };

        foreach (var tile in tileset.Tiles.Where(tile => tile.Properties.Count > 0))
        {
          var entry = new TilePropertyEntry { Id = tile.Id };

          foreach (var kvp in tile.Properties)
            entry.Properties.Add(kvp.Key, kvp.Value);

          walkerTileset.PropertyEntries.Add(entry);
        }

        walkerMap.Tilesets.Add(walkerTileset);
      }

      var dest = args[1] + ".map";

      using (var fs = new FileStream(dest, FileMode.Create))
      using (var writer = new BinaryWriter(fs))
      {
        walkerMap.Write(writer);
      }
    }
コード例 #12
0
ファイル: TmxBuildDirrector.cs プロジェクト: Vlad7/TanksStory
        /// <summary>
        /// This is constructor of TmxBuildDirector
        /// </summary>
        /// <param name="mapName"></param>
        /// <param name="builder"></param>
        public TmxBuildDirrector(String mapName, MapBuilder builder)
        {
            this.tmxName = mapName.Split('.')[0];

            this.tmxMap = new TmxMap(Resources.mapsFolderPath + mapName);

            this.builder = builder;

            this.tmxTilesetsImages = new Dictionary<Int32, ResourceImage>();

            this.tmxAnimations = new Dictionary<Int32, List<ResourceFrame>>();

            LoadImagesFromTilesets(tmxMap.Tilesets);

            LoadAnimationsFromTilesets(tmxMap.Tilesets);
        }
コード例 #13
0
ファイル: Map.cs プロジェクト: cedwards145/ld33
        public Map(string filename)
        {
            map = new TmxMap(filename);
            tileset = Game1.gameRef.Content.Load<Texture2D>("graphics\\" + map.Tilesets[0].Name);
            tileWidth = map.TileWidth;
            tileHeight = map.TileHeight;

            width = map.Width;
            height = map.Height;

            minions = new List<Minion>();
            towers = new List<Tower>();

            generateTiles();

            calculateMinionPath();
        }
コード例 #14
0
ファイル: MapManager.cs プロジェクト: guipaz/stryfe-rpg
        public void LoadMap(string mapName)
        {
            TmxMap tmxMap = new TmxMap(String.Format("Content/Maps/{0}.tmx", mapName));
            currentMap = new Map(tmxMap, mapName);

            // Loads player
            if (currentMap.PlayerReference != null)
            {
                Global.Player = currentMap.PlayerReference;
            }

            // Plays the song
            if (currentMap.song != null)
            {
                AudioManager.Instance.PlaySong(currentMap.song);
            }
        }
コード例 #15
0
ファイル: Map.cs プロジェクト: half-ogre/MonoGameQuest
        public Map(MonoGameQuest game)
            : base(game)
        {
            var tmxMap = new TmxMap(@"Content\map\map.tmx");

            CoordinateHeight = tmxMap.Height;
            CoordinateWidth = tmxMap.Width;

            CoordinateTerminus = new Vector2(
                CoordinateWidth - 1f,
                CoordinateHeight - 1f);

            PixelTileHeight = tmxMap.TileHeight;
            PixelTileWidth = tmxMap.TileWidth;

            _locations = new Dictionary<Vector2, List<int>>();

            foreach (var layer in tmxMap.Layers)
            {
                if (!layer.Visible || layer.Name.Equals("entities", StringComparison.OrdinalIgnoreCase))
                    continue;

                foreach (var tile in layer.Tiles)
                {
                    if (tile.Gid > 0)
                    {
                        var position = new Vector2(tile.X, tile.Y);

                        if (!_locations.ContainsKey(position))
                            _locations.Add(position, new List<int>());

                        _locations[position].Add(tile.Gid);
                    }
                }
            }

            BackgroundColor = new Color(
                r: tmxMap.BackgroundColor.R,
                g: tmxMap.BackgroundColor.G,
                b: tmxMap.BackgroundColor.R);
            UpdateOrder = Constants.UpdateOrder.Map;
        }
コード例 #16
0
        void loadContent(Game1 game, string name = null)
        {

            tileSet = game.Content.Load<Texture2D>(Assets.TILESET);
            if (name == null)
                name = Assets.DATA_TESTROOM_PLATFORM;

            map = new TmxMap(name);
            ExtractObjects();
            collisionMap = CollisionMap.Instance;

            collisionMap.Init(map);


            tileWidth = map.Tilesets[0].TileWidth;
            tileHeight = map.Tilesets[0].TileHeight;

            numTilesWide =  tileSet.Width / tileWidth;
            numTilesHigh = tileSet.Height / tileHeight;

        }
コード例 #17
0
 public TileMap(String path,  Microsoft.Xna.Framework.Content.ContentManager content)
 {
     map = new TmxMap(path);
     tileset = content.Load<Texture2D>(map.Tilesets[0].Name.ToString());
 }
コード例 #18
0
ファイル: Player.cs プロジェクト: takethispie/TimeOut2D
 public override void UpdateCollision(TmxMap currentMap)
 {
     foreach (TmxObject collisionArea in currentMap.ObjectGroups[0].Objects)
     {
         Rectangle collisionRectangle = new Rectangle((int)collisionArea.X, (int)collisionArea.Y, (int)collisionArea.Width, (int)collisionArea.Height);
         Rectangle spriteCollision = sAnimations[currentAnimation][0];
         spriteCollision.X = (int)position.X;
         spriteCollision.Y = (int)position.Y;
         spriteCollision.Y += 24;
         spriteCollision.Height -= 16;
         if (spriteCollision.Intersects(collisionRectangle))
         {
             position = oldPosition;
         }
     }
     oldPosition = position;
 }
コード例 #19
0
ファイル: Game1.cs プロジェクト: jakerose27/Puddle
        protected void LoadMap(string name)
        {
            map = new TmxMap(name);
            background = Content.Load<Texture2D>("background.png");

            // Read Level Info From Map
            graphics.PreferredBackBufferWidth = map.Width * map.TileWidth;
            graphics.PreferredBackBufferHeight = map.Height * map.TileHeight;

            player1.spriteX = Convert.ToInt32(map.Properties["startX"]);
            player1.spriteY = Convert.ToInt32(map.Properties["startY"]);
            player1.checkpointXPos = player1.spriteX;
            player1.checkpointYPos = player1.spriteY;

            // Create new level object
            level = new Level(player1);

            // Create all objects from tmx and place them in level
            foreach (TmxObjectGroup group in map.ObjectGroups)
            {
                foreach (TmxObjectGroup.TmxObject obj in group.Objects)
                {
                    Type t = Type.GetType(obj.Type);
                    Console.WriteLine(obj.Name);
                    object item = Activator.CreateInstance(t, obj);
                    if (item is Enemy)
                        level.enemies.Add((Enemy)item);
                    else
                        level.items.Add((Sprite)item);
                }
            }

            level.items.Sort((x, y) => x.CompareTo(y));

            player1.newMap = "";
            LoadContent();
            newMapLoad = false;
        }
コード例 #20
0
ファイル: Mosaic.cs プロジェクト: marshallward/Tesserae
        public Mosaic(Game gameInput, string mapName)
        {
            // Temporary code
            game = gameInput;
            map = new TmxMap(mapName);
            tMapWidth = map.Width;
            tMapHeight = map.Height;

            // Initialize graphics buffers
            canvas = new Canvas(game);
            renderTarget = new RenderTarget2D(game.GraphicsDevice,
                                              game.GraphicsDevice.Viewport.Width,
                                              game.GraphicsDevice.Viewport.Height);

            // Load spritesheets
            spriteSheet = new Dictionary<TmxTileset, Texture2D>();
            tileRect = new Dictionary<int, Rectangle>();
            idSheet = new Dictionary<int, TmxTileset>();

            foreach (TmxTileset ts in map.Tilesets)
            {
                var newSheet = GetSpriteSheet(ts.Image.Source);
                spriteSheet.Add(ts, newSheet);

                // Loop hoisting
                var wStart = ts.Margin;
                var wInc = ts.TileWidth + ts.Spacing;
                var wEnd = newSheet.Width;

                var hStart = ts.Margin;
                var hInc = ts.TileHeight + ts.Spacing;
                var hEnd = newSheet.Height;

                // Pre-compute tileset rectangles
                var id = ts.FirstGid;
                for (var h = hStart; h < hEnd; h += hInc)
                {
                    for (var w = wStart; w < wEnd; w += wInc)
                    {
                        var rect = new Rectangle(w, h,
                                                 ts.TileWidth, ts.TileHeight);
                        idSheet.Add(id, ts);
                        tileRect.Add(id, rect);
                        id += 1;
                    }
                }

                // Ignore properties for now
            }

            // Load id maps
            layerID = new List<int[,]>();
            foreach (TmxLayer layer in map.Layers)
            {
                var idMap = new int[tMapWidth, tMapHeight];
                foreach (TmxLayerTile t in layer.Tiles)
                {
                    idMap[t.X, t.Y] = t.Gid;
                }
                layerID.Add(idMap);

                // Ignore properties for now
            }
        }
コード例 #21
0
ファイル: Map.cs プロジェクト: GarethIW/LDEngine
        //private Layer collisionLayer;
        // Construct a TiledLib.Map from a TmxReader.map
        public Map(ContentManager content, string mapName)
        {
            string mapPath = AppDomain.CurrentDomain.BaseDirectory +
                "Content/" +
                mapName +
                ".tmx";

            TmxMap tmx = new TmxMap(mapPath);

            Version = new Version(tmx.Version);

            switch(tmx.Orientation)
            {
                case TmxMap.OrientationType.Isometric:
                    Orientation = Orientation.Isometric;
                    break;
                case TmxMap.OrientationType.Orthogonal:
                    Orientation = Orientation.Orthogonal;
                    break;
                case TmxMap.OrientationType.Staggered:
                    throw new Exception(
                        "TiledLib doesn't support maps with Staggered " +
                        "orientation.");
            }

            Width = tmx.Width;
            Height = tmx.Height;
            TileWidth = tmx.TileWidth;
            TileHeight = tmx.TileHeight;

            Properties = new PropertyCollection();
            foreach(KeyValuePair<string, string> kvp in tmx.Properties)
            {
                Properties.Add(kvp);
            }

            // Create a list for our tiles
            List<Tile> tiles = new List<Tile>();
            Tiles = new Collection<Tile>(tiles);

            // Read in each TileSet
            foreach (TmxTileset ts in tmx.Tilesets)
            {
                string tilesetName = ts.Name;
                Texture2D texture = content.Load<Texture2D>(ts.Image.Source);

                bool collisionSet = ts.Properties.ContainsKey("CollisionSet") &&
                    ts.Properties["CollisionSet"] == "True" ?
                    true : false;

                /* TODO:  Add this intelligence to TiledSharp.
                 * If the texture is bigger than a individual tile, infer all the
                 * additional tiles that must be created.
                 */

                if (texture.Width > ts.TileWidth || texture.Height > ts.TileHeight)
                {
                    // Deconstruct tileset to individual tiles
                    int id = 0;
                    for (int y = 0; y < texture.Height / ts.TileHeight; y++)
                    {
                        for (int x = 0; x < texture.Width / ts.TileWidth; x++)
                        {
                            Rectangle source = new Rectangle(
                                x * ts.TileWidth,
                                y * ts.TileHeight,
                                ts.TileWidth,
                                ts.TileHeight
                            );

                            Color[] collisionData = null;
                            bool[] collisionBitData = null;
                            PropertyCollection props = new PropertyCollection();

                            TmxTilesetTile tsTile = ts.Tiles.Find(i => i.Id == id);
                            if(tsTile != null)
                            {
                                foreach (KeyValuePair<string, string> kvp in
                                    tsTile.Properties)
                                {
                                    props.Add(kvp);

                                    // Inherit tilesets collision
                                    bool collidable = collisionSet;
                                    if (kvp.Key == "CollisionSet")
                                    {
                                        // Allow override per tile
                                        if (kvp.Value == "True")
                                        {
                                            collidable = true;
                                        } else
                                        {
                                            collidable = false;
                                        }
                                    }
                                    if (collidable)
                                    {
                                        int numOfBytes = ts.TileWidth * ts.TileHeight;
                                        collisionData = new Color[numOfBytes];
                                        collisionBitData = new bool[numOfBytes];

                                        texture.GetData<Color>(
                                            0,
                                            source,
                                            collisionData,
                                            0,
                                            numOfBytes
                                        );

                                        for (int col = 0; col < numOfBytes; col++)
                                        {
                                            if (collisionData[col].A > 0)
                                            {
                                                collisionBitData[col] = true;
                                            }
                                        }
                                        collisionData = null;
                                    }
                                }
                            }

                            Tile t = new Tile(
                                texture,
                                source,
                                props,
                                collisionBitData
                            );

                            while (id >= tiles.Count)
                            {
                                tiles.Add(null);
                            }
                            tiles.Insert(id + ts.FirstGid, t);
                            id++;
                        }
                    }
                }
            }

            // Process Map Items (layers, objectgroups, etc.)
            List<Layer> layers = new List<Layer>();
            Layers = new Collection<Layer>(layers);

            foreach(TmxLayer l in tmx.Layers)
            {
                Layer layer = null;

                PropertyCollection props = new PropertyCollection();
                foreach(KeyValuePair<string, string> kvp in l.Properties)
                {
                    props.Add(kvp);
                }

                layer = new TileLayer(
                    l.Name,
                    tmx.Width,  // As of TiledQT always same as layer.
                    tmx.Height, // As of TiledQT always same as layer.
                    l.Visible,
                    (float) l.Opacity,
                    props,
                    this,
                    l.Tiles
                );
                layers.Add(layer);
                namedLayers.Add(l.Name, layer);
            }

            foreach(TmxObjectGroup og in tmx.ObjectGroups)
            {
                Layer layer = null;

                PropertyCollection props = new PropertyCollection();
                foreach(KeyValuePair<string, string> kvp in og.Properties)
                {
                    props.Add(kvp);
                }

                List<MapObject> objects = new List<MapObject>();

                // read in all of our objects
                foreach(TmxObjectGroup.TmxObject i in og.Objects)
                {
                    Rectangle objLoc = new Rectangle(
                        i.X,
                        i.Y,
                        i.Width,
                        i.Height
                    );

                    List<Point> objPoints = new List<Point>();
                    if (i.Points != null)
                    {
                        foreach (Tuple<int, int> tuple in i.Points)
                        {
                            objPoints.Add(new Point(tuple.Item1, tuple.Item2));
                        }
                    }

                    PropertyCollection objProps = new PropertyCollection();
                    foreach(KeyValuePair<string, string> kvp in i.Properties)
                    {
                        objProps.Add(kvp);
                    }

                    objects.Add(
                        new MapObject(
                            i.Name,
                            i.Type,
                            objLoc,
                            objPoints,
                            objProps)
                    );
                }

                layer = new MapObjectLayer(
                    og.Name,
                    tmx.Width,
                    tmx.Height,
                    og.Visible,
                    (float) og.Opacity,
                    props,
                    objects
                );

                layers.Add(layer);
                namedLayers.Add(og.Name, layer);
            }
        }
コード例 #22
0
ファイル: TileMap.cs プロジェクト: robert-porter/Jeden
        public TileMap(string mapName, float scale)
        {
            Scale = scale;

            map = new TmxMap(mapName);
            MapWidth = map.Width;
            MapHeight = map.Height;
            TileWidth = map.TileWidth;
            TileHeight = map.TileHeight;
            RenderTiles = new TileMapRenderComponent.Tile[MapWidth, MapHeight];
            PhysicsObjects = new List<PhysicsObject>();
            ParallaxSprites = new List<ParallaxSprite>();

            // Load spritesheets
            spriteSheets = new Dictionary<TmxTileset, Texture>();
            subImageRects = new Dictionary<int, IntRect>();
            idSheet = new Dictionary<int, TmxTileset>();

            foreach (TmxTileset ts in map.Tilesets)
            {
                String filename = Path.GetFileName(ts.Image.Source);

                //Tiled stores the full path name of the tileset
                var newSheet = new Texture("assets/" + filename);
                spriteSheets.Add(ts, newSheet);

                // Loop hoisting
                var wStart = ts.Margin;
                var wInc = ts.TileWidth + ts.Spacing;
                var wEnd = ts.Image.Width / (ts.TileWidth + ts.Spacing); // don't want an ID for a partial tile

                var hStart = ts.Margin;
                var hInc = ts.TileHeight + ts.Spacing;
                var hEnd = ts.Image.Height / (ts.TileHeight + ts.Spacing);

                // Pre-compute sub image rectangles
                var id = ts.FirstGid;
                for (var h = hStart; h < hEnd; h += 1)
                {
                    for (var w = wStart; w < wEnd; w += 1)
                    {
                        var rect = new IntRect();

                        rect.Left = w * wInc;
                        rect.Width = ts.TileWidth;
                        rect.Height = ts.TileHeight;
                        rect.Top = h * hInc;

                        idSheet.Add(id, ts);
                        subImageRects.Add(id, rect);
                        id += 1;
                    }
                }

                // Ignore properties for now
            }

            // Load id maps
            layerID = new List<int[,]>();
            foreach (TmxLayer layer in map.Layers)
            {
                var idMap = new int[MapWidth, MapHeight];
                foreach (TmxLayerTile t in layer.Tiles)
                {

                    idMap[t.X, t.Y] = t.Gid;
                }
                layerID.Add(idMap);

               // if(layer.Name == "tiles")

                // Ignore properties for now
            }

            foreach (TmxObjectGroup objectGroup in map.ObjectGroups)
            {
                if (objectGroup.Name.ToLower().Contains("objects"))
                {
                    ParseCollisionLayer(objectGroup);
                }

                if(objectGroup.Name.ToLower().Contains("parallax"))
                {
                    ParseParallaxLayer(objectGroup);
                }
            }

            ParseTileLayer();
        }
コード例 #23
0
ファイル: Scene.cs プロジェクト: lightofanima/Polys
        /** Initialises the scene from script, loading the required data */
        public void InitialiseFromScript(Table table)
        {
            //Load map
            String tilemapPath = System.IO.Path.Combine("assets/tilemaps/", ScriptManager.retrieveValue(table, "tilemap", "TILEMAP_NOT_SET"));
            if (!System.IO.File.Exists(tilemapPath))
                throw new Exception(String.Format("Error loading \"{0}\". (is the path relative to assets/tilemaps/?)", tilemapPath));
            map = new TmxMap(tilemapPath);
            gridTileWidth = map.TileWidth;
            gridTileHeight = map.TileHeight;

            //Load tilesets
            tilesets = new Video.Tileset[map.Tilesets.Count];
            for (int iTileset = 0; iTileset < tilesets.Length; ++iTileset)
            {
                TmxTileset set = map.Tilesets[iTileset];
                if (set.Margin != 0 || set.Spacing != 0)
                    throw new Exception(String.Format("Tileset {0} must have margin and spacing equal to zero.", set.Name));
                tilesets[iTileset] = new Video.Tileset(set.Image.Source, set.Name, set.TileWidth, set.TileHeight, set.FirstGid);
            }

            //Initialise layers
            layers = new Video.TileLayer[map.Layers.Count];

            for (int iLayer = 0; iLayer < map.Layers.Count; ++iLayer)
            {
              layers[iLayer] = new Video.TileLayer(map.Layers[iLayer], tilesets, map.Width, map.Height, map.TileWidth, map.TileHeight);

                if (map.Layers[iLayer].Name == "collision")
                {
                    collisionLayer = layers[iLayer];
                }
                else if(map.Layers[iLayer].Name == "start")
                {
                    //This is the layer where we want the player to start.
                    startLayerIndex = iLayer;
                }
            }

            //Place the player:
            playerStartPixelX = ScriptManager.retrieveValue(table, "playerStartPixelX", 0);
            playerStartPixelY = (map.Height - 1)*map.TileHeight -ScriptManager.retrieveValue(table, "playerStartPixelY", 0);
        }
コード例 #24
0
ファイル: Layer.cs プロジェクト: sergigandia/Zelda
        public void LoadContent(WorldScreen screen)
        {
            map = new TmxMap("Content/maps/" +mapstring+".tmx");
            Console.WriteLine("Content/maps/" + mapstring + ".tmx");
            tileset = ScreenManager.Instance.Content.Load<Texture2D>("tileset/"+tilesets);
            collisiontex= ScreenManager.Instance.Content.Load<Texture2D>("tileset/kind");
            Tiles = new List<Tile>();
            Polygon d=null;
             List< Point> lite= new List<Point>();

             enemys = new List<Enemy>();
             items = new List<Item>();
            for (var i = 0; i < map.Layers[1].Tiles.Count; i++)
            {
                Tile.Type p=Tile.Type.air;
                int id = map.Layers[1].Tiles[i].Gid;
                if (id == 172)
                {
                    enemys.Add(new Hero.World.Entitys.Enemys.Octorock(new Vector2((int)position.X + map.Layers[1].Tiles[i].X * 16, (int)position.Y + map.Layers[1].Tiles[i].Y * 16),i));

                }
                if (id == 164) p = Tile.Type.air;
                if (id == 163) p = Tile.Type.solid;
                if (id == 168) p = Tile.Type.invisibol;
                if (id == 166)
                {
                    p = Tile.Type.leftd;
                   lite = new List<Point>();
                    lite.Add(new Point(map.Layers[1].Tiles[i].X * 16, map.Layers[1].Tiles[i].Y * 16));
                    lite.Add(new Point((map.Layers[1].Tiles[i].X * 16)+16, map.Layers[1].Tiles[i].Y * 16));
                    lite.Add(new Point((map.Layers[1].Tiles[i].X * 16) +16, (map.Layers[1].Tiles[i].Y * 16)+16));
                    d= new Polygon(lite);
                }
                if (id == 165)
                {
                    p = Tile.Type.rightd;
                   lite = new List<Point>();
                    lite.Add(new Point(map.Layers[1].Tiles[i].X * 16, map.Layers[1].Tiles[i].Y * 16));
                    lite.Add(new Point((map.Layers[1].Tiles[i].X * 16) + 16, map.Layers[1].Tiles[i].Y * 16));
                    lite.Add(new Point((map.Layers[1].Tiles[i].X * 16), (map.Layers[1].Tiles[i].Y * 16) + 16));
                                 d= new Polygon(lite);
                }
                if (d == null)
                {
                    Tile t = new Tile(p,
                        new Rectangle((int)position.X+map.Layers[1].Tiles[i].X * 16, (int)position.Y + map.Layers[1].Tiles[i].Y * 16, 16, 16));
                    Tiles.Add(t);
                }
                else
                {
                    Tile t = new Tile(p,
                     new Rectangle((int)position.X + map.Layers[1].Tiles[i].X * 16, (int)position.Y+ map.Layers[1].Tiles[i].Y * 16, 16, 16), d);
                    Tiles.Add(t);
                }
                lite.Clear();
                d = null;
                //       map.Layers[0].Tiles[i].Gid
            }
             foreach (Enemy e in enemys)
             {
                 e.LoadContent(screen);
             }
        }
コード例 #25
0
ファイル: Content.cs プロジェクト: RobKellett/EdgeCandy
        /// <summary>
        /// Loads all game content for later use.
        /// Should only be called during initialization.
        /// </summary>
        public static void Load()
        {
            Font = new Font("Content/font.ttf");

            CandyCane = new Texture("Content/Sprites/Candy/candy_cane.png");
            chocolates = new[]
                {
                    new Texture("Content/Sprites/Candy/dark_chocolate.png") { Repeated = true },
                    new Texture("Content/Sprites/Candy/milk_chocolate.png") { Repeated = true },
                    new Texture("Content/Sprites/Candy/white_chocolate.png") { Repeated = true }
                };

            DoubleCandyCane = new Texture("Content/Sprites/Candy/double_candy_cane.png");
            Logo = new Texture("Content/Sprites/logo.png");
            MeterBack = new Texture("Content/Sprites/meter_back.png");
            MeterFront = new Texture("Content/Sprites/meter_front.png");
            Noise = new Texture("Content/Sprites/noise.png");
            Player = new Texture("Content/Sprites/player.png");
            Powerup = new Texture("Content/Sprites/powerup.png");

            ranchers = new[]
                {
                    new Texture("Content/Sprites/Candy/rancher_green.png"),
                    new Texture("Content/Sprites/Candy/rancher_purple.png"),
                    new Texture("Content/Sprites/Candy/rancher_red.png"),
                    new Texture("Content/Sprites/Candy/rancher_teal.png")
                };
            Tileset = new Texture("Content/Sprites/tileset.png");

            Music = new Music("Content/Music/CandyRush.ogg") { Loop = true };

            JumpSound = new Sound(new SoundBuffer("Content/Sounds/jump.wav"));
            NoiseSound = new Sound(new SoundBuffer("Content/Sounds/noise.wav"));
            HitSound = new Sound(new SoundBuffer("Content/Sounds/hit.wav"));
            PowerupSound = new Sound(new SoundBuffer("Content/Sounds/powerup.wav"));
            ShatterSound = new Sound(new SoundBuffer("Content/Sounds/shatter.wav"));
            SliceSound = new Sound(new SoundBuffer("Content/Sounds/slice.wav"));

            TestMap = new TmxMap("Content/Levels/test.tmx");
            Level = new TmxMap("Content/Levels/level.tmx");

            var image = new Image(1, 1, Color.White);
            Pixel = new Texture(image);
        }
コード例 #26
0
ファイル: MapData.cs プロジェクト: bradur/LD33
    public void Init(TextAsset mapFile, Material tileSheet, Material wallMaterial)
    {
        foreach (Transform child in tileContainer)
        {
            DestroyObject(child.gameObject);
        }
        foreach (Transform child in objectContainer)
        {
            DestroyObject(child.gameObject);
        }
        TmxMap map;

        map = new TmxMap(mapFile.text, "rnd");
        this.wallMaterial = wallMaterial;

        horizontal_tiles = map.Width;
        vertical_tiles = map.Height;

        tile_width = map.TileWidth;
        tile_height = map.TileHeight;

        //tileSetName = map.Tilesets[0].Name;
        firstGids = new int[map.Tilesets.Count];
        mapTitle = map.Properties["Title"];
        time = IntParseFast(map.Properties["Time"]);
        villains = IntParseFast(map.Properties["Villain"]);
        gold = IntParseFast(map.Properties["Gold"]);
        timer.Init(time);

        tileMap = new Map(map.Width, map.Height);

        if (map.Layers.Count > 0)
        {
            GenerateTiles(map.Layers);
            mapDebug.text = tileMap.PrintableString();
        }

        if (map.ObjectGroups.Count > 0)
        {
            GenerateObjects(map.ObjectGroups);
        }
        hero.SetEndSpot(endX, endY);

        foreach (Transform child in tempContainer)
        {
            DestroyObject(child.gameObject);
        }
        manager.MapGenerationCallBack(this);
    }
コード例 #27
0
ファイル: LevelRenderer.cs プロジェクト: yaegerbomb/TwoDECS
        public void ImportTMX(ContentManager content, string filepath, int tilesize, SpriteFont font, PlayingState playingState)
        {
            TileMap = new TileMap();

            var map = new TmxMap(filepath);
            TileMap.RowCount = map.Width;
            TileMap.ColumnCount = map.Height;


            //get and set tile map details
            var tileMap = map.Tilesets["Basic"];
            CreateTileMap(tileMap);

            //get and set level layer
            var levelLayer = map.Layers["Level"];
            CreateTileArray(levelLayer);

            //get and set level bounding rects
            var boudingRects = map.ObjectGroups["Level Rects"].Objects;
            CreateBoundingRects(boudingRects, playingState);

            //get and set player spawn
            var playersSpawn = map.ObjectGroups["Player Spawn"].Objects;
            CreatePlayerSpawn(playersSpawn, playingState);

            //get and set enemy spawns
            var enemySpawns = map.ObjectGroups["Enemy Spawns"].Objects;
            CreateEnemySpawns(enemySpawns, playingState);

            this.Font = font;
        }      
コード例 #28
0
        static bool ConvertMap(string name)
        {
            Console.WriteLine("Converting map:\t" + name);

            var importMap = new TiledSharp.TmxMap(name);

            ShadowFileElement map = new ShadowFileElement();

            map.isBlock = true;
            map.name    = "ASDASD";

            map.AddProperty("Width", importMap.Width.ToString());
            map.AddProperty("Height", importMap.Height.ToString());

            map.AddProperty("TileWidth", importMap.TileWidth.ToString());
            map.AddProperty("TileHeight", importMap.TileHeight.ToString());

            ShadowFileElement layers = new ShadowFileElement();

            layers.name    = "Layers";
            layers.isBlock = true;

            foreach (var layer in importMap.Layers)
            {
                ShadowFileElement layerElement = new ShadowFileElement();
                layerElement.isBlock = true;

                layerElement.name = layer.Name;
                layerElement.AddProperty("Visible", layer.Visible.ToString());

                if (layer is TmxLayer tilelayer)
                {
                    string data = "";
                    for (int i = 0; i < tilelayer.Tiles.Count; i++)
                    {
                        data += tilelayer.Tiles[i].Gid;
                        if (i != tilelayer.Tiles.Count - 1)
                        {
                            data += ".";
                        }
                    }


                    layerElement.AddProperty("map", data);
                }

                layers.AddProperty(layerElement);
            }

            map.AddProperty(layers);


            string destFile = name;

            destFile = destFile.Replace(".tmx", ".sef");
            destFile = destFile.Replace(oldValue: ".tmx", newValue: ".sef");

            ShadowFileFormat.WriteFile(map, destFile);

            return(true);
        }
コード例 #29
0
ファイル: Map.cs プロジェクト: borealwinter/myrpg
        /// <summary>
        /// Loads the tmx file
        /// </summary>
        /// <param name="mapName">name of tmx file without the extension</param>
        private static void loadTmxMap(string mapName)
        {
            string name = String.Concat(mapName, ".tmx");
            _map = new TmxMap(Path.Combine(Settings.ContentFolder, "../../../../", "maps", name));
            _tileset = Settings.Content.Load<Texture2D>(_map.Tilesets[0].Name.ToString());
            _sizex = _map.Width;
            _sizey = _map.Height;
            _tiles = new List<Rectangle>();
            _tiles.Add(new Rectangle(0, 0, 0, 0));
            var tileSetSize = (_tileset.Width / Settings.TileSize) * (_tileset.Height / Settings.TileSize);

            for (int i = 0; i < tileSetSize; i++)
            {
                int x = (i % (_tileset.Width / Settings.TileSize)) * Settings.TileSize;
                int y = (i / (_tileset.Width / Settings.TileSize)) * Settings.TileSize;

                _tiles.Add(new Rectangle(x, y, Settings.TileSize, Settings.TileSize));
            }

            _numBackgroundLayers = (from TmxLayer background in _map.Layers
                                    where background.Name.ToLower().Contains("background")
                                    select background).Count();

            _numForegroundLayers = (from TmxLayer foreground in _map.Layers
                                    where foreground.Name.ToLower().Contains("foreground")
                                    select foreground).Count();

            _numLayers = _numBackgroundLayers + _numForegroundLayers + 1;

            _objectGroups = (from TmxObjectGroup objectGroup in _map.ObjectGroups
                             select objectGroup).ToList();

            _objects = new List<MapObject>();
            int j = 0;
            foreach (TmxObjectGroup objectGroup in _objectGroups)
            {
                if (objectGroup.Name == _BarrierObjects)
                {
                    foreach (TmxObject obj in objectGroup.Objects)
                    {
                        Boundary b = new Boundary((float)obj.X, (float)obj.Y, (int)obj.Width, (int)obj.Height);
                        b.Name = String.Concat(_BarrierObjects, j.ToString());
                        _objects.Add(b);

                        if (showBoundaries)
                        {
                            if (visibleBoundaries == null)
                            {
                                visibleBoundaries = new List<Texture2D>();
                            }
                            visibleBoundaries.Add(Settings.CreateTexture(
                                new Rectangle((int)obj.X, (int)obj.Y, (int)obj.Width, (int)obj.Height),
                                new Color(1f, 0f, 0f, 0.5f)));
                        }
                    }
                }
            }

            Settings.MapSize = new Vector2(_map.Width * 32, _map.Height * 32);

            IsScrollable = (_map.Width > 20 || _map.Height > 15) ? true : false;

            _offset = new Vector2(0f, 0f);

            player = new Avatar();
            player.Direction = Facing.East;
            player.State = PersonState.Walking;
            player.Speed = 10;
            player.Tint = Color.White;
            //player.Position = new Vector2(600, 600);
            player.Position = new Vector2(76, 200);
            player.Name = "Albert";
            //player.ScreenPosition = new Vector2(125, 125);

            npc1 = new NPCPerson("brunette00", 1);
            npc1.Direction = Facing.South;
            npc1.State = PersonState.Standing;
            npc1.Tint = Color.White;
            npc1.Speed = 9;
            npc1.MoveScript = 1;
            npc1.Name = "npc1";
            //npc1.BoundingBox = new Rectangle(0, 0, 48, 64);
            //Rectangle r = new Rectangle(0, 0, npc1.BoundingBoxWidth, npc1.BoundingBoxHeight);
            //npcBounds = Settings.CreateTexture(r, new Color(0f, 0.1f, 1f, 0.3f));
            npc1.Position = new Vector2(400, 200);

            npc2 = new NPCPerson("siriusboss", 3);
            npc2.Direction = Facing.South;
            npc2.State = PersonState.Standing;
            npc2.Tint = Color.White;
            npc2.Speed = 9;
            npc2.MoveScript = 1;
            npc2.Position = new Vector2(300, 300);
            npc2.Name = "npc2";
            _objects.Add(player);
            _objects.Add(npc1);
            _objects.Add(npc2);

            font = Settings.Content.Load<SpriteFont>("ExFont");
        }
コード例 #30
0
ファイル: Map.cs プロジェクト: borealwinter/myrpg
 /// <summary>
 /// Unloads resources
 /// </summary>
 public static void Unload()
 {
     _map = null;
     _tileset = null;
     _tiles.Clear();
     _tiles = null;
     Settings.Content.Unload();
     GC.Collect();
 }
コード例 #31
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 = new TmxMap("Content/exampleMap.tmx");
            tileset = Content.Load<Texture2D>(map.Tilesets[0].Name.ToString());

            tileWidth = map.Tilesets[0].TileWidth;
            tileHeight = map.Tilesets[0].TileHeight;

            tilesetTilesWide = tileset.Width / tileWidth;
            tilesetTilesHigh = tileset.Height / tileHeight;
        }