public static void ReadTilesets(TiledMap map, XElement root) { foreach (var tilesetElement in root.GetElements("tileset")) { var tileset = new TiledTileset(); // Read mandatory attributes. tileset.FirstId = tilesetElement.ReadAttribute("firstgid", 0); tileset.Name = tilesetElement.ReadAttribute("name", String.Empty); tileset.TileWidth = tilesetElement.ReadAttribute("tilewidth", 0); tileset.TileHeight = tilesetElement.ReadAttribute("tileheight", 0); // Read optional attributes. tileset.Spacing = tilesetElement.ReadAttribute("spacing", 0); tileset.Margin = tilesetElement.ReadAttribute("margin", 0); // Read the tileset image. tileset.Image = ReadImage(tilesetElement); // Read the tileset offset. var offset = ReadTileOffset(tilesetElement); tileset.OffsetX = offset.Item1; tileset.OffsetY = offset.Item2; // Read tile metadata. var tileMetadata = ReadTilesetMetadata(tilesetElement); if (tileMetadata.Count > 0) { tileset.Tiles.AddRange(tileMetadata); } // Add the tileset to the map. map.Tilesets.Add(tileset); } }
protected override void LoadContent() { map = new TiledMap(Content, "Content/HacksoiContent/test.tmx", "HacksoiContent/"); graphics.PreferredBackBufferWidth = map.Map.Width * map.Map.TileWidth; graphics.PreferredBackBufferHeight = map.Map.Height * map.Map.TileHeight; graphics.ApplyChanges(); centerWindow(); cameraPosition = Vector2.Zero; screenCenter = new Vector2(graphics.GraphicsDevice.Viewport.Width / 2f, graphics.GraphicsDevice.Viewport.Height / 2f); batch = new SpriteBatch(graphics.GraphicsDevice); basicEffect = new BasicEffect(graphics.GraphicsDevice); basicEffect.Projection = Matrix.CreateOrthographic(graphics.GraphicsDevice.Viewport.Width, -graphics.GraphicsDevice.Viewport.Height, 0.1f, 1000f); basicEffect.View = Matrix.Identity; basicEffect.World = Matrix.Identity; basicEffect.TextureEnabled = true; rasterizerState = new RasterizerState(); rasterizerState.CullMode = CullMode.None; font = Content.Load<SpriteFont>("Font"); LoadWorld(); }
public TiledMapComponent( TiledMap tiledmap, string collisionLayerName = null ) { this.tiledMap = tiledmap; if( collisionLayerName != null ) collisionLayer = tiledmap.getLayer<TiledTileLayer>( collisionLayerName ); }
public TiledMapComponent( TiledMap tiledMap, string collisionLayerName = null, bool shouldCreateColliders = true ) { this.tiledMap = tiledMap; _shouldCreateColliders = shouldCreateColliders; if( collisionLayerName != null ) collisionLayer = tiledMap.getLayer<TiledTileLayer>( collisionLayerName ); }
public static void ReadHeader(TiledMap map, XElement root) { map.Version = Version.Parse(root.ReadAttribute("version", "1.0")); map.Orientation = root.ReadAttribute("orientation", string.Empty); map.Width = root.ReadAttribute("width", 0); map.Height = root.ReadAttribute("height", 0); map.TileWidth = root.ReadAttribute("tilewidth", 0); map.TileHeight = root.ReadAttribute("tileheight", 0); map.BackgroundColor = ColorTranslator.FromHtml(root.ReadAttribute("backgroundcolor", string.Empty)); }
public TiledTileLayer( TiledMap map, string name, int width, int height, TiledTile[] tiles ) : base(name) { this.width = width; this.height = height; this.tiles = tiles; tiledMap = map; tiles = populateTilePositions(); }
protected override void LoadContent() { _spriteBatch = new SpriteBatch(GraphicsDevice); _bitmapFont = Content.Load <BitmapFont>("Fonts/courier-new-32"); _tiledMap = Content.Load <TiledMap>("Tilesets/level01"); _world = new CollisionWorld(new Vector2(0, 900)); _world.CreateGrid(_tiledMap.GetLayer <TiledTileLayer>("Tile Layer 1")); var zombieAnimator = Content.Load <SpriteSheetAnimator>("Sprites/zombie-animations"); _zombie = new Zombie(zombieAnimator); var zombieActor = _world.CreateActor(_zombie); zombieActor.Position = new Vector2(462.5f, 896f); }
public Pathfinder(TiledMap tilemap) { _tilemap = tilemap; var layer = tilemap.getLayer <TiledTileLayer>("main"); _start = new Point(1, 1); _end = new Point(10, 10); _gridGraph = new UnweightedGridGraph(layer); _breadthSearchPath = _gridGraph.search(_start, _end); _astarGraph = new WeightedGridGraph(layer); _astarSearchPath = _astarGraph.search(_start, _end); Debug.drawTextFromBottom = true; }
/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { //Added code player = new Player("test/Luigi"); map = Level.loadLevel(this, "levels/test"); tmr = new TiledMapRenderer(GraphicsDevice); camera = new Camera2D(); /* * testCollisions = new Collision[20]; * for (int i = 0; i < 20; i++) * testCollisions[i] = new Collision(); */ base.Initialize(); }
public override void Initialize() { TiledMap tiledStoryScreen = new TiledMap(MainConfig.CONTENT_MAP_DIRECTORY + "Story.xml", director.Content, MainConfig.PIPELINE_GRAPHICS_DIRECTORY, scene); BaseScreenSize = tiledStoryScreen.MapSize; for (var i = 0; i < 4; i++) { if (!selectedPlayers[i]) { continue; } var player = new Player((PlayerIndex)i, new MenuInputMapper(true)); scene.RegisterPlayer(player); } }
internal TiledMapLayerAnimatedModel(ContentReader reader, TiledMap map) : base(reader, true) { var tilesetFirstGlobalIdentifier = reader.ReadInt32(); var tileset = map.GetTilesetByTileGlobalIdentifier(tilesetFirstGlobalIdentifier); var animatedTilesetTileCount = reader.ReadInt32(); AnimatedTilesetTiles = new TiledMapTilesetAnimatedTile[animatedTilesetTileCount]; for (var i = 0; i < animatedTilesetTileCount; i++) { var tileLocalIdentifier = reader.ReadInt32(); AnimatedTilesetTiles[i] = tileset.GetAnimatedTilesetTileByLocalTileIdentifier(tileLocalIdentifier); } }
public static void PoblateCoins(TiledMap til, Scene sceneP) { var texture = sceneP.content.Load <Microsoft.Xna.Framework.Graphics.Texture2D>("Assets/Interactuables/Coin 32x32"); int iterator = 0; var objectLayer = til.getObjectGroup("Eventos"); foreach (var coin in objectLayer.objectsWithName("Moneda")) { var Monedas = sceneP.createEntity("Monedas" + iterator); Monedas.addComponent(new Sprite(texture)); Monedas.transform.setPosition(coin.position); Monedas.addComponent(new BoxCollider(-16f, -16f, 32f, 32f)); Monedas.addComponent(new CollectableController(til, sceneP.findEntity("player"))); iterator++; } }
public override void initialize() { clearColor = Color.CornflowerBlue; var renderer = addRenderer(new DefaultRenderer()); tiledMap = content.Load <TiledMap>("test"); var tiledEntity = this.createEntity("debugMap"); var tiledMapComponent = tiledEntity.addComponent(new TiledMapComponent(tiledMap, "collision")); tiledMapComponent.setLayersToRender("collision"); collisionLayer = tiledMapComponent.collisionLayer; var offscreenColliders = addEntity(new Entity()); offscreenColliders.addComponent(new BoxCollider(-32, 112, 32, 32)); offscreenColliders.addComponent(new BoxCollider(256, 112, 32, 32)); }
public void LoadContent() { Map = new TiledMap(this, "/dungeon.json"); Camera = new Camera(graphics); player = new Player(this); Shaker = new ScreenShaker(); Map.LoadContent(); player.LoadContent(); entities.Add(player); gameTheme = CM.Load <Song>("hero_immortal"); MediaPlayer.Volume = 0.05f; MediaPlayer.IsRepeating = true; MediaPlayer.Play(gameTheme); }
public TiledMapRenderer(GraphicsDevice graphicsDevice, TiledMap map = null) { if (graphicsDevice == null) { throw new ArgumentNullException(nameof(graphicsDevice)); } _graphicsDevice = graphicsDevice; _defaultEffect = new TiledMapEffect(graphicsDevice); _mapModelBuilder = new TiledMapModelBuilder(graphicsDevice); if (map != null) { LoadMap(map); } }
protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here player.Load(Content); LoadEmitter(); arialFont = Content.Load <SpriteFont>("Arial"); heart = Content.Load <Texture2D>("Heart"); var viewportAdapter = new BoxingViewportAdapter(GraphicsDevice, viewWidth, viewHeight); camera = new Camera2D(viewportAdapter); camera.Position = new Vector2(0, ScreenHeight / 2); map = Content.Load <TiledMap>("PLS"); foreach (TiledTileLayer layer in map.TileLayers) { if (layer.Name == "Collisions") { collisionLayer = layer; } } map = Content.Load <TiledMap>("PLS"); foreach (TiledTileLayer layer in map.TileLayers) { if (layer.Name == "KillTiles") { killLayer = layer; } } // game music gameMusic = Content.Load <Song>("SuperHero_violin_no_Intro"); MediaPlayer.Play(gameMusic); //loading enemies LoadAllEnemies(); //loading items LoadAllCoins(); }
/// <summary> /// TODO: Function under construction /// </summary> /// <param name="tileID">Tile I.</param> /// <param name="map">Map.</param> /// <param name="tileObject">Tile object.</param> private void AttachTileProperties(int tileID, TiledMap map, GameObject tileObject) { for (int i = 0; i < map.tileSets.Length; i++) { TiledTileSetFile tSet = map.tileSets[i]; if (tSet.image == null) { //for single images foreach (TiledTile tile in tSet.tiles) { if (tile.id + map.tileSetEntries[i].firstGID == tileID) { if (tile.customProperties != null && tile.customProperties.Length > 0) { Tile3D tileScript = tileObject.AddComponent <Tile3D>(); for (int j = 0; j < tile.customProperties.Length; j++) { string pName = tile.customProperties[j].name.ToLower(); string pValue = tile.customProperties[j].value; if (pName.Equals("generatecollider")) { bool gen; if (bool.TryParse(pValue, out gen)) { tileScript.generateCollider = gen; } } else if (pName.Equals("minrandomdisplacement") || pName.Equals("maxrandomdisplacement")) { /* * float x, y, z; * Vector3 displacement; * string[] vals = pValue.Split(','); * if (vals.Length == 3) * { * //TODO: continue from here * } */ } } } } } } } }
protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); heroUp_Sprite = Content.Load <Texture2D>("Hero/hero-back-walk"); heroDown_Sprite = Content.Load <Texture2D>("Hero/hero-walk-front"); heroSide_Sprite = Content.Load <Texture2D>("Hero/hero-walk-side"); heroIdleUp_Sprite = Content.Load <Texture2D>("Hero/hero-idle-back"); heroIdleDown_Sprite = Content.Load <Texture2D>("Hero/hero-idle-front"); heroIdleSide_Sprite = Content.Load <Texture2D>("Hero/hero-idle-side"); player.animWalkUp = new AnimatedSprite(heroUp_Sprite, 1, 6); player.animWalkDown = new AnimatedSprite(heroDown_Sprite, 1, 6); player.animWalkSide = new AnimatedSprite(heroSide_Sprite, 1, 6); player.animIdleUp = new AnimatedSprite(heroIdleUp_Sprite, 1, 1); player.animIdleDown = new AnimatedSprite(heroIdleDown_Sprite, 1, 1); player.animIdleSide = new AnimatedSprite(heroIdleSide_Sprite, 1, 1); skeletonAttack_Sprite = Content.Load <Texture2D>("Skeleton/Skeleton Attack"); skeletonDead_Sprite = Content.Load <Texture2D>("Skeleton/Skeleton Dead"); skeletonHit_Sprite = Content.Load <Texture2D>("Skeleton/Skeleton Hit"); skeletonIdle_Sprite = Content.Load <Texture2D>("Skeleton/Skeleton Idle"); skeletonReact_Sprite = Content.Load <Texture2D>("Skeleton/Skeleton React"); skeletonWalk_Sprite = Content.Load <Texture2D>("Skeleton/Skeleton Walk"); //my monster monster.animAttack = new AnimatedSprite(skeletonAttack_Sprite, 1, 18); monster.animDead = new AnimatedSprite(skeletonDead_Sprite, 1, 15); //monster.animReact = new AnimatedSprite(skeletonReact_Sprite, 1, 4); monster.animWalkSide = new AnimatedSprite(skeletonWalk_Sprite, 1, 13); monster.animHit = new AnimatedSprite(skeletonHit_Sprite, 1, 8); monster.animIdleSide = new AnimatedSprite(skeletonIdle_Sprite, 1, 11); //enemy monster EnemyMonster.EnemyMonsters.Add(enemyMonster); enemyMonster.animAttack = new AnimatedSprite(skeletonAttack_Sprite, 1, 18); enemyMonster.animDead = new AnimatedSprite(skeletonDead_Sprite, 1, 15); //monster.animReact = new AnimatedSprite(skeletonReact_Sprite, 1, 4); enemyMonster.animWalkSide = new AnimatedSprite(skeletonWalk_Sprite, 1, 13); enemyMonster.animHit = new AnimatedSprite(skeletonHit_Sprite, 1, 8); enemyMonster.animIdleSide = new AnimatedSprite(skeletonIdle_Sprite, 1, 11); //maps firstMap = Content.Load <TiledMap>("Maps/firstMap"); }
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); } }
private byte PanMapController() { TiledMap tiledMap = TiledMap.Instance; switch (movementData) { case 1: tiledMap.SetTile(new Tile { X = TiledMap.Tile.X, Y = TiledMap.Tile.Y - 1, Zoom = TiledMap.Tile.Zoom }); //north break; case 2: tiledMap.SetTile(new Tile { X = TiledMap.Tile.X, Y = TiledMap.Tile.Y + 1, Zoom = TiledMap.Tile.Zoom }); //south break; case 3: tiledMap.SetTile(new Tile { X = TiledMap.Tile.X + 1, Y = TiledMap.Tile.Y, Zoom = TiledMap.Tile.Zoom }); //east break; case 4: tiledMap.SetTile(new Tile { X = TiledMap.Tile.X - 1, Y = TiledMap.Tile.Y, Zoom = TiledMap.Tile.Zoom }); //west break; default: break; } return(0); }
/// <summary> /// LoadContent will be called once per game to load all content. /// </summary> protected override void LoadContent() { camera = new Camera2D(GraphicsDevice); spriteBatch = new SpriteBatch(GraphicsDevice); map = Content.Load <TiledMap>("Tilesets\\testmap"); player.texture = Content.Load <Texture2D>("Graphics\\player"); player.position.X = 256; player.position.Y = map.HeightInPixels; camera.ZoomIn(2f); cameraTarget = new RectangleF(player.position.X - (cameraTarget.Width / 2), player.position.Y - (cameraTarget.Height / 2), 0.1f * WINDOW_WIDTH, 0.1f * WINDOW_HEIGHT); // TODO: figure out why it's 0.1f camera.LookAt(cameraTarget.Center); }
private void initTiledMap() { var tiledEntity = createEntity("tiledMap"); tiledMap = content.Load <TiledMap>("TileMaps/Maps/DongZhuang/cave2"); var tiledMapComponent = tiledEntity.addComponent(new TiledMapComponent(tiledMap)); tiledMapComponent.setLayersToRender(new string[] { "Tiled", "Wall" }); tiledMapComponent.setRenderLayer(GameLayerSetting.tiledLayer); var tileMapUpPlayerComponent = tiledEntity.addComponent(new TiledMapComponent(tiledMap)); tileMapUpPlayerComponent.setLayersToRender(new string[] { "UpPlayer" }); tileMapUpPlayerComponent.setRenderLayer(GameLayerSetting.tiledActorUpLayer).setLayerDepth(LayerDepthExt.caluelateLayerDepth(210)); createMapCollision(tiledMap, "Collision"); }
private static void OnChangeScene(object sender, ChangeSceneEventArgs e) { TextAsset progressFile = Engine.AssetLoader.Get <TextAsset>("progress.json"); TextAsset nextRoom = Engine.AssetLoader.Get <TextAsset>(e.NextScenePath); // Read tmx map file and create a TiledMap TextAsset tmxMap = Engine.AssetLoader.Get <TextAsset>("Rooms/3x2.tmx"); XMLReader reader = new XMLReader(tmxMap.Content); TiledMap tiledMap = new TiledMap(reader); MainScene scene = new MainScene(progressFile, nextRoom, tiledMap); GameContext.Scene = scene; scene.ChangeSceneEvent += OnChangeScene; Engine.SceneManager.SetScene(scene); }
/// <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); // TODO: use this.Content to load your game content here player.Load(Content); var viewportAdapter = new BoxingViewportAdapter(Window, GraphicsDevice, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height); camera = new Camera2D(viewportAdapter); camera.Position = new Vector2(0, graphics.GraphicsDevice.Viewport.Height); map = Content.Load <TiledMap>("Level1"); }
static public TiledMap FromFile(string file) { TiledMap map = null; string jsonString; bool errCode = IOTools.LoadTextFromFile(file, out jsonString); if (jsonString == null || jsonString.Length <= 0) { Debug.LogAssertion("Can't open json file: " + file); } else { map = JsonUtility.FromJson <TiledMap> (jsonString); map.Init(); } return(map); }
private void initTiledMap() { var tiledEntity = createEntity("tiledMap"); tiledMap = content.Load <TiledMap>("TileMaps/Maps/DongZhuang/DongZhuangVillage"); var tiledMapComponent = tiledEntity.addComponent(new TiledMapComponent(tiledMap)); tiledMapComponent.setLayersToRender(new string[] { "Tiled", "Tree", "Room" }); tiledMapComponent.setRenderLayer(GameLayerSetting.tiledLayer); var tileMapUpPlayerComponent = tiledEntity.addComponent(new TiledMapComponent(tiledMap)); tileMapUpPlayerComponent.setLayersToRender(new string[] { "UpPlayer" }); tileMapUpPlayerComponent.setRenderLayer(GameLayerSetting.tiledActorUpLayer); createMapCollision(tiledMap, "Collision"); }
public ObjectInteractor(Scene scene, TiledMap map, int numObjLayers) : base() { this.scene = scene; //Add all the objects from every object layer List <TiledObjectGroup> objLayers = new List <TiledObjectGroup>(); for (int i = 0; i < numObjLayers; i++) { int num = i + 1; string layerName = "ObjLayer" + num.ToString(); objLayers.Add(map.getObjectGroup(layerName)); } //Setup the parser for the objects this.objParser = new ObjectParser(scene, map, objLayers); }
/// <summary> /// Adds a random slope to the map. /// </summary> /// <param name="map">The map.</param> /// <param name="intensity">Intensity of the slope (1 meaning that the diagonal length of the map is equal to the maximum increase of the map, <1 will have a lesser influence, and >1 will have a greater).</param> /// <param name="random">The random engine to use.</param> public static void AddSlope(TiledMap map, float intensity, System.Random random) { float a = random.Next(-100, 100) / 100f; float b = random.Next(-100, 100) / 100f; float increase = Mathf.Sqrt((float)(map.width + map.length)) * intensity; // Debug.Log("a, b : "+ a + ", " + b); for (int i = 0; i < map.width; i++) { for (int j = 0; j < map.length; j++) { map.tiles[i, j].height += (a * i + b * j) * increase; } } }
public static void ReadLayers(TiledMap map, XElement root) { string[] layerTypes = { "layer", "objectgroup" }; var elements = root.Elements().Where(e => layerTypes.Contains(e.Name.LocalName, StringComparer.OrdinalIgnoreCase)); foreach (XElement element in elements) { string layerType = element.Name.LocalName; if (layerType.Equals("layer", StringComparison.OrdinalIgnoreCase)) { ReadTileLayer(map, element); } else if (layerType.Equals("objectgroup", StringComparison.OrdinalIgnoreCase)) { ReadObjectGroup(map, element); } } }
public void LoadContent(ContentManager contentManager) { if (MapName == null) { throw new ArgumentNullException("The MapName may not be null"); } map = contentManager.Load <TiledMap>(MapName); var maxCount = 1; foreach (var set in map.Tilesets) { maxCount += set.Tilecount; } spriteTextures = new Texture2D[maxCount]; spritePosition = new Rectangle[maxCount]; foreach (var set in map.Tilesets) { for (int i = 0; i < set.Tilecount; i++) { var rec = new Rectangle(); var y = (int)Math.Floor(((decimal)i / (decimal)set.Columns)); var x = i % set.Columns; rec.X = x * set.TileWidth + x * set.Spacing + set.Margin; rec.Y = y * set.TileHeight + y * set.Spacing + set.Margin; rec.Width = set.TileWidth; rec.Height = set.TileHeight; spritePosition[set.FirstGid + i] = rec; spriteTextures[set.FirstGid + i] = set.Image.SpriteTexture; } } MapWidth = map.Width; MapHeight = map.Height; TileWidth = map.TileWidth; TileHeight = map.TileHeight; }
private void ProcessGroup(TiledGroup group, TiledMap map) { foreach (var layer in group.Layers) { ProcessLayer(layer, map); _depth++; } foreach (var objectGroup in group.Objects) { ProcessObjectGroup(objectGroup); } foreach (var child in group.Groups) { ProcessGroup(child, map); } }
private TiledObjectGroup GetObjectsGroup(TiledMap map, int tileId) { for (int i = 0; i < map.tileSets.Length; i++) { TiledTileSetFile tsFile = map.tileSets[i]; if (tsFile.tiles != null) { foreach (TiledTile tile in tsFile.tiles) { if (tile.id + map.tileSetEntries[i].firstGID == tileId) { return(tile.objectsGroup); } } } } return(null); }
protected override void LoadContent() { _spriteBatch = new SpriteBatch(GraphicsDevice); _backgroundTexture = Content.Load <Texture2D>("hills"); _bitmapFont = Content.Load <BitmapFont>("courier-new-32"); var textureAtlas = Content.Load <TextureAtlas>("test-tileset-atlas"); var textureRegion = textureAtlas.Regions.First(); _textureRegion = textureAtlas.Regions.Last(); _sprite = new Sprite(textureRegion) { Position = new Vector2(600, 240), Scale = Vector2.One * 2.5f, OriginNormalized = new Vector2(0.25f, 0.75f) }; _tiledMap = Content.Load <TiledMap>("level01"); }
private ushort[][] Fill2DMap(List <uint> tiles, uint width, uint height, TiledMap baseMap) { ushort[][] output = new ushort[height][]; for (int y = 0; y < height; ++y) { output[y] = new ushort[width]; for (int x = 0; x < width; ++x) { uint tile = tiles[(int)(y * width + x)].TileGetRelativeId(baseMap.TilesetDefinitions, Context); if (tile > 0xFFFF) { Context.ExitError("relative tile id is too big for output map: {0}", tile); } output[y][x] = (ushort)(tile); } } return(output); }
protected override void Initialize() { // TODO: Add your initialization logic _graphics.PreferredBackBufferWidth = 1280; _graphics.PreferredBackBufferHeight = 720; _graphics.ApplyChanges(); map = Content.Load <TiledMap>("test"); _mapRenderer = new TiledMapRenderer(GraphicsDevice, map); var viewportadapter = new BoxingViewportAdapter(Window, GraphicsDevice, 400, 400); camera = new OrthographicCamera(viewportadapter); camera.LookAt(new Vector2(0, 0)); _cameraMovement = new CameraMovement(); base.Initialize(); }
public void LayerAccessTest() { var map = new TiledMap("test.tmx"); Assert.IsNotNull(map.Layers[0] as TiledTileLayer); Assert.IsNotNull(map.Layers[1] as TiledObjectGroup); Assert.IsNotNull(map.Layers[2] as TiledTileLayer); Assert.IsNotNull(map["Background"] as TiledTileLayer); Assert.IsNotNull(map["Middleground"] as TiledObjectGroup); Assert.IsNotNull(map["Foreground"] as TiledTileLayer); map["Middleground"] = new TiledTileLayer { Name = "Middleground" }; Assert.IsNotNull(map["Middleground"]); }
private TiledTileset GetTilesetFromGid(TiledDataTile tile, TiledMap map) { var current = map.Tilesets.First(); for (var i = 1; i < map.Tilesets.Count; i++) { if (map.Tilesets[i].FirstGid <= tile.Gid) { current = map.Tilesets[i]; } else { break; } } return(current); }
/// <summary> /// returns the bounds Rectangle of the passed in tile /// </summary> /// <returns>The bounds for tile.</returns> /// <param name="tile">Tile.</param> /// <param name="tilemap">Tilemap.</param> public static Rectangle getBoundsForTile( TiledTile tile, TiledMap tilemap ) { return new Rectangle( tile.x * tilemap.tileWidth, tile.y * tilemap.tileHeight, tilemap.tileWidth, tilemap.tileHeight ); }
public void Build(TiledMap tiledMap, string tilesetName, bool collisions=true) { _width = tiledMap.width; _height = tiledMap.height; BuildTiles(tiledMap, tilesetName); if(collisions) { // Create colliders BuildMeshCollider(tiledMap); } }
public void BuildTiles(TiledMap tiledMap, string tilesetName) { // Index Tiled data TiledMap.Layer layer = tiledMap.layers[BACKGROUND_LAYER]; TiledMap.Tileset tileset = tiledMap.tilesets[tilesetName]; // Reverse grid Y-axis int[] grid = new int[layer.grid.Length]; System.Array.Copy(layer.grid, grid, grid.Length); ConvertGridToYUp(grid, layer.width, layer.height); // Build tiles BuildTiles(grid, layer.width, layer.height, tileset.firstgid, tileset.tileWidth, tileset.tileHeight); }
/// <summary> /// Generates a single mesh collider from Tiled data. /// Only relevant faces are computed. /// Impprovement notes : /// - Meshes could be separated if the max vertice count is reached (65536) /// - Could use triangle strips instead of individual triangles /// - Have more shapes available (only boxes are supported) /// </summary> /// <param name='tiledMap'>Tiled map.</param> public void BuildMeshCollider(TiledMap tiledMap) { // Index Tiled data TiledMap.Layer layer = tiledMap.layers [COLLISION_LAYER]; TiledMap.Tileset tileset = tiledMap.tilesets [COLLISION_TILESET]; int[] grid = new int[layer.grid.Length]; // Reverse grid Y-axis System.Array.Copy(layer.grid, grid, grid.Length); ConvertGridToYUp(grid, layer.width, layer.height); // Build collider BuildMeshCollider(grid, layer.width, layer.height, tileset.firstgid); }
private static void ReadObjectGroup(TiledMap map, XElement root) { var layer = new TiledObjectGroup(); // Read generic layer information. ReadGenericLayerInformation(layer, root); // Read the used to display the objects in this group (if any). layer.Color = ColorTranslator.FromHtml(root.ReadAttribute("color", string.Empty)); // Read all objects. foreach (var objectElement in root.GetElements("object")) { // Is this a tile object? if (objectElement.HasAttribute("gid")) { ObjectParser.ReadTileObject(layer, objectElement); } else if (objectElement.HasElement("ellipse")) { // TODO: Add support for ellipsis objects. } else if (objectElement.HasElement("polygon")) { // TODO: Add support for polygon objects. } else if (objectElement.HasElement("polyline")) { // TODO: Add support for polyline objects. } else { ObjectParser.ReadRectangleObject(layer, objectElement); } } map.Layers.Add(layer); }
private void LoadCollisions(AsgardBase Base, TiledMap map) { #region build collision world var viewMap = map; var midgard = Base.LookupSystem<Midgard>(); var world = midgard.GetWorld(); var layer = viewMap.Layers.Last() as TiledTileLayer; { var layerField = typeof(TiledMap).GetField("_layers", BindingFlags.NonPublic | BindingFlags.Instance); List<TiledLayer> layers = layerField.GetValue(viewMap) as List<TiledLayer>; layers.Remove(layer); } for (var y = 0; y < layer.Height; y++) { for (var x = 0; x < layer.Width; x++) { var tile = layer.GetTile(x, y); if (tile.Id == 1702)// hack { var xTile = tile.X; var yTile = tile.Y; Vector2 centerPoint = new Vector2((xTile * (viewMap.TileWidth - 1)) + ((viewMap.TileWidth - 1) / 2), (yTile * (viewMap.TileHeight - 1)) + ((viewMap.TileHeight - 1) / 2)); Vector2 upperLeftPos = new Vector2(xTile * (viewMap.TileWidth - 1), (yTile) * (viewMap.TileHeight - 1)); var body = BodyFactory.CreateRectangle(world, (viewMap.TileWidth * _worldfactor) - 0.01f, (viewMap.TileHeight * _worldfactor) - 0.01f, 1.0f); body.Restitution = 1f; body.Position = new Vector2( centerPoint.X * _worldfactor, centerPoint.Y * _worldfactor); body.CollisionCategories = FarseerPhysics.Dynamics.Category.Cat1; body.CollidesWith = FarseerPhysics.Dynamics.Category.Cat2; } } } #endregion }
private void LoadTilemap(string name) { // Build background // Load map data TiledMap tiledMap = new TiledMap(); tiledMap.LoadFromJSON(name); width = tiledMap.width; // Build visible tilemap with collisions normalTilemap.collisionMapping = new int[] { 1, // [0] block 0, // [1] duck 2, // [2] spike up 3, // [3] coin 4, // ... 0, 0, 0, 0 }; normalTilemap.Build(tiledMap, "background"); normalTilemap.transform.position = new Vector3(offsetX, 0); // Build duckland tilemap without colliders duckWorldTilemap.Build(tiledMap, "background", false); duckWorldTilemap.SetLayer(LayerMask.NameToLayer("DuckWorld")); duckWorldTilemap.transform.position = new Vector3(offsetX, 0); TiledMap.Layer bgLayer = tiledMap.layers["background"]; // Build special colliders for(int y = 0; y < bgLayer.height; ++y) { for(int x = 0; x < bgLayer.width; ++x) { int t = bgLayer.AtYup(x,y); // Note: t starts at index 1 Vector3 pos = new Vector3(offsetX+x+0.5f, y+0.5f); if(t == 3) { Instantiate(spikePrefab, pos, Quaternion.identity); } } } // Build collectibles TiledMap.Layer objectLayer = tiledMap.layers["objects"]; for(int y = 0; y < objectLayer.height; ++y) { for(int x = 0; x < objectLayer.width; ++x) { int t = objectLayer.AtYup(x,y); if(t == 4) { Instantiate(collectiblePrefab, new Vector3(offsetX+x+0.5f, y+0.5f), Quaternion.identity); } else if (t == 5) { Instantiate(cancerPrefab, new Vector3(offsetX+x+0.5f, y+0.5f), Quaternion.identity); } else if (t == 6) { Instantiate(goalPrefab, new Vector3(offsetX+x+0.5f, y+0.5f), Quaternion.identity); } else if (t == 7) { Instantiate(heartPrefab, new Vector3(offsetX+x+0.5f, y+0.5f), Quaternion.identity); } } } }
public TiledTilesetTile( int id, TiledMap tiledMap ) { this.id = id; this.tiledMap = tiledMap; }
/// <summary> /// note that the origin is the top left so this position will represent that /// </summary> /// <returns>The world position.</returns> /// <param name="tilemap">Tilemap.</param> public Vector2 getWorldPosition( TiledMap tilemap ) { return new Vector2( x * tilemap.tileWidth, y * tilemap.tileHeight ); }
private static void ReadTileLayer(TiledMap map, XElement root) { var layer = new TiledTileLayer(); // Read generic layer information. ReadGenericLayerInformation(layer, root); // Read layer data. var dataElement = root.Element("data"); if (dataElement != null) { ReadTileLayerData(layer, dataElement); } map.Layers.Add(layer); }
/// <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); // TODO: use this.Content to load your game content here _tiles = Content.Load<Texture2D>("tiles_spritesheet"); _font = Content.Load<SpriteFont>("MonoLog"); _level = new TiledMap("Levels/levelTest.tmx"); _mapObject = new MapObject(this, new Vector2(0,0), _tiles, _level, _font); //_mapObject.Scale = new Vector2(2,2); GameObjects.Add(_mapObject); }
public TiledMapMover( TiledTileLayer collisionLayer ) { this.collisionLayer = collisionLayer; tiledMap = collisionLayer.tiledMap; Assert.isNotNull( collisionLayer, nameof( collisionLayer ) + " is required" ); }
/// <summary> /// Rectangle that encompases this tile with origin on the top left /// </summary> /// <returns>The tile rectangle.</returns> /// <param name="tilemap">Tilemap.</param> public Rectangle getTileRectangle( TiledMap tilemap ) { return new Rectangle( x * tilemap.tileWidth, y * tilemap.tileHeight, tilemap.tileWidth, tilemap.tileHeight ); }
public void Load(AsgardBase Base, TiledMap map) { Width = map.Width; Height = map.Height; TileWidth = map.TileWidth; TileHeight = map.TileHeight; FirstId = 1; var layers = map.Layers.ToList(); if (layers.Count < 5) return; Layer1 = new LayerData(layers[0] as TiledTileLayer); Layer2 = new LayerData(layers[1] as TiledTileLayer); Layer3 = new LayerData(layers[2] as TiledTileLayer); Layer4 = new LayerData(layers[3] as TiledTileLayer); Layer5 = new LayerData(layers[4] as TiledTileLayer); LoadCollisions(Base, map); }