private static RectangleF CalculateBoundary(TmxMap tmxMap) { RectangleF rcMap = new RectangleF(Point.Empty, tmxMap.MapSizeInPixels()); // Take boundaries from object groups var objBounds = from g in tmxMap.ObjectGroups from o in g.Objects where o.Visible == true select o.GetWorldBounds(); // Take boundaries from objects embedded in tiles var tileBounds = from layer in tmxMap.Layers where layer.Visible == true from y in Enumerable.Range(0, layer.Height) from x in Enumerable.Range(0, layer.Width) let tileId = layer.GetTileIdAt(x, y) where tileId != 0 let tile = tmxMap.Tiles[tileId] from o in tile.ObjectGroup.Objects let bound = o.GetWorldBounds() let point = TmxMath.TileCornerInScreenCoordinates(tmxMap, x, y) select new RectangleF(bound.X + point.X, bound.Y + point.Y, bound.Width, bound.Height); var allBounds = objBounds.Concat(tileBounds); var union = allBounds.Aggregate(rcMap, RectangleF.Union); // Inflate a tile size to make room for the grid union.Inflate(tmxMap.TileWidth, tmxMap.TileHeight); union.Inflate(PreviewImage.GridSize, PreviewImage.GridSize); return union; }
public static Bitmap CreateBitmap(TmxMap tmxMap, float scale) { SummaryReport report = new SummaryReport(); report.Capture("Previewing"); // What is the boundary of the bitmap we are creating? RectangleF bounds = CalculateBoundary(tmxMap); Bitmap bitmap = null; try { int width = (int)Math.Ceiling(bounds.Width * scale) + 1; int height = (int)Math.Ceiling(bounds.Height * scale) + 1; bitmap = TmxHelper.CreateBitmap32bpp(width, height); } catch (System.ArgumentException) { StringBuilder warning = new StringBuilder(); warning.AppendFormat("Map cannot be previewed at '{0}' scale. Try a smaller scale.\n", scale); warning.AppendLine("Image will be constructed on a 1024x1024 canvas. Parts of your map may be cropped."); Logger.WriteWarning(warning.ToString()); bitmap = TmxHelper.CreateBitmap32bpp(1024, 1024); } using (Pen pen = new Pen(Color.Black, 1.0f)) using (Graphics g = Graphics.FromImage(bitmap)) { g.InterpolationMode = InterpolationMode.NearestNeighbor; #if !TILED2UNITY_MAC g.PixelOffsetMode = PixelOffsetMode.HighQuality; #endif g.ScaleTransform(scale, scale); g.FillRectangle(Brushes.WhiteSmoke, 0, 0, bounds.Width, bounds.Height); g.DrawRectangle(pen, 1, 1, bounds.Width - 1, bounds.Height - 1); g.TranslateTransform(-bounds.X, -bounds.Y); DrawBackground(g, tmxMap); DrawGrid(g, tmxMap); DrawTiles(g, tmxMap); DrawColliders(g, tmxMap, scale); DrawObjectColliders(g, tmxMap); } report.Report(); return bitmap; }
public void LoadTMX(string mapFilePath) { var mapFile = new TmxMap("Content/Maps/" + mapFilePath + ".tmx"); Texture = Assets.Textures[Path.GetFileNameWithoutExtension(mapFile.Tilesets[0].Image.Source)]; TileWidth = mapFile.TileWidth; TileHeight = mapFile.TileHeight; Width = mapFile.Width; Height = mapFile.Height; var firstGid = mapFile.Tilesets[0].FirstGid; mapValues.Clear(); for (int y = 0; y < mapFile.Height; y++) { mapValues.Add(new List <int>()); for (int x = 0; x < mapFile.Width; x++) { mapValues[y].Add(mapFile.TileLayers[0].Tiles[(y * mapFile.Width) + x].Gid - firstGid); } } }
/// <summary> /// Initializes a new instance of the <see cref="Tiled.SFML.Map"/> class. /// </summary> /// <param name="filename">Filename.</param> /// <param name="view">View.</param> public Map(string filename, View view) { _view = view; var map = new TmxMap(filename); Properties = map.Properties; Width = map.Width; Height = map.Height; TileSize = new Vector2f(map.TileWidth, map.TileHeight); var gidDict = ConvertGidDict(map.Tilesets); // Load objects Objects = ConvertObjects(map.ObjectGroups, gidDict); // Load layers Layers = new List <Layer>(); foreach (var layer in map.Layers) { Layers.Add(new Layer(layer, TileSize, gidDict)); } }
public TileMap() { var map = new TmxMap($@"{Path.GetDirectoryName(PathTools.GetSourceFilePath())}\content\grass.tmx"); var tileSize = new Vector2(1f / (map.Width - 1), 1f / (map.Height - 1)); var tileSet = map.Tilesets[0]; SpriteSheetName = Path.GetFileName(tileSet.Image.Source); var columns = (uint)tileSet.Columns.Value; var rows = (uint)(tileSet.TileCount.Value / tileSet.Columns.Value); foreach (var tile in map.Layers[0].Tiles) { if (0 == tile.Gid) { continue; } var x = tile.X / (float)map.Width; var y = (map.Height - tile.Y - 1) / (float)map.Height; var geom = new Box2D(x, y, tileSize.X, tileSize.Y); var tex = SpriteSheet.CalcSpriteTexCoords((uint)tile.Gid - 1, columns, rows); tiles.Add(new Tile(geom, tex)); } }
protected override void LoadContent() { _spriteBatch = new SpriteBatch(GraphicsDevice); map = new TmxMap("Content/map.tmx"); Texture2D[] tileset = { Content.Load <Texture2D>("Summer - spring/Ground/" + map.Tilesets[0].Name.ToString()), Content.Load <Texture2D>("Summer - spring/Trees/" + map.Tilesets[1].Name.ToString()) }; int tileWidth = map.Tilesets[0].TileWidth; int tileHeight = map.Tilesets[0].TileHeight; int TileSetTilesWide = tileset[0].Width / tileWidth; mapManager = new TileMapManager(_spriteBatch, map, tileset[0], TileSetTilesWide, tileWidth, tileHeight); collisionObjects = new List <Rectangle>(); foreach (var o in map.ObjectGroups["Collisions"].Objects) { collisionObjects.Add(new Rectangle((int)o.X, (int)o.Y, (int)o.Width, (int)o.Height)); } SpriteSheet[] sheets = { Content.Load <SpriteSheet>("Player/Player.sf", new JsonContentLoader()), Content.Load <SpriteSheet>("Player/Player_Jump.sf", new JsonContentLoader()) }; player.Load(sheets); // TODO: use this.Content to load your game content here }
void Start() { var map = new TmxMap("test1.tmx"); Debug.Log("Height"); Debug.Log(map.Height); Debug.Log("Width"); Debug.Log(map.Width); Debug.Log("Tile Height"); Debug.Log(map.TileHeight); Debug.Log("Tile Width"); Debug.Log(map.TileWidth); // Debug.Log (map.Layers[0].Tiles[3].Gid); //Tile tile1 = GameObject.Find ("Tile").GetComponent <Tile> (); //tile1.currentTile = map.Layers [0].Tiles [0].Gid - 1; foreach (TmxLayerTile tile in map.Layers[0].Tiles) { Vector3 tilePosition = new Vector3(tile.X, (-1 * tile.Y), 0); GameObject tileObject = Instantiate(tilePrefab, tilePosition, transform.rotation) as GameObject; Tile tileScript = tileObject.GetComponent <Tile> (); tileScript.currentTile = tile.Gid - 1; } }
private static void DrawObjectLayerColliders(SKCanvas canvas, TmxMap tmxMap, TmxObjectGroup objectLayer) { foreach (var obj in objectLayer.Objects) { if (!obj.Visible) { continue; } // Either type color or object color or unity:layer color Color objColor = objectLayer.Color; string collisionType = objectLayer.UnityLayerOverrideName; if (String.IsNullOrEmpty(collisionType)) { collisionType = obj.Type; } if (tmxMap.ObjectTypes.TmxObjectTypeMapping.ContainsKey(collisionType)) { objColor = tmxMap.ObjectTypes.TmxObjectTypeMapping[collisionType].Color; } if (objectLayer.Ignore == TmxLayerNode.IgnoreSettings.Collision) { // We're ignoring collisions but the game object is still a part of the map. if (!(obj is TmxObjectTile)) { DrawObjectMarker(canvas, tmxMap, obj, objColor.ToSKColor()); } } else { DrawObjectCollider(canvas, tmxMap, obj, objColor.ToSKColor()); } } }
private static RectangleF CalculateBoundary(TmxMap tmxMap) { RectangleF rcMap = new RectangleF(Point.Empty, tmxMap.MapSizeInPixels); // Any tile layers in the map can be offset var tileLayerBounds = from layer in tmxMap.EnumerateTileLayers() where layer.Visible == true select new RectangleF(layer.GetCombinedOffset(), rcMap.Size); // Take boundaries from object groups var objBounds = from g in tmxMap.EnumerateObjectLayers() from o in g.Objects where o.Visible == true select o.GetOffsetWorldBounds(); // Take boundaries from objects embedded in tiles var tileBounds = from layer in tmxMap.EnumerateTileLayers() where layer.Visible == true from y in Enumerable.Range(0, layer.Height) from x in Enumerable.Range(0, layer.Width) let tileId = layer.GetTileIdAt(x, y) where tileId != 0 let tile = tmxMap.Tiles[tileId] from o in tile.ObjectGroup.Objects let bound = o.GetOffsetWorldBounds() let point = TmxMath.TileCornerInScreenCoordinates(tmxMap, x, y) select new RectangleF(bound.X + point.X, bound.Y + point.Y, bound.Width, bound.Height); var allBounds = tileLayerBounds.Concat(objBounds).Concat(tileBounds); var union = allBounds.Aggregate(rcMap, RectangleF.Union); // Inflate a tile size to make room for the grid union.Inflate(tmxMap.TileWidth, tmxMap.TileHeight); union.Inflate(PreviewImage.GridSize, PreviewImage.GridSize); return(union); }
private static Dictionary <string, int> LoadImgs(TmxMap tmx, Proto.TmxMap tmxOut) { var counts = 0; var imgs = new Dictionary <string, int>(); foreach (var tileset in tmx.Tilesets) { if (!string.IsNullOrEmpty(tileset.Image.Source)) { var path = tileset.Image.Source; if (!imgs.ContainsKey(path)) { tmxOut.Imgs.Add(new Proto.TmxMap.Types.ImgSet() { Path = Path.GetFullPath(path) }); imgs[path] = counts++; } } foreach (var tile in tileset.Tiles) { if (!string.IsNullOrEmpty(tile.Image.Source)) { var path = tile.Image.Source; if (!imgs.ContainsKey(path)) { tmxOut.Imgs.Add(new Proto.TmxMap.Types.ImgSet() { Path = Path.GetFullPath(path) }); imgs[path] = counts++; } } } } return(imgs); }
public TileMap(string tmxFile, World world) { this.world = world; tmxMap = new TmxMap(tmxFile); layerCount = tmxMap.Layers.Count; tileArray = new Texture2D[layerCount]; tileWidthArray = new int[layerCount]; tileHeightArray = new int[layerCount]; tilesetTilesWideArray = new int[layerCount]; tilesetTilesHighArray = new int[layerCount]; for (int i = 0; i < layerCount; i++) { string textureName = tmxMap.Tilesets[0].Name.ToString(); tileArray[i] = ResourceLoader.LoadTexture2D(world.GraphicsDevice, textureName, "Content/" + textureName + ".png"); tileWidthArray[i] = tmxMap.Tilesets[0].TileWidth; tileHeightArray[i] = tmxMap.Tilesets[0].TileHeight; tilesetTilesWideArray[i] = tileArray[0].Width / tileWidthArray[i]; tilesetTilesHighArray[i] = tileArray[0].Height / tileHeightArray[i]; } TmxList <TmxObjectGroup> groups = tmxMap.ObjectGroups; foreach (TmxObjectGroup group in groups) { if (group.Name == "collisions") { TmxList <TmxObject> tmxObjects = group.Objects; foreach (TmxObject tmxObject in tmxObjects) { Collider collider = new SampleCollider(new Rectangle((int)tmxObject.X, (int)tmxObject.Y, (int)tmxObject.Width, (int)tmxObject.Height)); colliders.Add(collider); } } } }
/// <summary> /// Load initial game content /// </summary> protected override void LoadContent() { // spritebatch used to draw textures spriteBatch = new SpriteBatch(GraphicsDevice); // load sprite sheet currently in use tilesetTxtr = Content.Load <Texture2D>("dungeon_test"); // load tiled map data this.map = new TmxMap("Content/dungeon_test.tmx"); ecs.AddComponentsToEntity(player.Eid, new EntityComponentSystem.RenderComponent(ecs, tilesetTxtr, new Rectangle(4 * 16, 8 * 16, 16, 16)), new EntityComponentSystem.PositionComponent(ecs, new Vector2(200, 200)), new EntityComponentSystem.MovementComponent(ecs, new Vector2(0, 0), new Vector2(6, 6)), new EntityComponentSystem.InputComponent(ecs) ); var playerPos = ((EntityComponentSystem.PositionComponent)player. Components[ecs.ComponentCids[ typeof(EntityComponentSystem.PositionComponent)]]).Position; ecs.AddComponentsToEntity(player.Eid, new EntityComponentSystem.CameraComponent( ecs, player.Eid, new Vector3(RPGGame._screenWidth / 2, RPGGame._screenHeight / 2, 0), new Vector3(playerPos.X, playerPos.Y, 0), 2.5f ) ); }
private void DrawMapLayer(TmxLayer layer) { TmxMap map = currentMap.TmxMap; int size = Global.TileSize; for (var i = 0; i < layer.Tiles.Count; i++) { int gid = layer.Tiles[i].Gid; if (gid != 0) { Tileset tileset = currentMap.GetTileset(gid); int tileFrame = gid - tileset.FirstGid; int column = tileFrame % tileset.TilesWide; int row = tileFrame / tileset.TilesWide; float x = (i % map.Width) * map.TileWidth; float y = (float)Math.Floor(i / (double)map.Width) * map.TileHeight; Rectangle tilesetRec = new Rectangle(size * column, size * row, size, size); spriteBatch.Draw(tileset.Texture, new Rectangle((int)x, (int)y, size, size), tilesetRec, Color.White); } } }
private static void DrawObjectColliders(Graphics g, TmxMap tmxMap) { var collidersObjectGroup = from item in tmxMap.ObjectGroups where item.Visible == true select item; foreach (var objGroup in collidersObjectGroup) { GraphicsState state = g.Save(); g.TranslateTransform(objGroup.Offset.X, objGroup.Offset.Y); foreach (var obj in objGroup.Objects) { if (obj.Visible) { // Either type color or object color or unity:layer color Color objColor = objGroup.Color; string collisionType = objGroup.UnityLayerOverrideName; if (String.IsNullOrEmpty(collisionType)) { collisionType = obj.Type; } if (tmxMap.ObjectTypes.TmxObjectTypeMapping.ContainsKey(collisionType)) { objColor = tmxMap.ObjectTypes.TmxObjectTypeMapping[collisionType].Color; } DrawObjectCollider(g, tmxMap, obj, objColor); } } g.Restore(state); } }
public static Map LoadTiledMap(GraphicsDevice graphicsDevice, string pathToMap) { TmxMap data = new TmxMap(pathToMap); Dictionary <TmxTileset, Texture2D> tilesetTextureMap = new Dictionary <TmxTileset, Texture2D>(); string tilesheetFolder = @"Content/Tilesets"; foreach (TmxTileset tileset in data.Tilesets) { string pathToResource = Path.Combine(tilesheetFolder, Path.GetFileName(tileset.Image.Source)); if (!File.Exists(pathToResource)) { continue; } using (FileStream stream = new FileStream(pathToResource, FileMode.Open)) { Texture2D texture = Texture2D.FromStream(graphicsDevice, stream); tilesetTextureMap.Add(tileset, texture); } } return(new Map(data, tilesetTextureMap)); }
public static TmxLayerTile GetSolidBlock(TmxMap map, int x, int y) { if (y < 0 || x < 0) { return(null); } var tileset_ = (TmxTileset)map.Tilesets[0]; var gid = (y * map.Width) + x; if (gid == 768) { gid = 0; } if (gid > map.Width * map.Height - 1) { return(null); } var tileset = (TmxTileset)map.Tilesets[0]; foreach (TmxLayer layer in map.Layers) { PropertyDict dict; var tile = layer.Tiles[gid]; tileset.Tiles.TryGetValue((int)tile.GID - 1, out dict); if (dict != null && dict.ContainsKey("destroyable")) { return(tile); } } return(null); }
public void Load(string projectDir) { if (Image != null) { return; } var map = new TmxMap(Path.Combine(projectDir, Project.Paths.Maps, TmxPath)); TileSize = new Size(map.TileWidth, map.TileHeight); Image = new Bitmap(map.Width * TileSize.Width, map.Height * TileSize.Height); var tileSheets = new Dictionary <string, Image>(); using (var graphic = Graphics.FromImage(Image)) { map.Fetch((x, y, tilesetName, tileRow, tileCol) => { Image tileSet; if (!tileSheets.TryGetValue(tilesetName, out tileSet)) { tileSet = Image.FromFile(Path.Combine(projectDir, Project.Paths.TileSheets, tilesetName)); tileSheets.Add(tilesetName, tileSet); } graphic.DrawImage( tileSet, new Rectangle(x * TileSize.Width, y * TileSize.Height, TileSize.Width, TileSize.Height), new Rectangle(tileCol * TileSize.Width, tileRow * TileSize.Height, TileSize.Width, TileSize.Height), GraphicsUnit.Pixel); }); } foreach (var img in tileSheets) { img.Value.Dispose(); } }
private static void PrepareTransformForTileObject(Graphics g, TmxMap tmxMap, TmxObjectTile tmxObjectTile) { // Isometric tiles are off by a half-width if (tmxMap.Orientation == TmxMap.MapOrientation.Isometric) { g.TranslateTransform(-tmxObjectTile.Tile.TileSize.Width * 0.5f, 0); } // Apply scale { // Move to "local origin" of tile and scale float toCenter_x = (tmxMap.Orientation == TmxMap.MapOrientation.Isometric) ? (tmxObjectTile.Tile.TileSize.Width * 0.5f) : 0.0f; g.TranslateTransform(toCenter_x, 0); { SizeF scale = tmxObjectTile.GetTileObjectScale(); g.ScaleTransform(scale.Width, scale.Height); } // Move back g.TranslateTransform(-toCenter_x, 0); } // Apply horizontal flip if (tmxObjectTile.FlippedHorizontal) { g.TranslateTransform(tmxObjectTile.Tile.TileSize.Width, 0); g.ScaleTransform(-1, 1); } // Apply vertical flip if (tmxObjectTile.FlippedVertical) { g.TranslateTransform(0, -tmxObjectTile.Tile.TileSize.Height); g.ScaleTransform(1, -1); } }
private static void DrawBackground(Graphics g, TmxMap tmxMap) { // Draw the background for the map // A full white background is preferred because of the colliders we draw on the top of the layers Size size = tmxMap.MapSizeInPixels(); Rectangle rect = new Rectangle(Point.Empty, size); g.FillRectangle(Brushes.White, rect); }
private void Init(TextAsset mapFile) { XDocument mapX = XDocument.Parse(mapFile.text); TmxMap map = new TmxMap(mapX); PlayerMovement player = Instantiate(playerPrefab); GameManager.main.SetPlayer(player); GameManager.main.SetToolCounts( Tools.IntParseFast(map.Properties["Bombs"]), Tools.IntParseFast(map.Properties["Dynamites"]), Tools.IntParseFast(map.Properties["Blocks"]) ); for (int index = 0; index < map.ObjectGroups.Count; index += 1) { for (int oIndex = 0; oIndex < map.ObjectGroups[index].Objects.Count; oIndex += 1) { TmxObject tmxObject = map.ObjectGroups[index].Objects[oIndex]; int layerTypeIndex = System.Array.IndexOf(layerTypes, map.ObjectGroups[index].Properties["Type"]); LayerType layerType = (LayerType)layerTypeIndex; if (layerType == LayerType.Player) { player.transform.SetParent(world, false); player.transform.localPosition = new Vector3((float)tmxObject.X / 64f, map.Height - (float)tmxObject.Y / 64f, 0); player.GetComponent <PlayerUseTool>().Initialize(mapGrid); } //SpawnObject(tmxObject, world.GetItemContainer().transform, map.Width, map.Height); } } mapGrid.Initialize(map.Width, map.Height, player); for (int index = 0; index < map.Layers.Count; index += 1) { TmxLayer layer = map.Layers[index]; //LayerType layerType = (LayerType)Tools.IntParseFast(layer.Properties["Type"]); int layerTypeIndex = System.Array.IndexOf(layerTypes, layer.Properties["Type"]); LayerType layerType = (LayerType)layerTypeIndex; TiledMesh tiledMesh; if (layerType == LayerType.Ground) { tiledMesh = Instantiate(tiledMeshPrefab); tiledMesh.transform.SetParent(otherStuff, false); tiledMesh.Init(map.Width, map.Height, layer, groundMaterial, transform); tiledMesh.GetComponent <MeshCollider>().enabled = false; } else if (layerType == LayerType.Slime) { int tilesX = map.Width; int tilesY = map.Height; for (int y = 0; y < tilesY; y++) { for (int x = 0; x < tilesX; x++) { TmxLayerTile tile = layer.Tiles[(tilesY - y - 1) * tilesX + x]; int tileId = tile.Gid - 1; if (tileId == -1) { continue; } mapGrid.AttemptToCreateSlime(-1, -1, x, y); } } } else if (layerType == LayerType.Wall) { int tilesX = map.Width; int tilesY = map.Height; for (int y = 0; y < tilesY; y++) { for (int x = 0; x < tilesX; x++) { TmxLayerTile tile = layer.Tiles[(tilesY - y - 1) * tilesX + x]; int tileId = tile.Gid - 1; if (tileId == -1) { continue; } mapGrid.PlaceWall(x, y); } } } } mapGrid.Activate(); }
private static void DrawPolygon(Graphics g, Pen pen, Brush brush, TmxMap tmxMap, TmxObjectPolygon tmxPolygon) { var points = TmxMath.GetPointsInMapSpace(tmxMap, tmxPolygon).ToArray(); g.FillPolygon(brush, points); g.DrawPolygon(pen, points); }
private static void DrawObjectCollider(Graphics g, TmxMap tmxMap, TmxObject tmxObject, Color color) { using (Brush brush = TmxHelper.CreateObjectColliderBrush(color)) using (Pen pen = new Pen(color)) { GraphicsState state = g.Save(); PointF xfPosition = TmxMath.ObjectPointFToMapSpace(tmxMap, tmxObject.Position); g.TranslateTransform(xfPosition.X, xfPosition.Y); g.RotateTransform(tmxObject.Rotation); if (tmxObject.GetType() == typeof(TmxObjectPolygon)) { DrawPolygon(g, pen, brush, tmxMap, tmxObject as TmxObjectPolygon); } else if (tmxObject.GetType() == typeof(TmxObjectRectangle)) { if (tmxMap.Orientation == TmxMap.MapOrientation.Isometric) { TmxObjectPolygon tmxIsometricRectangle = TmxObjectPolygon.FromRectangle(tmxMap, tmxObject as TmxObjectRectangle); DrawPolygon(g, pen, brush, tmxMap, tmxIsometricRectangle); } else { // Rectangles are polygons DrawPolygon(g, pen, brush, tmxMap, tmxObject as TmxObjectPolygon); } } else if (tmxObject.GetType() == typeof(TmxObjectEllipse)) { DrawEllipse(g, pen, brush, tmxMap, tmxObject as TmxObjectEllipse); } else if (tmxObject.GetType() == typeof(TmxObjectPolyline)) { DrawPolyline(g, pen, tmxMap, tmxObject as TmxObjectPolyline); } else if (tmxObject.GetType() == typeof(TmxObjectTile)) { GraphicsState tileState = g.Save(); TmxObjectTile tmxObjectTile = tmxObject as TmxObjectTile; PrepareTransformForTileObject(g, tmxMap, tmxObjectTile); // Draw the collisions // Temporarily set orienation to Orthogonal for tile colliders TmxMap.MapOrientation restoreOrientation = tmxMap.Orientation; tmxMap.Orientation = TmxMap.MapOrientation.Orthogonal; { // Make up for the fact that the bottom-left corner is the origin g.TranslateTransform(0, -tmxObjectTile.Tile.TileSize.Height); foreach (var obj in tmxObjectTile.Tile.ObjectGroup.Objects) { DrawObjectCollider(g, tmxMap, obj, Color.Gray); } } tmxMap.Orientation = restoreOrientation; g.Restore(tileState); } else { g.Restore(state); Logger.WriteWarning("Unhandled object: {0}", tmxObject.GetNonEmptyName()); } // Restore our state g.Restore(state); } }
private static void DrawGridHex(Graphics g, TmxMap tmxMap) { // Our collection of points to render HashSet <Point> points = new HashSet <Point>(); // Note: borrowed heavily from Tiled source (HexagonalRenderer::drawGrid) int tileWidth = tmxMap.TileWidth & ~1; int tileHeight = tmxMap.TileHeight & ~1; int sideLengthX = tmxMap.StaggerAxis == TmxMap.MapStaggerAxis.X ? tmxMap.HexSideLength : 0; int sideLengthY = tmxMap.StaggerAxis == TmxMap.MapStaggerAxis.Y ? tmxMap.HexSideLength : 0; int sideOffsetX = (tmxMap.TileWidth - sideLengthX) / 2; int sideOffsetY = (tmxMap.TileHeight - sideLengthY) / 2; int columnWidth = sideOffsetX + sideLengthX; int rowHeight = sideOffsetY + sideLengthY; bool staggerX = tmxMap.StaggerAxis == TmxMap.MapStaggerAxis.X; // Determine the tile and pixel coordinates to start at Point startTile = new Point(0, 0); Point startPos = TmxMath.TileCornerInScreenCoordinates(tmxMap, startTile.X, startTile.Y); Point[] oct = new Point[8] { new Point(0, tileHeight - sideOffsetY), new Point(0, sideOffsetY), new Point(sideOffsetX, 0), new Point(tileWidth - sideOffsetX, 0), new Point(tileWidth, sideOffsetY), new Point(tileWidth, tileHeight - sideOffsetY), new Point(tileWidth - sideOffsetX, tileHeight), new Point(sideOffsetX, tileHeight) }; if (staggerX) { // Odd row shifting is applied in the rendering loop, so un-apply it here if (TmxMath.DoStaggerX(tmxMap, startTile.X)) { startPos.Y -= rowHeight; } for (; startTile.X < GetMaxTilesWide(tmxMap); startTile.X++) { Point rowTile = startTile; Point rowPos = startPos; if (TmxMath.DoStaggerX(tmxMap, startTile.X)) { rowPos.Y += rowHeight; } for (; rowTile.Y < GetMaxTilesHigh(tmxMap); rowTile.Y++) { points.Add(TmxMath.AddPoints(rowPos, oct[1])); points.Add(TmxMath.AddPoints(rowPos, oct[2])); points.Add(TmxMath.AddPoints(rowPos, oct[3])); points.Add(TmxMath.AddPoints(rowPos, oct[4])); bool isStaggered = TmxMath.DoStaggerX(tmxMap, startTile.X); bool lastRow = rowTile.Y == tmxMap.Height - 1; bool lastColumn = rowTile.X == tmxMap.Width - 1; bool bottomLeft = rowTile.X == 0 || (lastRow && isStaggered); bool bottomRight = lastColumn || (lastRow && isStaggered); if (bottomRight) { points.Add(TmxMath.AddPoints(rowPos, oct[5])); points.Add(TmxMath.AddPoints(rowPos, oct[6])); } if (lastRow) { points.Add(TmxMath.AddPoints(rowPos, oct[6])); points.Add(TmxMath.AddPoints(rowPos, oct[7])); } if (bottomLeft) { points.Add(TmxMath.AddPoints(rowPos, oct[7])); points.Add(TmxMath.AddPoints(rowPos, oct[0])); } rowPos.Y += tileHeight + sideLengthY; } startPos.X += columnWidth; } } else { // Odd row shifting is applied in the rendering loop, so un-apply it here if (TmxMath.DoStaggerY(tmxMap, startTile.Y)) { startPos.X -= columnWidth; } for (; startTile.Y < tmxMap.Height; startTile.Y++) { Point rowTile = startTile; Point rowPos = startPos; if (TmxMath.DoStaggerY(tmxMap, startTile.Y)) { rowPos.X += columnWidth; } for (; rowTile.X < tmxMap.Width; rowTile.X++) { points.Add(TmxMath.AddPoints(rowPos, oct[0])); points.Add(TmxMath.AddPoints(rowPos, oct[1])); points.Add(TmxMath.AddPoints(rowPos, oct[2])); points.Add(TmxMath.AddPoints(rowPos, oct[3])); points.Add(TmxMath.AddPoints(rowPos, oct[4])); bool isStaggered = TmxMath.DoStaggerY(tmxMap, startTile.Y); bool lastRow = rowTile.Y == tmxMap.Height - 1; bool lastColumn = rowTile.Y == tmxMap.Width - 1; bool bottomLeft = lastRow || (rowTile.X == 0 && !isStaggered); bool bottomRight = lastRow || (lastColumn && isStaggered); if (lastColumn) { points.Add(TmxMath.AddPoints(rowPos, oct[4])); points.Add(TmxMath.AddPoints(rowPos, oct[5])); } if (bottomRight) { points.Add(TmxMath.AddPoints(rowPos, oct[5])); points.Add(TmxMath.AddPoints(rowPos, oct[6])); } if (bottomLeft) { points.Add(TmxMath.AddPoints(rowPos, oct[7])); points.Add(TmxMath.AddPoints(rowPos, oct[0])); } rowPos.X += tileWidth + sideLengthX; } startPos.Y += rowHeight; } } foreach (var p in points) { RectangleF rc = new RectangleF(p.X, p.Y, PreviewImage.GridSize, PreviewImage.GridSize); rc.Offset(-PreviewImage.GridSize * 0.5f, -PreviewImage.GridSize * 0.5f); g.DrawRectangle(Pens.Black, rc.X, rc.Y, rc.Width, rc.Height); } }
private static void DrawObjectCollider(Graphics g, TmxMap tmxMap, TmxObject tmxObject, Color color) { using (Brush brush = TmxHelper.CreateObjectColliderBrush(color)) using (Pen pen = new Pen(color)) { GraphicsState state = g.Save(); PointF xfPosition = TmxMath.ObjectPointFToMapSpace(tmxMap, tmxObject.Position); g.TranslateTransform(xfPosition.X, xfPosition.Y); g.RotateTransform(tmxObject.Rotation); if (tmxObject.GetType() == typeof(TmxObjectPolygon)) { DrawPolygon(g, pen, brush, tmxMap, tmxObject as TmxObjectPolygon); } else if (tmxObject.GetType() == typeof(TmxObjectRectangle)) { if (tmxMap.Orientation == TmxMap.MapOrientation.Isometric) { TmxObjectPolygon tmxIsometricRectangle = TmxObjectPolygon.FromRectangle(tmxMap, tmxObject as TmxObjectRectangle); DrawPolygon(g, pen, brush, tmxMap, tmxIsometricRectangle); } else { // Rectangles are polygons DrawPolygon(g, pen, brush, tmxMap, tmxObject as TmxObjectPolygon); } } else if (tmxObject.GetType() == typeof(TmxObjectEllipse)) { DrawEllipse(g, pen, brush, tmxMap, tmxObject as TmxObjectEllipse); } else if (tmxObject.GetType() == typeof(TmxObjectPolyline)) { DrawPolyline(g, pen, tmxMap, tmxObject as TmxObjectPolyline); } else if (tmxObject.GetType() == typeof(TmxObjectTile)) { GraphicsState tileState = g.Save(); TmxObjectTile tmxObjectTile = tmxObject as TmxObjectTile; // Isometric tiles are off by a half-width if (tmxMap.Orientation == TmxMap.MapOrientation.Isometric) { g.TranslateTransform(-tmxMap.TileWidth * 0.5f, 0); } // Apply scale SizeF scale = tmxObjectTile.GetTileObjectScale(); g.ScaleTransform(scale.Width, scale.Height); // Apply horizontal flip if (tmxObjectTile.FlippedHorizontal) { g.TranslateTransform(tmxObjectTile.Tile.TileSize.Width, 0); g.ScaleTransform(-1, 1); } // Apply vertical flip if (tmxObjectTile.FlippedVertical) { g.TranslateTransform(0, -tmxObjectTile.Tile.TileSize.Height); g.ScaleTransform(1, -1); } // (Note: Now we can draw the tile and collisions as normal as the transforms have been set up.) // Draw the tile Rectangle destination = new Rectangle(0, -tmxObjectTile.Tile.TileSize.Height, tmxObjectTile.Tile.TileSize.Width, tmxObjectTile.Tile.TileSize.Height); Rectangle source = new Rectangle(tmxObjectTile.Tile.LocationOnSource, tmxObjectTile.Tile.TileSize); g.DrawImage(tmxObjectTile.Tile.TmxImage.ImageBitmap, destination, source, GraphicsUnit.Pixel); // Put a black border around the tile so it sticks out a bit as an object g.DrawRectangle(Pens.Black, destination); // Draw the collisions // Temporarily set orienation to Orthogonal for tile colliders TmxMap.MapOrientation restoreOrientation = tmxMap.Orientation; tmxMap.Orientation = TmxMap.MapOrientation.Orthogonal; { // Make up for the fact that the bottom-left corner is the origin g.TranslateTransform(0, -tmxObjectTile.Tile.TileSize.Height); foreach (var obj in tmxObjectTile.Tile.ObjectGroup.Objects) { DrawObjectCollider(g, tmxMap, obj, Color.Gray); } } tmxMap.Orientation = restoreOrientation; g.Restore(tileState); } else { g.Restore(state); Logger.WriteWarning("Unhandled object: {0}", tmxObject.GetNonEmptyName()); } // Restore our state g.Restore(state); } }
private static int GetMaxTilesWide(TmxMap tmxMap) { return Math.Min(tmxMap.Width, MaxPreviewTilesWide); }
private static int GetMaxTilesHigh(TmxMap tmxMap) { return Math.Min(tmxMap.Height, MaxPreviewTilesHigh); }
private static void DrawTiles(Graphics g, TmxMap tmxMap) { foreach (TmxLayer layer in tmxMap.Layers) { if (layer.Visible == false) continue; if (layer.Ignore == TmxLayer.IgnoreSettings.Visual) continue; // Set the opacity for the layer (Not supported on Mac builds) #if !TILED2UNITY_MAC ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.Matrix33 = layer.Opacity; ImageAttributes imageAttributes = new ImageAttributes(); imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); #endif // Translate by the offset GraphicsState state = g.Save(); g.TranslateTransform(layer.Offset.X, layer.Offset.Y); // The range of x and y depends on the render order of the tiles // By default we draw right and down but may reverse the tiles we visit var range_x = Enumerable.Range(0, GetMaxTilesWide(layer)); var range_y = Enumerable.Range(0, GetMaxTilesHigh(layer)); if (tmxMap.DrawOrderHorizontal == -1) range_x = range_x.Reverse(); if (tmxMap.DrawOrderVertical == -1) range_y = range_y.Reverse(); // Visit the tiles we are going to draw var tiles = from y in range_y from x in range_x let rawTileId = layer.GetRawTileIdAt(x, y) let tileId = layer.GetTileIdAt(x, y) where tileId != 0 let tile = tmxMap.Tiles[tileId] // Support for animated tiles. Just show the first frame of the animation. let frame = tmxMap.Tiles[tile.Animation.Frames[0].GlobalTileId] select new { Tile = frame, Position = TmxMath.TileCornerInScreenCoordinates(tmxMap, x, y), Bitmap = frame.TmxImage.ImageBitmap, IsFlippedDiagnoally = TmxMath.IsTileFlippedDiagonally(rawTileId), IsFlippedHorizontally = TmxMath.IsTileFlippedHorizontally(rawTileId), IsFlippedVertically = TmxMath.IsTileFlippedVertically(rawTileId), }; PointF[] destPoints = new PointF[4]; PointF[] destPoints3 = new PointF[3]; foreach (var t in tiles) { PointF location = t.Position; // Individual tiles may be larger than the given tile size of the overall map location.Y = (t.Position.Y - t.Tile.TileSize.Height) + tmxMap.TileHeight; // Take tile offset into account location.X += t.Tile.Offset.X; location.Y += t.Tile.Offset.Y; // Make up the 'quad' of texture points and transform them PointF center = new PointF(t.Tile.TileSize.Width * 0.5f, t.Tile.TileSize.Height * 0.5f); destPoints[0] = new Point(0, 0); destPoints[1] = new Point(t.Tile.TileSize.Width, 0); destPoints[2] = new Point(t.Tile.TileSize.Width, t.Tile.TileSize.Height); destPoints[3] = new Point(0, t.Tile.TileSize.Height); // Transform the points based on our flipped flags TmxMath.TransformPoints(destPoints, center, t.IsFlippedDiagnoally, t.IsFlippedHorizontally, t.IsFlippedVertically); // Put the destination points back into world space TmxMath.TranslatePoints(destPoints, location); // Stupid DrawImage function only takes 3 destination points otherwise it throws an exception destPoints3[0] = destPoints[0]; destPoints3[1] = destPoints[1]; destPoints3[2] = destPoints[3]; // Draw the tile Rectangle source = new Rectangle(t.Tile.LocationOnSource, t.Tile.TileSize); #if !TILED2UNITY_MAC g.DrawImage(t.Bitmap, destPoints3, source, GraphicsUnit.Pixel, imageAttributes); #else g.DrawImage(t.Bitmap, destPoints3, source, GraphicsUnit.Pixel); #endif } g.Restore(state); } }
private static void DrawPolyline(Graphics g, Pen pen, TmxMap tmxMap, TmxObjectPolyline tmxPolyline) { var points = TmxMath.GetPointsInMapSpace(tmxMap, tmxPolyline).ToArray(); g.DrawLines(pen, points); }
private static void DrawGridQuad(Graphics g, TmxMap tmxMap) { HashSet<Point> points = new HashSet<Point>(); for (int x = 0; x < GetMaxTilesWide(tmxMap); ++x) { for (int y = 0; y < GetMaxTilesHigh(tmxMap); ++y) { // Add the "top-left" corner of a tile points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x, y)); // Add all other corners of the tile to our list of grid points // This is complicated by different map types (espcially staggered isometric) if (tmxMap.Orientation == TmxMap.MapOrientation.Orthogonal || tmxMap.Orientation == TmxMap.MapOrientation.Isometric) { points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x + 1, y)); points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x + 1, y + 1)); points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x, y + 1)); } else if (tmxMap.Orientation == TmxMap.MapOrientation.Staggered) { bool sx = TmxMath.DoStaggerX(tmxMap, x); bool sy = TmxMath.DoStaggerY(tmxMap, y); if (sx) { // top-right, bottom-right, and bottom-left points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x + 1, y + 1)); points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x, y + 1)); points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x - 1, y + 1)); } else if (sy) { // top-right, bottom-right, and bottom-left points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x + 1, y + 1)); points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x, y + 2)); points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x, y + 1)); } else if (tmxMap.StaggerAxis == TmxMap.MapStaggerAxis.X) { // top-right, bottom-right, and bottom-left points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x + 1, y)); points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x, y + 1)); points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x - 1, y)); } else if (tmxMap.StaggerAxis == TmxMap.MapStaggerAxis.Y) { // top-right, bottom-right, and bottom-left points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x, y + 1)); points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x, y + 2)); points.Add(TmxMath.TileCornerInGridCoordinates(tmxMap, x - 1, y + 1)); } } } } // Can take for granted that background is always white List<RectangleF> rectangles = new List<RectangleF>(points.Count); foreach (var p in points) { RectangleF rc = new RectangleF(p.X, p.Y, PreviewImage.GridSize, PreviewImage.GridSize); rc.Offset(-PreviewImage.GridSize * 0.5f, -PreviewImage.GridSize * 0.5f); rectangles.Add(rc); } g.DrawRectangles(Pens.Black, rectangles.ToArray()); }
public TiledMapProcessorResult(TmxMap map) { Map = map; }
private static void DrawTilesInTileLayer(Graphics g, TmxMap tmxMap, TmxLayer layer) { // Set the opacity for the layer (Not supported on Mac builds) #if !TILED2UNITY_MAC ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.Matrix33 = layer.Opacity; ImageAttributes imageAttributes = new ImageAttributes(); imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); #endif // The range of x and y depends on the render order of the tiles // By default we draw right and down but may reverse the tiles we visit var range_x = Enumerable.Range(0, GetMaxTilesWide(layer)); var range_y = Enumerable.Range(0, GetMaxTilesHigh(layer)); if (tmxMap.DrawOrderHorizontal == -1) { range_x = range_x.Reverse(); } if (tmxMap.DrawOrderVertical == -1) { range_y = range_y.Reverse(); } // Visit the tiles we are going to draw var tiles = from y in range_y from x in range_x let rawTileId = layer.GetRawTileIdAt(x, y) let tileId = layer.GetTileIdAt(x, y) where tileId != 0 let tile = tmxMap.Tiles[tileId] // Support for animated tiles. Just show the first frame of the animation. let frame = tmxMap.Tiles[tile.Animation.Frames[0].GlobalTileId] select new { Tile = frame, Position = TmxMath.TileCornerInScreenCoordinates(tmxMap, x, y), Bitmap = frame.TmxImage.ImageBitmap, IsFlippedDiagnoally = TmxMath.IsTileFlippedDiagonally(rawTileId), IsFlippedHorizontally = TmxMath.IsTileFlippedHorizontally(rawTileId), IsFlippedVertically = TmxMath.IsTileFlippedVertically(rawTileId), }; PointF[] destPoints = new PointF[4]; PointF[] destPoints3 = new PointF[3]; foreach (var t in tiles) { PointF location = t.Position; // Individual tiles may be larger than the given tile size of the overall map location.Y = (t.Position.Y - t.Tile.TileSize.Height) + tmxMap.TileHeight; // Take tile offset into account location.X += t.Tile.Offset.X; location.Y += t.Tile.Offset.Y; // Make up the 'quad' of texture points and transform them PointF center = new PointF(t.Tile.TileSize.Width * 0.5f, t.Tile.TileSize.Height * 0.5f); destPoints[0] = new Point(0, 0); destPoints[1] = new Point(t.Tile.TileSize.Width, 0); destPoints[2] = new Point(t.Tile.TileSize.Width, t.Tile.TileSize.Height); destPoints[3] = new Point(0, t.Tile.TileSize.Height); // Transform the points based on our flipped flags TmxMath.TransformPoints(destPoints, center, t.IsFlippedDiagnoally, t.IsFlippedHorizontally, t.IsFlippedVertically); // Put the destination points back into world space TmxMath.TranslatePoints(destPoints, location); // Stupid DrawImage function only takes 3 destination points otherwise it throws an exception destPoints3[0] = destPoints[0]; destPoints3[1] = destPoints[1]; destPoints3[2] = destPoints[3]; // Draw the tile Rectangle source = new Rectangle(t.Tile.LocationOnSource, t.Tile.TileSize); #if !TILED2UNITY_MAC g.DrawImage(t.Bitmap, destPoints3, source, GraphicsUnit.Pixel, imageAttributes); #else g.DrawImage(t.Bitmap, destPoints3, source, GraphicsUnit.Pixel); #endif } }
private static int GetMaxTilesWide(TmxMap tmxMap) { return(Math.Min(tmxMap.Width, MaxPreviewTilesWide)); }
public static Level ParseLevel(int levelNo) { //Get Map var levelStr = levelNo.ToString().PadLeft(5, '0'); var map = new TmxMap($"{Application.streamingAssetsPath}/Levels/level_{levelStr}.tmx"); //Get Level Info From Map var mapProperties = map.Properties.ToArray(); var width = map.Width; var height = map.Height; var itemLayer = map.TileLayers.FirstOrDefault(layer => layer.Name == ItemLayer); var cellItemLayer = map.TileLayers.FirstOrDefault(layer => layer.Name == CellItemLayer); var groupLayers = new TmxObjectGroup[10]; var groups = new Group[10]; foreach (var temp in map.ObjectGroups) { if (!GroupNames.ContainsKey(temp.Name)) { continue; } groupLayers[GroupNames[temp.Name]] = temp; } //goals var goals = new Dictionary <GoalType, int>(4); var goalCount = 0; foreach (var pair in mapProperties) { if (goalCount >= 4) { break; } if (!Enum.TryParse(pair.Key, true, out GoalType goalType)) { continue; } if (!int.TryParse(pair.Value, out var goalAmount)) { continue; } goals.Add(goalType, goalAmount); goalCount++; } if (goalCount == 0) { throw new ApplicationException("No goal in level"); } //move count var moveCountPair = mapProperties.FirstOrDefault(p => p.Key == MoveCount); if (!int.TryParse(moveCountPair.Value, out var moveCount)) { throw new ApplicationException("No move count"); } //items if (itemLayer == null) { throw new ApplicationException("Item layer is null"); } var itemList = itemLayer.Tiles.Select(i => FakeItemIds.Contains(i.Gid - 1) ? ItemTypeInBoard.Empty : Enumeration.FromValue <ItemTypeInBoard>(i.Gid - 1)) .ToArray(); var itemGrid = itemList.ToArray().Make2DArray(height, width); //cell items CellItemTypeInBoard[,] cellItemGrid; if (cellItemLayer == null) { cellItemGrid = new CellItemTypeInBoard[height, width].Populate(CellItemTypeInBoard.Empty); } else { cellItemGrid = cellItemLayer.Tiles.Select(i => Enumeration.FromValue <CellItemTypeInBoard>(i.Gid - 1)) .ToArray().Make2DArray(height, width); } //groups if (groupLayers.All(g => g == null)) { var items = new List <ItemTypeInBoard> { ItemTypeInBoard.BlueCube, ItemTypeInBoard.GreenCube, ItemTypeInBoard.RedCube, ItemTypeInBoard.YellowCube, }; groups[0] = new Group { Items = items, UseForDrop = true }; Debug.LogError("Could not find any Group. Created Temp group for drop"); } else { for (var i = 0; i < groupLayers.Length; i++) { if (groupLayers[i] == null) { continue; } //group items if (groupLayers[i].Objects.Count <= 0) { throw new ApplicationException( $"There were no items in {groupLayers[i].Name}. Added temp items to group"); } var items = groupLayers[i].Objects.ToList() .Select(o => Enumeration.FromValue <ItemTypeInBoard>(o.Tile.Gid - 1)).ToList(); //use for drop bool useForDrop; if (!groupLayers[i].Properties.ContainsKey(UseForDrop)) { useForDrop = false; } else { bool.TryParse(groupLayers[i].Properties[UseForDrop], out useForDrop); } groups[i] = new Group { Items = items, UseForDrop = useForDrop, }; } if (groups.All(g => g == null || !g.UseForDrop)) { throw new ApplicationException($"Could not find any group for drop. Please add it"); } } var level = new Level(width, height, itemGrid, cellItemGrid, goals, moveCount, groups); return(level); }
public TileMap(String mapName, Microsoft.Xna.Framework.Content.ContentManager content) { name = mapName; wallSprites = new List <Sprite>(); backgroundTiles = new List <Tile>(); nearbyMaps = new List <string>(); map = new TmxMap("Content/Tilemaps/" + mapName + ".tmx"); nearbyMaps = mapName.Split('-').ToList(); List <int> UnwalkableTileGids = FindUnwalkableTiles(map); string tileSetPath = map.Tilesets[0].Name.ToString(); tileSetPath = "Tilemaps/" + tileSetPath; tileset = content.Load <Texture2D>(tileSetPath); tileHeight = map.Tilesets[0].TileHeight; tileWidth = map.Tilesets[0].TileWidth; tilesetTilesWide = tileset.Width / tileWidth; tilesetTilesHigh = tileset.Height / tileHeight; int mapWidth = map.Width * tileWidth; int mapHeight = map.Height * tileHeight; this._Postion = new Vector2(Convert.ToInt32(nearbyMaps[0]) * mapWidth, Convert.ToInt32(nearbyMaps[1]) * mapHeight); mapTilePos = new Vector2(Convert.ToInt32(nearbyMaps[0]), Convert.ToInt32(nearbyMaps[1])); tileMapRect = new Rectangle((int)this._Postion.X, (int)this._Postion.Y, mapWidth, mapHeight); bool test = true; for (var i = 0; i < map.Layers[0].Tiles.Count; i++) { int gid = map.Layers[0].Tiles[i].Gid; // Empty tile, do nothing if (gid != 0) { int tileFrame = gid - 1; int column = tileFrame % tilesetTilesWide; int row; if (tileFrame + 1 > tilesetTilesWide) { row = tileFrame - column * tilesetTilesWide; } else { row = 0; } float x = (i % map.Width) * map.TileWidth; float y = (float)Math.Floor(i / (double)map.Width) * map.TileHeight; int tileX = (int)(x / map.TileWidth); int tileY = (int)(y / map.TileHeight); Rectangle tilesetRec = new Rectangle(tileWidth * column, tileHeight * row, tileWidth, tileHeight); x += this._Postion.X; y += this._Postion.Y; Vector2 tilePos = new Vector2(x, y); if (test == true) { test = false; } else { test = true; } bool walkable = true; if (UnwalkableTileGids.Contains(gid)) { walkable = false; } Tile newTile = new Tile(tileset, tilePos, tileWidth, tileHeight, column, row, true, new Vector2(tileX, tileY), walkable); backgroundTiles.Add(newTile); } } WallList = FindWalls(); foreach (Rectangle rect in WallList) { wallSprites.Add(SpriteFromRect(rect, content)); } }
private static int GetMaxTilesHigh(TmxMap tmxMap) { return(Math.Min(tmxMap.Height, MaxPreviewTilesHigh)); }
private static void DrawGrid(Graphics g, TmxMap tmxMap) { if (tmxMap.Orientation == TmxMap.MapOrientation.Hexagonal) { DrawGridHex(g, tmxMap); } else { DrawGridQuad(g, tmxMap); } }
/// <summary> /// Adds a map to a stage spread to a number of different actors. /// </summary> /// <param name="stage">The stage where the map should be created.</param> /// <param name="path">The path to the map inside the content folder.</param> /// <param name="growStage">If the stage should grow its layers to support each layer of the loaded map.</param> /// <param name="useSharedPositionTransform">Wheter the transform should be a SharedPositionTransform or a normal one.</param> /// <returns>Each TiledMapComponent that is needed to display the map.</returns> public TiledMapComponent[] AddMap(Stage stage, string path, bool growStage = false, bool useSharedPositionTransform = false) { TmxMap map = InnerLoadMap(path); // In the following code we go through each tileLayer in map and look where it wants to be // placed on the stage. This is done via the "layer" custom property on each tile layer. // If this property is not set in the tmx file then we simply set the layer to the previously // layer + 1. Layers can also be skipped. For example the layer property could go from 1 on the first // layer to 3 on the second layer. One might do this so that sprites can be put on layer 2 which // ensures total control of what is supposed to be drawn when. // Create all variables that are needed for the loop bool warnedNotAbleToGrow = false; int atLayer = 0; List <int> layersToPlaceOn = new List <int>(map.TileLayers.Count); for (int i = 0; i < map.TileLayers.Count; i++) { // first set the default layer to be placed on as the lastlayer + 1 int layerToPlaceOn = atLayer + 1; // Try to see if a layer property is on the tilelayer. if (map.TileLayers[i].Properties.TryGetValue("layer", out string value) == true) { if (int.TryParse(value, out int newLayer) == false) // if we can not parse it print an error. { Log.Warn("TileLayer " + map.TileLayers[i].Name + " layer could not be parsed to int: " + value); } else // otherwise set the layerToPlace on to the value we just read and parsed. { layerToPlaceOn = newLayer; } } // If the newLayer is smaller than the previous layer print an error and set it to previous layer + 1. if (layerToPlaceOn < atLayer) { Log.Warn("TileLayer " + map.TileLayers[i].Name + " layer order should increment with each layer or stay the same value!"); layerToPlaceOn = atLayer + 1; } // Check to see if the layer is bigger than the stage has layers and if the stage should not grow. if (layerToPlaceOn >= stage.Layers && growStage == false) { // Print an error about this once. if (warnedNotAbleToGrow == false) { Log.Warn("Stage can not grow but layers on TiledMap are above the layer count. This might result in wrong rendering of the map"); warnedNotAbleToGrow = true; } // Set the layer to the maximum amount the stage can have layers. layerToPlaceOn = stage.Layers - 1; } // Lastly put it in the layerToPlaceOn list and set the new layer number to the atLayer for the next loop. layersToPlaceOn.Add(layerToPlaceOn); atLayer = layerToPlaceOn; } // If we should grow the stage then do this now. int growToLayers = layersToPlaceOn[layersToPlaceOn.Count - 1] + 1; if (growStage == true && growToLayers > stage.Layers) { stage.GrowToLayers(growToLayers); } // Now that every index is set, we have to create each TiledMapComponent. For this we go through the // previously set indexes and create a batch when the layer is different. int lastIndex = 0; List <TiledMapComponent> mapComponents = new List <TiledMapComponent>(); for (int i = 1; i < layersToPlaceOn.Count; i++) { if (layersToPlaceOn[lastIndex] != layersToPlaceOn[i]) { mapComponents.Add(InnerAddMapWithActor(map, stage, layersToPlaceOn[lastIndex], useSharedPositionTransform, lastIndex, i - 1)); lastIndex = i; } } // There now should still be one batch of maps that we should create. mapComponents.Add(InnerAddMapWithActor(map, stage, layersToPlaceOn[lastIndex], useSharedPositionTransform, lastIndex, layersToPlaceOn.Count - 1)); // If shared transforms are used then set their group. if (useSharedPositionTransform == true) { SharedPositionTransform2[] sharedTrans = new SharedPositionTransform2[mapComponents.Count]; for (int i = 0; i < sharedTrans.Length; i++) { sharedTrans[i] = mapComponents[i].Actor.GetComponent <SharedPositionTransform2>(); } sharedTrans[0].SetGroup(sharedTrans); } // Go through each map and set the connected maps which are all the maps we just created. for (int i = 0; i < mapComponents.Count; i++) { mapComponents[i].SetConnectedMaps(mapComponents); } loadedMaps.Add(map); // load all objects NotifyLoadObjects(map, mapComponents); // Lastly return the mapcomponents. return(mapComponents.ToArray()); }
void LoadMainGame(Zombicide game) { //Initialize map map = new TiledSharp.TmxMap(@"Content/Tiled/Big Game Hunting.tmx"); mapPic = game.Content.Load <Texture2D>(@"Tiled/Big Game Hunting"); Highlight = game.Content.Load <Texture2D>(@"Highlight"); closedDoor = game.Content.Load <Texture2D>(@"ClosedDoor"); openDoor = game.Content.Load <Texture2D>(@"OpenDoor"); mapX = (game.GraphicsDevice.Viewport.Width / 2) - (mapWidth / 2); mapY = (game.GraphicsDevice.Viewport.Height / 2) - (mapHeight / 2); tilesHigh = Convert.ToInt32(map.Layers[0].Properties.Where(x => x.Key == "TilesHigh").FirstOrDefault().Value); tilesWide = Convert.ToInt32(map.Layers[0].Properties.Where(x => x.Key == "TilesWide").FirstOrDefault().Value); tileWidth = mapWidth / tilesWide; tileHeight = mapHeight / tilesHigh; litTiles = new List <Tile>(); doorTiles = new List <Tile>(); tileData = LoadTileData("BigGameHunting"); foreach (Tile T in tileData) { if (T.LeftSide == RoomSide.closeddoor || T.LeftSide == RoomSide.opendoor || T.TopSide == RoomSide.closeddoor || T.TopSide == RoomSide.opendoor) { doorTiles.Add(T); } } //Initialize random number generator RNG = new Random(); //Place reset map Button resetMapButton = game.Content.Load <Texture2D>(@"CenterMapButton"); resetMapX = 1200 - 54; resetMapY = game.GraphicsDevice.Viewport.Height - 54; //read in Start tile from map data and place player there var startTile = map.Layers[0].Properties.Where(x => x.Key == "StartTile").FirstOrDefault().Value.Split(','); game.ActiveCharacter.Move(startTile, true); //Load Zombie Spawns Zombie.SpawnTiles = map.Layers[0].Properties.Where(x => x.Key.StartsWith("SpawnZone")).Select(x => x.Value.Split(',').Select(y => Convert.ToInt32(y)).ToArray()).ToList(); //Load and initialize objectives Objective.ObjectiveTiles = map.Layers[0].Properties.Where(x => x.Key.StartsWith("Objective")).Select(x => x.Value.Split(',').Select(y => Convert.ToInt32(y)).ToArray()).ToList(); Objective.Initialize(game); //Initialize UI for Main game screen PanelTabs tabs = new PanelTabs(); PanelTabs RightTabs = new PanelTabs(); Panel movePanel = new Panel(new Vector2(400, 750), PanelSkin.Default, Anchor.TopRight, new Vector2(0, 50)); Panel playerPanel = new Panel(new Vector2(400, 750), PanelSkin.Default, Anchor.TopLeft, new Vector2(0, 50)); playerPanel.AddChild(tabs); movePanel.AddChild(RightTabs); TabData EquipmentTab = RightTabs.AddTab("Equipment"); Item MH = game.ActiveCharacter.MainHandSlot; MainHand = new Image(MH.Texture, new Vector2(MH.Size.X, MH.Size.Y), anchor: Anchor.TopLeft); MainHand.OutlineWidth = 3; var mainWeap = (Weapon)game.ActiveCharacter.MainHandSlot; MainHand.ToolTipText = "Damage: " + mainWeap.Damage + "\nDice: " + mainWeap.Dice + "\nHit Value: " + mainWeap.DiceThreshold + "\nRange: " + mainWeap.MinRange + "-" + mainWeap.MaxRange; MainHand.OnClick = (Entity pgh) => { game.ActiveCharacter.SetActiveWeapon("MAIN"); }; OffHand = new Image(Character.EmptyHand, new Vector2(MH.Size.X, MH.Size.Y), anchor: Anchor.TopRight); OffHand.OutlineWidth = 3; OffHand.OutlineColor = Color.White; OffHand.OnClick = (Entity pgh) => { if (game.ActiveCharacter.OffHandSlot != null) { game.ActiveCharacter.SetActiveWeapon("OFF"); } }; ArmorSlot = new Image(Character.EmptyArmor, new Vector2(MH.Size.X, MH.Size.Y), anchor: Anchor.AutoCenter, offset: new Vector2(0, 50)); ArmorSlot.OutlineWidth = 3; ArmorSlot.OutlineColor = Color.White; EquipmentTab.button.Padding = new Vector2(0, 0); EquipmentTab.button.Size = new Vector2(100, 50); EquipmentTab.button.Offset = new Vector2(0, -50); EquipmentTab.panel.Offset = new Vector2(0, -50); EquipmentTab.button.ButtonParagraph.Scale = .9f; EquipmentTab.panel.AddChild(MainHand); EquipmentTab.panel.AddChild(OffHand); EquipmentTab.panel.AddChild(ArmorSlot); TabData SkillTab = RightTabs.AddTab("Skills"); BlueSkill = new Paragraph(game.ActiveCharacter.BlueSkill.SkillName, Anchor.Auto, color: Color.DeepSkyBlue); YellowSkill = new Paragraph(game.ActiveCharacter.YellowSkill.SkillName, Anchor.Auto, color: Color.DarkGray); OrangeSkill1 = new Paragraph(game.ActiveCharacter.OrangeSkills.First().SkillName, Anchor.Auto, color: Color.DarkGray); OrangeSkill2 = new Paragraph(game.ActiveCharacter.OrangeSkills.Last().SkillName, Anchor.Auto, color: Color.DarkGray); RedSkill1 = new Paragraph(game.ActiveCharacter.RedSkills.First().SkillName, Anchor.Auto, color: Color.DarkGray); RedSkill2 = new Paragraph(game.ActiveCharacter.RedSkills.ElementAt(1).SkillName, Anchor.Auto, color: Color.DarkGray); RedSkill3 = new Paragraph(game.ActiveCharacter.RedSkills.Last().SkillName, Anchor.Auto, color: Color.DarkGray); SkillTab.panel.AddChild(BlueSkill); SkillTab.panel.AddChild(YellowSkill); SkillTab.panel.AddChild(OrangeSkill1); SkillTab.panel.AddChild(OrangeSkill2); SkillTab.panel.AddChild(RedSkill1); SkillTab.panel.AddChild(RedSkill2); SkillTab.panel.AddChild(RedSkill3); SkillTab.button.Padding = new Vector2(0, 0); SkillTab.button.Size = new Vector2(100, 50); SkillTab.panel.Offset = new Vector2(0, -50); SkillTab.button.ButtonParagraph.Scale = .9f; TabData tab1 = tabs.AddTab("Player"); life = new Paragraph("Life: " + (game.ActiveCharacter.DeathThreshold - game.ActiveCharacter.GetDamageTaken()).ToString()); moves = new Paragraph("Moves Left: " + (game.ActiveCharacter.movesLeft).ToString()); level = new Paragraph("Level: " + (game.ActiveCharacter.Level).ToString()); experience = new Paragraph("Experience: " + (game.ActiveCharacter.Experience).ToString()); forfeitMove = new Button("Forfeit Move", anchor: Anchor.BottomCenter); forfeitMove.OnClick = (Entity btn) => { game.ActiveCharacter.movesLeft--; }; tab1.button.Padding = new Vector2(0, 0); tab1.button.Size = new Vector2(100, 50); tab1.button.Offset = new Vector2(0, -50); tab1.panel.Offset = new Vector2(0, -50); tab1.panel.AddChild(new Header(game.ActiveCharacter.CharacterName)); tab1.panel.AddChild(new HorizontalLine()); tab1.panel.AddChild(life); tab1.panel.AddChild(moves); tab1.panel.AddChild(level); tab1.panel.AddChild(experience); tab1.panel.AddChild(forfeitMove); tab1.button.ButtonParagraph.Scale = .9f; BackPackTab = tabs.AddTab("Backpack"); BackPackTab.panel.AddChild(new Header("Items")); BackPackTab.button.Padding = new Vector2(0, 0); BackPackTab.button.Size = new Vector2(100, 50); BackPackTab.button.ButtonParagraph.Scale = .9f; TabData tab3 = tabs.AddTab("Team"); tab3.button.Padding = new Vector2(0, 0); tab3.button.Size = new Vector2(100, 50); tab3.button.ButtonParagraph.Scale = .9f; UserInterface.Active.AddEntity(playerPanel); UserInterface.Active.AddEntity(movePanel); whosTurn = MoveState.PlayerTurn; applyMoveTiles(game); //Initialize Dice and Zombies Zombie.Initialize(game); Dice.Initialize(game); }
public void Load(TmxMap map, LevelSettings settings) { Instance = this; // Instantiate the containers entityContainer = new GameObject("31 Entities"); Transform ecTransform = entityContainer.transform; wallContainer = new GameObject("Walls"); wallContainer.transform.parent = ecTransform; floorContainer = new GameObject("Floors"); floorContainer.transform.parent = ecTransform; collectibleContainer = new GameObject("Collectibles"); collectibleContainer.transform.parent = ecTransform; pushableContainer = new GameObject("Pushables"); pushableContainer.transform.parent = ecTransform; accessibleContainer = new GameObject("Accessibles"); accessibleContainer.transform.parent = ecTransform; switchableContainer = new GameObject("Switchables"); switchableContainer.transform.parent = ecTransform; shadeContainer = new GameObject("Shades"); shadeContainer.transform.parent = ecTransform; ExplosionContainer = new GameObject("Explosions"); ExplosionContainer.transform.parent = ecTransform; triggerContainer = new GameObject("Triggers"); triggerContainer.transform.parent = ecTransform; var leverGateManager = new LeverGateManager(); int type1 = 0; int type2 = 0; int type3 = 0; List <Lever> levers = new List <Lever>(); List <Gate> gates = new List <Gate>(); //entities = new Entity[map.Width, map.Height]; //walls = new bool[map.Width, map.Height]; //Initialized with a seed, so that every time the randomizer produces the same level var random = new System.Random(0); LevelEntry[,] data = new LevelEntry[map.Width, map.Height]; LevelSettings.FloorType[,] floorData = new LevelSettings.FloorType[map.Width, map.Height]; int playerX = 0; int playerY = 0; foreach (var layer in map.Layers) { var tiles = layer.Tiles; foreach (var tile in tiles) { var tileType = (TileType)tile.Gid; if (tileType == TileType.Empty) { continue; } if (!prefabs.ContainsKey(tileType)) { continue; } var indexX = tile.X; var indexY = map.Height - tile.Y - 1; var position = new Vector2(indexX, indexY); var prefab = prefabs[tileType]; var gameObj = Object.Instantiate(prefab, position, Quaternion.identity) as GameObject; var transform = gameObj.transform; GameObject parent; var entity = gameObj.GetComponent <Entity>(); if (entity != null) { data[tile.X, map.Height - tile.Y - 1].Entity = entity; } //Calling this adds some variety between levels, but ensures the same level will always look the same random.NextDouble(); #region Read tile types switch (tileType) { case TileType.Player: parent = entityContainer; //GameObject ovPrefab = Object.Instantiate(overlayFloor, position, Quaternion.identity) as GameObject; // ovPrefab.renderer.sortingOrder = FloorOrder + 1; //ovPrefab.transform.parent = overlayContainer.transform; playerX = tile.X; playerY = tile.Y; /*GameObject obj = new GameObject(); * obj.transform.position = position; * obj.transform.parent = overlayContainer.transform; * var ovRen = obj.AddComponent<SpriteRenderer>(); * ovRen.sprite = AssetHelper.instance.SurewashIcon; * ovRen.sortingOrder = FloorOrder + 1; * ovRen.material = prefab.renderer.material;*/ break; case TileType.Crate: case TileType.Trolley: case TileType.Explosive: case TileType.Plant: parent = pushableContainer; break; //case TileType.Sanitizer: // parent = collectibleContainer; // break; case TileType.HeatPad: parent = accessibleContainer; transform.GetComponent <Renderer>().sortingOrder = FloorOrder + 2; floorData[indexX, indexY] = LevelSettings.FloorType.HeatPad; data[tile.X, tile.Y].FloorType = LevelSettings.FloorType.HeatPad; break; case TileType.Door: case TileType.DoorVertical: case TileType.Fountain: case TileType.GateClean: parent = accessibleContainer; break; case TileType.Patient: parent = switchableContainer; transform.GetComponent <SpriteRenderer>().sortingOrder = PlaceDepth(transform.position.y); //-Mathf.RoundToInt(4 * transform.position.y) - 1; break; case TileType.Lever1: parent = accessibleContainer; var lever1 = gameObj.GetComponent <Lever>(); lever1.LeverGateType = LeverGateType.Type1; levers.Add(lever1); type1 = 1; leverGateManager.Add(lever1); break; case TileType.Lever2: parent = accessibleContainer; var lever2 = gameObj.GetComponent <Lever>(); lever2.LeverGateType = LeverGateType.Type2; levers.Add(lever2); type2 = 1; leverGateManager.Add(lever2); break; case TileType.Lever3: parent = accessibleContainer; var lever3 = gameObj.GetComponent <Lever>(); levers.Add(lever3); type3 = 1; lever3.LeverGateType = LeverGateType.Type3; leverGateManager.Add(lever3); break; case TileType.Gate1: case TileType.Gate1Vertical: parent = accessibleContainer; var gate1 = gameObj.GetComponent <Gate>(); gates.Add(gate1); type1 = 1; gate1.LeverGateType = LeverGateType.Type1; leverGateManager.Add(gate1); break; case TileType.Gate2: case TileType.Gate2Vertical: parent = accessibleContainer; var gate2 = gameObj.GetComponent <Gate>(); gates.Add(gate2); type2 = 1; gate2.LeverGateType = LeverGateType.Type2; leverGateManager.Add(gate2); break; case TileType.Gate3: case TileType.Gate3Vertical: parent = accessibleContainer; var gate3 = gameObj.GetComponent <Gate>(); gate3.LeverGateType = LeverGateType.Type3; gates.Add(gate3); type3 = 1; leverGateManager.Add(gate3); break; case TileType.Gate1Open: transform.GetComponent <Renderer>().sortingOrder = PlaceWall(transform.position.y) + UsableOffset; goto case TileType.Gate1VerticalOpen; case TileType.Gate1VerticalOpen: parent = accessibleContainer; var gate1Open = gameObj.GetComponent <Gate>(); gate1Open.LeverGateType = LeverGateType.Type1; gate1Open.Open = true; leverGateManager.Add(gate1Open); gates.Add(gate1Open); type1 = 1; break; case TileType.Gate2Open: transform.GetComponent <Renderer>().sortingOrder = PlaceWall(transform.position.y) + UsableOffset; goto case TileType.Gate2VerticalOpen; case TileType.Gate2VerticalOpen: parent = accessibleContainer; var gate2Open = gameObj.GetComponent <Gate>(); gate2Open.LeverGateType = LeverGateType.Type2; gate2Open.Open = true; leverGateManager.Add(gate2Open); gates.Add(gate2Open); type2 = 1; break; case TileType.Gate3Open: case TileType.Gate3VerticalOpen: parent = accessibleContainer; var gate3Open = gameObj.GetComponent <Gate>(); gate3Open.LeverGateType = LeverGateType.Type3; gate3Open.Open = true; leverGateManager.Add(gate3Open); gates.Add(gate3Open); type3 = 1; break; case TileType.LaserDown: parent = wallContainer; var laserDown = gameObj.GetComponent <LaserEmitter>(); laserDown.Direction = Direction.Down; break; case TileType.LaserUp: parent = wallContainer; var laserUp = gameObj.GetComponent <LaserEmitter>(); laserUp.Direction = Direction.Up; break; case TileType.LaserRight: parent = wallContainer; var laserRight = gameObj.GetComponent <LaserEmitter>(); laserRight.Direction = Direction.Right; break; case TileType.LaserLeft: parent = wallContainer; var laserLeft = gameObj.GetComponent <LaserEmitter>(); laserLeft.Direction = Direction.Left; break; case TileType.Mirror: parent = switchableContainer; break; case TileType.MirrorInverse: parent = switchableContainer; var mirror = gameObj.GetComponent <Mirror>(); mirror.Forward = false; break; case TileType.Wall: parent = wallContainer; transform.GetComponent <SpriteRenderer>().sortingOrder = PlaceWall(transform.position.y); //walls[tile.X, tile.Y] = true; data[tile.X, tile.Y].Wall = gameObj; break; case TileType.Terminal: parent = accessibleContainer; transform.GetComponent <Renderer>().sortingOrder = PlaceWall(transform.position.y) + 1; break; case TileType.Floor: parent = floorContainer; transform.GetComponent <SpriteRenderer>().sortingOrder = FloorOrder; var blenderer = gameObj.GetComponent <Renderer>() as SpriteRenderer; float brighter = ((float)random.NextDouble() - 0.5f) * 0.02f; blenderer.color = new Color( blenderer.color.r + (float)(random.NextDouble() * 0) + brighter, blenderer.color.g + (float)(random.NextDouble() * 0.01f) + brighter, blenderer.color.b + (float)(random.NextDouble() * 0.015f) + brighter, blenderer.color.a); data[tile.X, tile.Y].Floor = gameObj; break; case TileType.Carpet: parent = floorContainer; transform.GetComponent <SpriteRenderer>().sortingOrder = FloorOrder + 1; break; default: throw new Exception("Impossibru!"); } #endregion transform.parent = parent.transform; } } int x; int y; //bool breakOff = false; /*for (x = 0; x < map.Width; ++x) { * for (y = 0; y < map.Height; ++y) { * if (data[x, y].Wall != null && (y == map.Height - 1 || data[x, y + 1].Wall == null)) { * if (random.Next(0, 5) == 3) { * //var position = new Vector3(x, map.Height - y - 1, 0); * //GameObject ovWall = Object.Instantiate(overlayWall) as GameObject; * //ovWall.transform.parent = overlayContainer.transform; * //ovWall.transform.position = position + new Vector3(0, wallOverlayOffset, 0); * //ovWall.renderer.sortingOrder = PlaceWall(position.y) + 1; * (data[x, y].Wall.renderer as SpriteRenderer).sprite = AssetHelper.instance.SureWall; * breakOff = true; * break; * } * } * } * if (breakOff) { * break; * } * }*/ int maxWall = 0; for (x = map.Width - 1; x >= 0; --x) { for (y = 0; y < map.Height; ++y) { if (data[x, y].Wall != null) { if (x > maxWall) { maxWall = x; } } } } for (y = map.Height - 1; y >= 0; --y) { if (data[maxWall, y].Wall != null) { (data[maxWall, y].Wall.GetComponent <Renderer>() as SpriteRenderer).sprite = AssetHelper.instance.SureWall; break; } } if (data[playerX, playerY].Floor != null) { (data[playerX, playerY].Floor.GetComponent <Renderer>() as SpriteRenderer).sprite = AssetHelper.instance.SureFloor; } if (type1 + type2 + type3 == 1) { foreach (var gate in gates) { gate.LeverGateType = LeverGateType.None; } foreach (var lever in levers) { lever.LeverGateType = LeverGateType.None; } } for (x = 0; x < map.Width; ++x) { for (y = 0; y < map.Height; ++y) { switch (data[x, y].FloorType) { case LevelSettings.FloorType.HeatPad: var frend = data[x, y].Floor.GetComponent <Renderer>() as SpriteRenderer; frend.color = new Color( frend.color.r - 0.2f, frend.color.g - 0.2f, frend.color.b - 0.2f); break; } } } #region Make Gradients for (int i = 0; i < map.Height; ++i) { var shadeLeft = makeGradient(map, -1, i); shadeLeft.GetComponent <Renderer>().material = shadeLeft.left; var shadeRight = makeGradient(map, map.Width, i); shadeRight.GetComponent <Renderer>().material = shadeRight.right; } for (int j = 0; j < map.Width; ++j) { var shadeTop = makeGradient(map, j, -1); shadeTop.GetComponent <Renderer>().material = shadeTop.top; var shadeBot = makeGradient(map, j, map.Height); shadeBot.GetComponent <Renderer>().material = shadeBot.bottom; } var shadeTL = makeGradient(map, -1, -1); shadeTL.GetComponent <Renderer>().material = shadeTL.topLeft; var shadeTR = makeGradient(map, map.Width, -1); shadeTR.GetComponent <Renderer>().material = shadeTR.topRight; var shadeBL = makeGradient(map, -1, map.Height); shadeBL.GetComponent <Renderer>().material = shadeBL.bottomLeft; var shadeBR = makeGradient(map, map.Width, map.Height); shadeBR.GetComponent <Renderer>().material = shadeBR.bottomRight; #endregion foreach (var obj in map.Objects) { switch (obj.objectType) { case TmxObject.ObjectType.Tile: GetIndex(obj.position, out x, out y); Entity e = data[x, y].Entity; if (e != null) { Trigger a = new Trigger(obj, settings); e.AddTriggerAction(a); } break; default: var triggerObj = Entity.Create <RectTrigger>("RectTrigger"); var recTrigger = triggerObj.GetComponent <RectTrigger>(); recTrigger.action = new Trigger(obj, settings); recTrigger.transform.parent = triggerContainer.transform; break; } } settings.SetFloorData(floorData); }
private static void DrawEllipse(Graphics g, Pen pen, Brush brush, TmxMap tmxMap, TmxObjectEllipse tmxEllipse) { RectangleF rc = new RectangleF(new PointF(0, 0), tmxEllipse.Size); if (tmxMap.Orientation == TmxMap.MapOrientation.Isometric) { // Circles and ellipses not supported in Insometric mode g.FillEllipse(Brushes.Red, rc); g.DrawEllipse(Pens.White, rc); Logger.WriteWarning(" Not supported (isometric): {0}", tmxEllipse.GetNonEmptyName()); } else if (!tmxEllipse.IsCircle()) { // We don't really support ellipses, especially as colliders g.FillEllipse(Brushes.Red, rc); g.DrawEllipse(Pens.White, rc); Logger.WriteWarning(" Not supported (ellipse): {0}", tmxEllipse.GetNonEmptyName()); } else { g.FillEllipse(brush, rc); g.DrawEllipse(pen, rc); } }
public TileMap() { map = new TmxMap(@"D:\Daten\tiled\Level\level.tmx"); }
private static void DrawGridHex(Graphics g, TmxMap tmxMap) { // Our collection of points to render HashSet<Point> points = new HashSet<Point>(); // Note: borrowed heavily from Tiled source (HexagonalRenderer::drawGrid) int tileWidth = tmxMap.TileWidth & ~1; int tileHeight = tmxMap.TileHeight & ~1; int sideLengthX = tmxMap.StaggerAxis == TmxMap.MapStaggerAxis.X ? tmxMap.HexSideLength : 0; int sideLengthY = tmxMap.StaggerAxis == TmxMap.MapStaggerAxis.Y ? tmxMap.HexSideLength : 0; int sideOffsetX = (tmxMap.TileWidth - sideLengthX) / 2; int sideOffsetY = (tmxMap.TileHeight - sideLengthY) / 2; int columnWidth = sideOffsetX + sideLengthX; int rowHeight = sideOffsetY + sideLengthY; bool staggerX = tmxMap.StaggerAxis == TmxMap.MapStaggerAxis.X; // Determine the tile and pixel coordinates to start at Point startTile = new Point(0, 0); Point startPos = TmxMath.TileCornerInScreenCoordinates(tmxMap, startTile.X, startTile.Y); Point[] oct = new Point[8] { new Point(0, tileHeight - sideOffsetY), new Point(0, sideOffsetY), new Point(sideOffsetX, 0), new Point(tileWidth - sideOffsetX, 0), new Point(tileWidth, sideOffsetY), new Point(tileWidth, tileHeight - sideOffsetY), new Point(tileWidth - sideOffsetX, tileHeight), new Point(sideOffsetX, tileHeight) }; if (staggerX) { // Odd row shifting is applied in the rendering loop, so un-apply it here if (TmxMath.DoStaggerX(tmxMap, startTile.X)) { startPos.Y -= rowHeight; } for (; startTile.X < GetMaxTilesWide(tmxMap); startTile.X++) { Point rowTile = startTile; Point rowPos = startPos; if (TmxMath.DoStaggerX(tmxMap, startTile.X)) { rowPos.Y += rowHeight; } for (; rowTile.Y < GetMaxTilesHigh(tmxMap); rowTile.Y++) { points.Add(TmxMath.AddPoints(rowPos, oct[1])); points.Add(TmxMath.AddPoints(rowPos, oct[2])); points.Add(TmxMath.AddPoints(rowPos, oct[3])); points.Add(TmxMath.AddPoints(rowPos, oct[4])); bool isStaggered = TmxMath.DoStaggerX(tmxMap, startTile.X); bool lastRow = rowTile.Y == tmxMap.Height - 1; bool lastColumn = rowTile.X == tmxMap.Width - 1; bool bottomLeft = rowTile.X == 0 || (lastRow && isStaggered); bool bottomRight = lastColumn || (lastRow && isStaggered); if (bottomRight) { points.Add(TmxMath.AddPoints(rowPos, oct[5])); points.Add(TmxMath.AddPoints(rowPos, oct[6])); } if (lastRow) { points.Add(TmxMath.AddPoints(rowPos, oct[6])); points.Add(TmxMath.AddPoints(rowPos, oct[7])); } if (bottomLeft) { points.Add(TmxMath.AddPoints(rowPos, oct[7])); points.Add(TmxMath.AddPoints(rowPos, oct[0])); } rowPos.Y += tileHeight + sideLengthY; } startPos.X += columnWidth; } } else { // Odd row shifting is applied in the rendering loop, so un-apply it here if (TmxMath.DoStaggerY(tmxMap, startTile.Y)) { startPos.X -= columnWidth; } for (; startTile.Y < tmxMap.Height; startTile.Y++) { Point rowTile = startTile; Point rowPos = startPos; if (TmxMath.DoStaggerY(tmxMap, startTile.Y)) { rowPos.X += columnWidth; } for (; rowTile.X < tmxMap.Width; rowTile.X++) { points.Add(TmxMath.AddPoints(rowPos, oct[0])); points.Add(TmxMath.AddPoints(rowPos, oct[1])); points.Add(TmxMath.AddPoints(rowPos, oct[2])); points.Add(TmxMath.AddPoints(rowPos, oct[3])); points.Add(TmxMath.AddPoints(rowPos, oct[4])); bool isStaggered = TmxMath.DoStaggerY(tmxMap, startTile.Y); bool lastRow = rowTile.Y == tmxMap.Height - 1; bool lastColumn = rowTile.Y == tmxMap.Width - 1; bool bottomLeft = lastRow || (rowTile.X == 0 && !isStaggered); bool bottomRight = lastRow || (lastColumn && isStaggered); if (lastColumn) { points.Add(TmxMath.AddPoints(rowPos, oct[4])); points.Add(TmxMath.AddPoints(rowPos, oct[5])); } if (bottomRight) { points.Add(TmxMath.AddPoints(rowPos, oct[5])); points.Add(TmxMath.AddPoints(rowPos, oct[6])); } if (bottomLeft) { points.Add(TmxMath.AddPoints(rowPos, oct[7])); points.Add(TmxMath.AddPoints(rowPos, oct[0])); } rowPos.X += tileWidth + sideLengthX; } startPos.Y += rowHeight; } } foreach (var p in points) { RectangleF rc = new RectangleF(p.X, p.Y, PreviewImage.GridSize, PreviewImage.GridSize); rc.Offset(-PreviewImage.GridSize * 0.5f, -PreviewImage.GridSize * 0.5f); g.DrawRectangle(Pens.Black, rc.X, rc.Y, rc.Width, rc.Height); } }
public static EntityFactory genPlayer(Scene scene, TiledRlStage stage, PosUtil posUtil, TmxMap map) { var factory = EntityFactory.begin(scene, "player", posUtil); return(factory .body(new Vec2i(7, 7), Dir9.S, true, false) .actor(new Engine.Beh.Player(factory.entity), 3) .viewWodi8(Content.Chips.Pochi.Animals.Kuma04) .add(new FovComp(stage, map)) .performance(50, 10, 5) .add(new Player())); }
private static void DrawColliders(Graphics g, TmxMap tmxMap, float scale) { for (int l = 0; l < tmxMap.Layers.Count; ++l) { TmxLayer layer = tmxMap.Layers[l]; if (layer.Visible == true && layer.Ignore != TmxLayer.IgnoreSettings.Collision) { foreach (TmxLayer collisionLayer in layer.CollisionLayers) { TmxObjectType type = tmxMap.ObjectTypes.GetValueOrDefault(collisionLayer.Name); Color lineColor = type.Color; Color polyColor = Color.FromArgb(128, lineColor); DrawLayerColliders(g, collisionLayer, polyColor, lineColor, scale); } } } }