static void AddTile(float x, float y, TileLayer tileLayer, GameObject tilePrefab, int tileId) { GameObject newTile; Vector2 position; position.x = x; position.y = y; string newName = "Tile JustInCase " + sortingCount.ToString(); switch (tileLayer) { case TileLayer.FLOOR: newName = "Tile Floor " + tileId.ToString(); break; case TileLayer.WALL: newName = "Tile Wall " + tileId.ToString(); break; case TileLayer.FOG: newName = "Tile Fog " + tileId.ToString(); break; } Basics.assert(GameObject.Find(newName) == null); newTile = Instantiate(tilePrefab, position, Quaternion.identity) as GameObject; newTile.name = newName; //newTile.transform.parent = gameObject.transform; newTile.GetComponent<SpriteRenderer>().sortingOrder = sortingCount; sortingCount++; }
private static void TrackPlaymodeChanges(TileLayer layer, TileLayerEditor editor) { TileLayer[] layers = (TileLayer[])GameObject.FindObjectsOfType(typeof(TileLayer)); if(Application.isPlaying && keepRealtimeChanges) { playModeTiles[layer] = layer.tileData.Clone(); } else { if(wasPlayingLastUpdate && keepRealtimeChanges && !Application.isPlaying) { foreach(TileLayer l in layers) { if(playModeTiles.Contains(l)) { l.tileData = (TileInstance[])playModeTiles[l]; editor.RebuildMap(l.layerSize); TileLayerEditor.InstantiatePrefabs(l); } } //Undo.RegisterSceneUndo("Playmode changes to tile layers"); } playModeTiles.Clear(); } wasPlayingLastUpdate = Application.isPlaying; }
public void PaintArea(TileLayer layer, int tileX, int tileY, Rectangle selectorRect, TileType tileType) { int selectorTileWidth = selectorRect.Width / layer.TileSize; int selectorTileHeight = selectorRect.Height / layer.TileSize; for (int x = 0; x < selectorTileWidth; x++) { for (int y = 0; y < selectorTileHeight; y++) { Rectangle tileRect = new Rectangle(selectorRect.X + (x * layer.TileSize), selectorRect.Y + (y * layer.TileSize), layer.TileSize, layer.TileSize); Tile replacementTile = TileFactory.Get(tileType, tileRect, layer.TilesetTileWidth); bool inBounds = tileX + x >= 0 && tileY + y >= 0 && tileX + x < layer.Width && tileY + y < layer.Height; if (inBounds) { if (layer.GetTile(tileX + x, tileY + y).Value == replacementTile.Value) continue; layer.SetTile(tileX + x, tileY + y, replacementTile); } } } }
public bool Initialize(MapFile mf, EngineType et, List<string> customRulesININames, List<string> customArtININames) { if (et == EngineType.AutoDetect) { Logger.Fatal("Engine type needs to be known by now!"); return false; } Engine = et; TheaterType = Theater.TheaterTypeFromString(mf.ReadString("Map", "Theater")); FullSize = mf.FullSize; LocalSize = mf.LocalSize; _tiles = new TileLayer(FullSize.Size); LoadAllObjects(mf); if (!IgnoreLighting) _lighting = mf.Lighting; else _lighting = new Lighting(); _wayPoints.AddRange(mf.Waypoints); if (!LoadInis(customRulesININames, customArtININames)) { Logger.Fatal("Ini files couldn't be loaded"); return false; } Logger.Info("Overriding rules.ini with map INI entries"); _rules.MergeWith(mf); return true; }
private void LoadMapButton_Click(object sender, RoutedEventArgs e) { WebClient webClient = new WebClient(); string uri = string.Format("http://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial?supressStatus=true&key={0}", BingKeyTextBox.Text); webClient.OpenReadCompleted += (s, a) => { if (a.Error == null) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(BingAuthentication)); BingAuthentication bingAuthentication = serializer.ReadObject(a.Result) as BingAuthentication; a.Result.Close(); if (bingAuthentication.authenticationResultCode == "ValidCredentials") { ESRI.ArcGIS.Client.Bing.TileLayer tileLayer = new TileLayer() { ID = "BingLayer", LayerStyle = TileLayer.LayerType.Road, ServerType = ServerType.Production, Token = BingKeyTextBox.Text }; MyMap.Layers.Insert(0, tileLayer); BingKeyGrid.Visibility = System.Windows.Visibility.Collapsed; InvalidBingKeyTextBlock.Visibility = System.Windows.Visibility.Collapsed; } else InvalidBingKeyTextBlock.Visibility = System.Windows.Visibility.Visible; } else InvalidBingKeyTextBlock.Visibility = System.Windows.Visibility.Visible; }; webClient.OpenReadAsync(new System.Uri(uri)); }
/// <summary> /// Creates a new TileMap with specified dimensions /// </summary> /// <param name="width">The width of the TileMap, to be passed to each layer</param> /// <param name="height">The height of the TileMap, to be passed to each layer</param> /// <param name="layers">The number of layers to construct on initialization</param> public TileMap(int width, int height, int layers) { Layers = new TileLayer[layers]; Width = width; Height = height; for (var i = 0; i < layers; i++) { Layers[i] = new TileLayer(width, height); } }
public override void Use(TileLayer layer, int tileX, int tileY, Rectangle selectorRect, TileType tileType) { int tileWidth = selectorRect.Width / layer.TileSize; int tileHeight = selectorRect.Height / layer.TileSize; for (int x = 0; x < layer.Width; x += tileWidth) for (int y = 0; y < layer.Height; y += tileHeight) PaintArea(layer, x, y, selectorRect, tileType); }
public DebugDrawingSurfaceWindow(DrawingSurface ds, TileLayer tiles, Theater t, Map.Map map) : this() { _drawingSurface = ds; _tiles = tiles; _theater = t; _map = map; ds.Unlock(); pictureBox1.Image = ds.Bitmap; }
public MapTile(ushort dx, ushort dy, ushort rx, ushort ry, short rz, short tilenum, ushort subtile, TileLayer layer, short setnum = 0) { Dx = dx; Dy = dy; Rx = rx; Ry = ry; Z = rz; TileNum = tilenum; SetNum = setnum; SubTile = subtile; Layer = layer; }
public override void Use(TileLayer layer, int tileX, int tileY, Rectangle selectorRect, TileType tileType) { for (int x = 0; x < selection.Rectangle.Width / layer.TileSize; x += selectorRect.Width / layer.TileSize) { for (int y = 0; y < selection.Rectangle.Height / layer.TileSize; y += selectorRect.Height / layer.TileSize) { Rectangle r = new Rectangle(selectorRect.X, selectorRect.Y, selection.Rectangle.Width - (x * layer.TileSize), selection.Rectangle.Height - (y * layer.TileSize)); PaintArea(layer, x + (selection.Rectangle.X / layer.TileSize), y + (selection.Rectangle.Y / layer.TileSize), r, tileType); } } }
public static void OnSceneGUI_Ammendum(TileLayer layer, UniTileTemplate manager, TileLayerEditor editor) { Handles.BeginGUI(); GUILayout.BeginArea(new Rect(20, 40, 150, 40)); keepRealtimeChanges = GUILayout.Toggle(keepRealtimeChanges, "Keep Playmode Changes", "Button"); GUILayout.EndArea(); Handles.EndGUI(); TrackPlaymodeChanges(layer, editor); }
public EditTileTypesForm(TileLayer customLayer, BindingList<TileType> tileTypes) { InitializeComponent(); ChangeMade = false; this.customLayer = customLayer; this.tileTypes = tileTypes; listTileTypes.DataSource = tileTypes; listTileTypes.SelectedIndex = 0; }
public static ILayer CreateLayer() { var url = "https://www.openbasiskaart.nl/mapcache/tms/1.0.0/osm@rd"; var tileSource = TmsTileSourceBuilder.Build(url, true, DefaultCache); var tileLayer = new TileLayer(tileSource) { Name = "openbasiskaart.nl" }; tileLayer.Attribution.Text = "© OpenStreetMap contributors (via openbasiskaart.nl)"; tileLayer.Attribution.Url = "https://www.openstreetmap.org/copyright"; return(tileLayer); }
public void drawUsingPlayerCamera() { spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null, cam.CurrentCameraTranslation); TileLayer background = _tManager.getLayer("background"); List <Tile> surroundingTiles = background.adjacentTo(_tManager.CurrentTile); for (int x = 0; x < background.MapWidth; x++) { for (int y = 0; y < background.MapHeight; y++) { int textureIndex = background.Tiles[y, x].Id; Texture2D texture = tileTextures[textureIndex]; // Draw surrounding tiles if (surroundingTiles.Contains(background.Tiles[y, x])) { spriteBatch.Draw(texture, new Rectangle(x * tileWidth, y * tileHeight, tileWidth, tileHeight), new Color(255, 255, 255)); } else { spriteBatch.Draw(texture, new Rectangle(x * tileWidth, y * tileHeight, tileWidth, tileHeight), Color.White); } } } // draw the character spriteBatch.DrawString(font, Math.Round(SimplePlayerSprite.currentTime, 2).ToString(), new Vector2(GraphicsDevice.Viewport.Width / 2, 10), Color.White, 0, Vector2.Zero, 3, SpriteEffects.None, 1); spriteBatch.Draw(_character, new Rectangle(_tManager.CurrentTile.X * tileWidth, _tManager.CurrentTile.Y * tileHeight, tileWidth, tileHeight), Color.White); //spriteBatch.Draw(_character, _characterRect, Color.White); spriteBatch.End(); spriteBatch.Begin(); //spriteBatch.DrawString(debug, cameraPosition.ToString(), new Vector2(10, 10), Color.White); //spriteBatch.DrawString(debug, new Vector2(_characterRect.X, _characterRect.Y).ToString(), new Vector2(10, 30), Color.White); spriteBatch.End(); }
public int GetBlock(string layerName, int x, int y) { if (x < 0 || y < 0 || x > map.Width - 1 || y > map.Height - 1) { return(0); } TileLayer layer = map.TileLayers[layerName]; if (layer.Tiles[x][y] != null) { return(layer.Tiles[x][y].SourceID + 1 - sourceIdOffset[layerName]); } return(0); }
public TileObject[] GetObjectsOnLayer(Vector2Int cell, TileLayer layer) { List <TileObject> result = new List <TileObject>(); foreach (var obj in ObjectMatrix[cell.X, cell.Y]) { if (obj.Layer == layer) { result.Add(obj); } } return(result.ToArray()); }
public override void AddLayer(Layer layer, Variant attributes) { // Add the layer to the map view mapView.Layers.Add(layer); // Check if the layer has info window. In that case will add a custom UTF grid event listener to the layer. Variant infoWindow = attributes.GetObjectElement("infowindow"); if (infoWindow.Type == VariantType.VariantTypeObject) { TileLayer tileLayer = (TileLayer)layer; tileLayer.UTFGridEventListener = new MyUTFGridEventListener(vectorLayer, infoWindow); } }
public override void Excute() { if (form.TextureList.Items.Count > 0 && form.TextureList.SelectedItem != null) { LayerStateBeforeRecursion = new TileLayer(currentLayer.TileMapArray); foreach (Texture2D text in currentLayer.TexturesList) { LayerStateBeforeRecursion.AddTexture(text); } fillCounter = 5000; FillCellIndex((int)form.TileX, (int)form.TileY, -1); } }
private void Draw(Vector2 gridPos) { TileLayer layer = target as TileLayer; if (layer == null) { return; } if (gridPos != prevPos) { DrawTiles(gridPos); } }
private void picTileset_Click(object sender, EventArgs e) { MouseEventArgs args = e as MouseEventArgs; int clickedX = args.X / tileSize + hScroll.Value; int clickedY = args.Y / tileSize + vScroll.Value; if (GraphicsManager.TileIndex.GetPosition(currentTileset, new Loc(clickedX, clickedY)) > 0) { chosenTileset = currentTileset; if ((Control.ModifierKeys & Keys.Shift) != 0) { chkAnimationMode.Checked = false; //multiselect Loc endTile = new Loc(clickedX, clickedY); multiSelect = endTile - chosenTile + Loc.One; RefreshTilesetPic(); tilePreview.SetChosenAnim(new TileBrush(new TileLayer(chosenTile, chosenTileset), multiSelect)); } else { chosenTile = new Loc(clickedX, clickedY); multiSelect = Loc.One; RefreshTilesetPic(); if (!inAnimMode) { tilePreview.SetChosenAnim(new TileBrush(new TileLayer(chosenTile, chosenTileset), multiSelect)); } else { TileLayer chosenAnim = tilePreview.GetChosenAnim(); if (lbxFrames.SelectedIndex > -1) { chosenAnim.Frames[lbxFrames.SelectedIndex] = new TileFrame(chosenTile, chosenTileset); } else { chosenAnim.Frames.Add(new TileFrame(chosenTile, chosenTileset)); } tilePreview.SetChosenAnim(new TileBrush(chosenAnim, multiSelect)); UpdateAnimFrames(); } } } }
private void removeLayerButton_Click(object sender, EventArgs e) { string filename = TilelayerListBox.SelectedItem as string; if (currentLayer != null) { tileMap.Layers.Remove(currentLayer); layerDict.Remove(filename); TilelayerListBox.Items.Remove(TilelayerListBox.SelectedItem); currentLayer = null; AdjustScrollBars(); } }
private void ClearMap() { TileLayer layer = target as TileLayer; if (layer == null) { return; } layer.tileData = null; this.ClearGroups(layer); if (layer.parent != null) { RebuildMap(layer.parent, layer.parent.layerSize); } }
void UpdateAnimFrames() { TileLayer chosenAnim = tilePreview.GetChosenAnim(); int selection = lbxFrames.SelectedIndex; lbxFrames.Items.Clear(); for (int ii = 0; ii < chosenAnim.Frames.Count; ii++) { lbxFrames.Items.Add(chosenAnim.Frames[ii].ToString()); } if (selection < lbxFrames.Items.Count) { lbxFrames.SelectedIndex = selection; } }
private void visibleToolStripMenuItem_Click(object sender, EventArgs e) { TreeNode node = this.projectTree.SelectedNode; if (node != null) { if (node.Tag is TileLayer <Tile> ) { TileLayer <Tile> layer = (TileLayer <Tile>)node.Tag; layer.Visible = !layer.Visible; this.projectTree.Invalidate(); } } }
public void SetDestinationTileLoad(TileCoordinates input) { //Debug.Log("[SetDestinationTileLoad] input is null : " + (input == null)); tileLayer = GameManager.Instance.GetTileLayer(0); if (input != null) { destinationTile = tileLayer.GetTileAsComponent(input.x, input.y); } else { destinationTile = null; } //Debug.Log("[SetDestinationTileLoad] destTile is null: " + (destinationTile == null)); }
public DebugDrawingSurfaceWindow(DrawingSurface ds, TileLayer tiles, Theater t, Map.Map map) : this() { _drawingSurface = ds; _tiles = tiles; _theater = t; _map = map; _cells = (_map.FullSize.Width * 2 - 1) * _map.FullSize.Height; ds.Unlock(); // map is pre-rendered bitmap, shadow/heightmap are rendered on demand canvasMap.Image = ds.Bitmap; }
public static bool IsUsing(this TileLayer tileLayer, TileSet tileSet) { for (int y = 0; y < tileLayer.height; ++y) { for (int x = 0; x < tileLayer.width; ++x) { if (tileLayer.tiles[x, y].gid > 0 && tileSet.ContainsTile(tileLayer.tiles[x, y].gid)) { return(true); } } } return(false); }
public static TileLayer CreateMbTilesLayer(string path) { TileLayer mbTilesLayer = null; try { //DisplayAlert("test", File.ReadAllText(mbpath), "ok"); var mbTilesTileSource = new BruTile.MbTiles.MbTilesTileSource(new SQLiteConnectionString(path, true)); mbTilesLayer = new TileLayer(mbTilesTileSource); return(mbTilesLayer); } catch (Exception ex) { return(mbTilesLayer); } }
public Room CreateRoom() { Room room = new Room(this); TileLayer structureLayer = this.Tilemap.GetLayer("structure"); foreach (Tile tile in structureLayer.Tiles) { if (tile.Tileset.GetPropertiesOfGid(tile.Gid) != null) { BlockType type = Block.GetBlockTypeFromString(tile.Tileset.GetPropertiesOfGid(tile.Gid)["type"]); room.AddBlock((int)tile.Position.X, (int)tile.Position.Y, type); } } return(room); }
private void btnAddFrame_Click(object sender, EventArgs e) { TileLayer chosenAnim = tilePreview.GetChosenAnim(); if (lbxFrames.SelectedIndex > -1) { chosenAnim.Frames.Insert(lbxFrames.SelectedIndex, new TileFrame(chosenTile, chosenTileset)); } else { chosenAnim.Frames.Add(new TileFrame(chosenTile, chosenTileset)); } tilePreview.SetChosenAnim(new TileBrush(chosenAnim, multiSelect)); UpdateAnimFrames(); }
private void OsmClick(object sender, RoutedEventArgs e) { MapControl.Map.Layers.Clear(); var tileSource = new HttpTileSource(new GlobalSphericalMercator(0, 20), "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", new[] { "a", "b", "c" }, name: "OSM"); var tileLayer = new TileLayer(tileSource) { Name = "OSM" }; MapControl.Map.Layers.Add(tileLayer); LayerList.Initialize(MapControl.Map.Layers); MapControl.ZoomToFullEnvelope(); MapControl.Refresh(); }
public void SetBrush(TileLayer anim) { if (anim.Frames.Count > 0) { chosenTileset = anim.Frames[0].Sheet; currentTileset = chosenTileset; chosenTile = anim.Frames[0].TexLoc; multiSelect = Loc.One; inAnimMode = (anim.Frames.Count > 1); tilePreview.SetChosenAnim(new TileBrush(anim, multiSelect)); //refresh RefreshTileSelect(); } }
private void MapForm_Load(object sender, EventArgs e) { //Add BackgroundLayer mbMap.Map.BackgroundLayer.Add(m_layers["Google"]); m_currentLayer = m_layers["Google"]; changeBgLayer("None"); //Add Beijing Map this.mbMap.Map.Layers.Add(shapeLayer); shapeLayer.Enabled = miShowShapeLayer.Checked; // Edgeid layer //this.mbMap.Map.Layers.Add(edgeIdLayer); edgeIdLayer.Enabled = miShowEdgeId.Checked && miShowShapeLayer.Checked; //Add the static layer for symbol this.mbMap.Map.Layers.Add(markerLayer); //Add a pushpin layer this.mbMap.Map.Layers.Add(outputLayer); //Add std output layer this.mbMap.Map.Layers.Add(stdOutputLayer); this.mbMap.Map.Layers.Add(greenPointLayer); this.mbMap.Map.Layers.Add(redPointLayer); //Initialize the timer initTimer(); //Config the active tool mbMap.ActiveTool = MapBox.Tools.Pan; mbMap.ActiveToolChanged += new MapBox.ActiveToolChangedHandler(mbMap_ActiveToolChanged); //Move and zoom the map IMathTransform mathTransform = LayerTools.Wgs84toGoogleMercator.MathTransform; Envelope geom = GeoAPI.CoordinateSystems.Transformations.GeometryTransform.TransformBox( //new Envelope(-122.298, -123.399, 46.9695, 47.9896), new Envelope(116.298, 116.399, 39.9695, 39.9896), mathTransform); this.mbMap.Map.ZoomToBox(geom); //this.mbMap.Map.ZoomToBox(shapeLayer.Envelope); RefreshMap(); }
private void AddSources() { var norgeskart = KartverketSources.Create( KartverketTileSource.NorgeskartBakgrunn, FetchFactory.CreateRetryFetcher(httpClient)); norgeskart.PersistentCache = new ReadOnlyFileCache(GetCacheFolder(norgeskart.Name), "png"); var norgeskartLayer = new TileLayer(norgeskart) { Name = norgeskart.Name, Enabled = true }; mapView.Map.Layers.Add(norgeskartLayer); var sjøkart = KartverketSources.Create( KartverketTileSource.SjøkartRaster, FetchFactory.CreateRetryFetcher(httpClient)); sjøkart.PersistentCache = new ReadOnlyFileCache(GetCacheFolder(sjøkart.Name), "png"); var sjøkartLayer = new TileLayer(sjøkart) { Name = sjøkart.Name, Enabled = false }; mapView.Map.Layers.Add(sjøkartLayer); var osm = KnownTileSources.Create( KnownTileSource.OpenStreetMap, tileFetcher: FetchFactory.CreateRetryFetcher(httpClient)); osm.PersistentCache = new ReadOnlyFileCache(GetCacheFolder(osm.Name), "png"); var osmLayer = new TileLayer(osm) { Name = osm.Name, Enabled = false }; mapView.Map.Layers.Add(osmLayer); selectedSource = norgeskart; sources.Add(norgeskart); sources.Add(sjøkart); sources.Add(osm); layers.Add(norgeskartLayer); layers.Add(sjøkartLayer); layers.Add(osmLayer); }
public void drawUsingTileCamera() { int tileMapWidth = tileMap.GetLength(1); // number of columns int tileMapHeight = tileMap.GetLength(0); // number of rows spriteBatch.Begin(); // Draw the background texture TileLayer background = _tManager.getLayer("background"); List <Tile> surroundingTiles = background.adjacentTo(_tManager.CurrentTile); for (int x = 0; x < background.MapWidth; x++) { for (int y = 0; y < background.MapHeight; y++) { int textureIndex = background.Tiles[y, x].Id; Texture2D texture = tileTextures[textureIndex]; // Draw surrounding tiles if (surroundingTiles.Contains(background.Tiles[y, x])) { spriteBatch.Draw(texture, new Rectangle(x * tileWidth - (int)cameraPosition.X, y * tileHeight - (int)cameraPosition.Y, tileWidth, tileHeight), new Color(255, 255, 255)); } else { spriteBatch.Draw(texture, new Rectangle(x * tileWidth - (int)cameraPosition.X, y * tileHeight - (int)cameraPosition.Y, tileWidth, tileHeight), Color.White); } } } // draw the character spriteBatch.Draw(_character, new Rectangle(_tManager.CurrentTile.X * tileWidth - (int)cameraPosition.X, _tManager.CurrentTile.Y * tileHeight - (int)cameraPosition.Y, tileWidth, tileHeight), Color.White); spriteBatch.End(); }
public void SetUpNewGame() { Texture2D tiles = GameRef.Content.Load <Texture2D>(@"Tiles\tileset1"); TileSet set = new TileSet(8, 8, 32, 32); set.Texture = tiles; TileLayer background = new TileLayer(200, 200); TileLayer edge = new TileLayer(200, 200); TileLayer building = new TileLayer(200, 200); TileLayer decor = new TileLayer(200, 200); map = new TileMap(set, background, edge, building, decor, "test-map"); map.FillEdges(); map.FillBuilding(); map.FillDecoration(); camera = new Camera(); }
void LoadTileLayer(DMapLayerTiles l, float z) { if (this.transform == null) { return; } GameObject tileLayer = new GameObject(l.name, typeof(TileLayer)); tileLayer.hideFlags = HideFlags.DontSave; tileLayer.transform.parent = this.transform; tileLayer.transform.position = tileLayer.transform.position + new Vector3(0, 0, z); TileLayer tlcomp = tileLayer.GetComponent <TileLayer>(); tlcomp.layerdata = l; _layers.Add(l.name, tileLayer); }
public TileLayer GetLayer() { if (layer == null) { layer = World.Instance.TileMap.GetLayer(Layer); } if (layer != null) { if (layer.Name != this.Layer) { layer = World.Instance.TileMap.GetLayer(this.Layer); } } return(layer); }
/// <summary> /// Updates the object based on the given neighbours. If cross connect is used, it will determine it's own neighbours. /// </summary> /// <param name="neighbourObjects"></param> public void UpdateAll(PlacedTileObject[] neighbourObjects) { if (CrossConnectAllowed) { // Hacky way to find which layer the tileObjectSO is TileLayer layer = GetComponent <PlacedTileObject>().GetLayer(); for (int i = 0; i < neighbourObjects.Length; i++) { UpdateAllOnDirection((Direction)i, layer); } } else { UpdateAllOnLayer(neighbourObjects); } }
/// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); font = Content.Load<SpriteFont>("font"); hudTex = Content.Load<Texture2D>("hud"); tilesSprite = new VoxelSprite(16, 16, 16); LoadVoxels.LoadSprite(Path.Combine(Content.RootDirectory, "tiles.vxs"), ref tilesSprite); gameMap = Content.Load<Map>("1"); tileLayer = (TileLayer)gameMap.GetLayer("tiles"); MapObjectLayer spawnLayer = (MapObjectLayer)gameMap.GetLayer("spawns"); gameWorld = new VoxelWorld(gameMap.Width, 11, 1); for(int yy=0;yy<11;yy++) for(int xx=0;xx<12;xx++) if(tileLayer.Tiles[xx,yy]!=null) gameWorld.CopySprite(xx*Chunk.X_SIZE, yy*Chunk.Y_SIZE, 0, tilesSprite.AnimChunks[tileLayer.Tiles[xx,yy].Index-1]); scrollColumn = 12; gameCamera = new Camera(GraphicsDevice, GraphicsDevice.Viewport); gameCamera.Position = new Vector3(0f, gameWorld.Y_SIZE * Voxel.HALF_SIZE, 0f); gameCamera.Target = gameCamera.Position; gameHero = new Hero(); gameHero.LoadContent(Content, GraphicsDevice); enemyController = new EnemyController(GraphicsDevice); enemyController.LoadContent(Content, spawnLayer); projectileController = new ProjectileController(GraphicsDevice); projectileController.LoadContent(Content); particleController = new ParticleController(GraphicsDevice); powerupController = new PowerupController(GraphicsDevice); powerupController.LoadContent(Content); gameStarfield = new Starfield(GraphicsDevice); drawEffect = new BasicEffect(GraphicsDevice) { World = gameCamera.worldMatrix, View = gameCamera.viewMatrix, Projection = gameCamera.projectionMatrix, VertexColorEnabled = true, }; }
public TileMap( TileSet tileSet, TileLayer groundLayer, TileLayer edgeLayer, TileLayer buildingLayer, TileLayer decorationLayer, string mapName) : this(tileSet, mapName) { GroundLayer = groundLayer; EdgeLayer = edgeLayer; BuildingLayer = buildingLayer; DecorationLayer = decorationLayer; MapWidth = groundLayer.Width; MapHeight = groundLayer.Height; }
private void ShowContextMenu(TreeNode selectedNode, Point mouseLocation) { switch (selectedNode.Name.ToLower()) { case "projectnode": { ProjectMenu.Show(mouseLocation); break; } case "mapsnode": { MapsMenu.Show(mouseLocation); break; } case "mapnode": { MapMenu.Show(mouseLocation); break; } case "tilesnode": { TilesMenu.Show(mouseLocation); break; } case "layernode": { if (selectedNode.Tag is TileLayer <Tile> ) { TileLayer <Tile> layer = (TileLayer <Tile>)selectedNode.Tag; visibleToolStripMenuItem.Checked = layer.Visible; LayerMenu.Show(mouseLocation); } break; } case "tilefilternode": { TilesMenu.Show(mouseLocation); break; } } }
void DidChangeSwitcher (object sender = null, EventArgs e = null) { var title = switcher.TitleAt (switcher.SelectedSegment); var selectedFloor = Convert.ToInt32 (title); if (floor != selectedFloor) { // Clear existing tileLayer, if any. if (tilelayer != null) tilelayer.Map = null; // Create a new TileLayer with the new floor choice. tilelayer = UrlTileLayer.FromUrlConstructor ((x, y, zoom) => { var url = string.Format ("http://www.gstatic.com/io2010maps/tiles/9/L{0}_{1}_{2}_{3}.png", floor, zoom, x, y); return new NSUrl (url); }); tilelayer.Map = mapView; floor = selectedFloor; } }
public void Initialize() { var map = GetSection("Map"); string[] size = map.ReadString("Size").Split(','); FullSize = new Rectangle(int.Parse(size[0]), int.Parse(size[1]), int.Parse(size[2]), int.Parse(size[3])); Tiles = new TileLayer(FullSize.Width, FullSize.Height); size = map.ReadString("LocalSize").Split(','); LocalSize = new Rectangle(int.Parse(size[0]), int.Parse(size[1]), int.Parse(size[2]), int.Parse(size[3])); Logger.Info("Reading map"); Logger.Debug("Reading tiles"); ReadTiles(); Logger.Debug("Reading map overlay"); ReadOverlay(); Logger.Debug("Reading map terrain objects"); ReadTerrain(); Logger.Debug("Reading map smudge objects"); ReadSmudges(); Logger.Debug("Reading infantry on map"); ReadInfantry(); Logger.Debug("Reading vehicles on map"); ReadUnits(); Logger.Debug("Reading aircraft on map"); ReadAircraft(); Logger.Debug("Reading map structures"); ReadStructures(); Logger.Debug("Waypoints"); ReadWaypoints(); Lighting = new Lighting(GetOrCreateSection("Lighting")); }
//SPRITE SHEET private void CreateSpriteList(TileLayer layer) { Texture2D myTexture = (Texture2D)Resources.Load(layer.TexturePath.Trim('/').Split('.')[0]) as Texture2D; int amountOfTiles = myTexture.width/layer.TileSet.TileWidth * myTexture.height/layer.TileSet.TileHeight; x = 0; y = 0; //Separate the texture into multiple sprites for ease of access, as Unity reads texture coordinates from the bottom left. for(int i = 0 ; i < amountOfTiles; i++) { if(x > 0 && x == myTexture.width/layer.TileSet.TileWidth) { x = 0; y++; } mySprite = Sprite.Create(myTexture, new Rect(32*x, myTexture.height - 32*(y+1), layer.TileSet.TileWidth, layer.TileSet.TileHeight), new Vector2(0,0), layer.TileSet.TileWidth); //Add the clipped sprite to the sprite list mySpriteList.Add(mySprite); x++; } }
/** Draws a tile layer with a given camera. */ public static void draw(TileLayer layer, int gridTileWidth, int gridTileHeight, Camera camera = null) { int tileMinX, tileMinY, tileMaxX, tileMaxY; if (camera != null) { tileMinX = (camera.mCornerX - layer.maxTileWidth) / layer.genericTileWidth; tileMinY = (camera.mCornerY - layer.maxTileHeight) / layer.genericTileHeight; tileMaxX = tileMinX + (targetWidth+ layer.maxTileWidth) / layer.genericTileWidth+2; tileMaxY = tileMinY + (targetHeight+ layer.maxTileHeight) / layer.genericTileHeight+2; } else { tileMinX = 0; tileMinY = 0; tileMaxX = (targetWidth) / layer.genericTileWidth+1; tileMaxY = (targetHeight) / layer.genericTileHeight+1; } int limX = Math.Min(layer.tileCountX, tileMaxX); int limY = Math.Max(tileMinY, 0); Util.Util.insertionSort<Sprite, Transformable>(layer.objects); int objectIndex = 0; for (int yid = Math.Min(layer.tileCountY, tileMaxY)-1; yid >= limY; --yid) { int y = yid * layer.genericTileHeight; //Draw objects until they start going below the current layer for (; objectIndex < layer.objects.Count; ++objectIndex) { if (layer.objects[objectIndex].rect.y < y) break; draw(layer.objects[objectIndex], camera); } for (int xid = Math.Max(tileMinX, 0); xid < limX; ++xid) { int tileId = layer.tiles[xid, yid]; if (tileId < 0) continue; Sprite tile = layer.tileCache[tileId]; int x = xid * layer.genericTileWidth; //Bind tileset textures tile.tileset.bind(); //Get screen coordinates of the tile in pixels Util.Rect rect = tile.rect; rect.x = x; rect.y = y; if (camera != null) camera.worldToScreen(ref rect); if (!Util.Maths.isRectVisible(rect, targetWidth, targetHeight)) continue; //Set matrix uniforms shaderIndexedBitmapSprite["orthoMatrix"].SetValue( Util.Maths.matrixPixelProjection(rect, targetWidth, targetHeight)); shaderIndexedBitmapSprite["uvMatrix"].SetValue(tile.uvMatrix(tile.tileset.width, tile.tileset.height)); //Draw LowLevelRenderer.draw(); } } //Draw all remaining objects for (; objectIndex < layer.objects.Count; ++objectIndex) draw(layer.objects[objectIndex], camera); }
private void addLayerButton_Click(object sender, EventArgs e) { newLayerForm form = new newLayerForm(); form.ShowDialog(); if (form.OKPressed) { TileLayer tileLayer = new TileLayer( int.Parse(form.width.Text), int.Parse(form.height.Text)); layerDict.Add(form.name.Text, tileLayer); tileMap.Layers.Add(tileLayer); layerListBox.Items.Add(form.name.Text); if (tileMap.CollisionLayer == null) { tileMap.CollisionLayer = new CollisionLayer( int.Parse(form.width.Text), int.Parse(form.height.Text)); } AdjustScrollBars(); } }
private void removeLayerButton_Click(object sender, EventArgs e) { if (currentLayer != null) { string filename = layerListBox.SelectedItem as string; layerListBox.Items.Remove(layerListBox.SelectedItem); layerDict.Remove(filename); tileMap.Layers.Remove(currentLayer); if (layerListBox.Items.Count == 0) tileMap.CollisionLayer = null; currentLayer = null; AdjustScrollBars(); } }
private void layerListBox_SelectedIndexChanged(object sender, EventArgs e) { if (layerListBox.SelectedItem != null) { currentLayer = layerDict[layerListBox.SelectedItem as string]; alphaSlider.Value = (int)(currentLayer.Alpha * 100); } }
public ObjectSorter(Theater t, TileLayer map) { _map = map; _t = t; }
public void OnInspectorGUI(TileLayer layer, UniTileTemplate selection, TileLayerEditor editor) { if(layer.material == null) return; useScrollView = EditorGUILayout.Toggle("Use scrollview", useScrollView); float w = Mathf.Min(Screen.width, layer.material.mainTexture.width); //Mathf.Min(rect.width,layer.material.mainTexture.width); float scale = w / layer.material.mainTexture.width; float h = layer.material.mainTexture.height * scale; Rect rect = GUILayoutUtility.GetLastRect(); float top = rect.yMax; int tilesX = (int)Mathf.Floor((float)layer.material.mainTexture.width / (layer.tileSize.x + layer.borderSize.x * 2f)); int tileX1 = (int)Mathf.Floor((float)selection.selectedTile.id % (float)tilesX); int tileY1 = (int)Mathf.Floor((float)selection.selectedTile.id / (float)tilesX); int tileX2 = (int)Mathf.Floor((float)selection.selectedTileEnd.id % (float)tilesX); int tileY2 = (int)Mathf.Floor((float)selection.selectedTileEnd.id / (float)tilesX); int tileXMin=Mathf.Min(tileX1, tileX2); int tileYMin=Mathf.Min(tileY1, tileY2); int tileXMax=Mathf.Max(tileX1, tileX2); int tileYMax=Mathf.Max(tileY1, tileY2); int tileWidth = tileXMax - tileXMin + 1; int tileHeight = tileYMax - tileYMin + 1; float tempTop = top; if(useScrollView) { scale = 1; w = layer.material.mainTexture.width; h = layer.material.mainTexture.height; float scrollWidth = Screen.width-25; float scrollHeight = h+10; scrollPos = EditorGUILayout.BeginScrollView(scrollPos, false, false, GUILayout.Height(scrollHeight), GUILayout.Width(scrollWidth)); GUILayout.Label("", GUILayout.Width(scrollWidth), GUILayout.Height(scrollHeight)); tempTop = 0; } else { GUILayout.Label("", GUILayout.Width(w), GUILayout.Height(h)); } GUI.DrawTexture(new Rect(0,tempTop,w,h), layer.material.mainTexture); if(selection.selectedTile.id>=0 && !selection.tilesPicked) { GUIStyle style = new GUIStyle(GUI.skin.customStyles[0]); style.normal.background = SelectionTexture; GUI.Box( new Rect( (tileXMin * (layer.tileSize.x + layer.borderSize.x * 2f) + layer.borderSize.x) * scale, tempTop + (tileYMin * (layer.tileSize.y + layer.borderSize.y * 2f) + layer.borderSize.y) * scale, (tileWidth * (layer.tileSize.x + layer.borderSize.x * 2f) - layer.borderSize.x * 2f) * scale, (tileHeight * (layer.tileSize.y + layer.borderSize.y * 2f) - layer.borderSize.y * 2f) * scale ), "", style ); } if(useScrollView) { EditorGUILayout.EndScrollView(); } if(Event.current!=null) { if(Event.current.type==EventType.MouseDown) { if(Event.current.button==0) { Vector2 pos = Event.current.mousePosition; if(useScrollView) pos += scrollPos; this.selecting=true; selection.tilesPicked = false; if(pos.x>=0 && pos.x<=layer.material.mainTexture.width * scale && pos.y>=top && pos.y<=top+layer.material.mainTexture.height * scale) { editor.selectedTemplate = - 1; selection.selectedTile.id = selection.selectedTileEnd.id = (int)Mathf.Floor((pos.x / scale) /(layer.tileSize.x + layer.borderSize.x * 2f)) + (int)(Mathf.Floor((pos.y - top)/(scale * (layer.tileSize.y + layer.borderSize.y * 2f))) * tilesX); if(Event.current.clickCount==2) { TileEditorWindow window = TileEditorWindow.CreateInstance<TileEditorWindow>(); window.Setup(editor, selection.selectedTilesList); window.ShowUtility(); } } } else { selection.tilesPicked = false; selection.selectedTile.id = -1; selection.selectedTileEnd.id = -1; } } if(Event.current.type==EventType.mouseDrag) { if(selecting) { Vector2 pos = Event.current.mousePosition; if(useScrollView) pos += scrollPos; if(pos.x>=0 && pos.x<=layer.material.mainTexture.width * scale && pos.y>=top && pos.y<=top+layer.material.mainTexture.height * scale) { selection.selectedTileEnd.id = (int)Mathf.Floor((pos.x / scale) /(layer.tileSize.x + layer.borderSize.x * 2f)) + (int)(Mathf.Floor((pos.y - top)/(scale * (layer.tileSize.y + layer.borderSize.y * 2f))) * tilesX); selection.tilesPicked = false; selection.selectedTilesWidth = tileXMax - tileXMin + 1; selection.selectedTilesList = new TileInstance[(tileXMax - tileXMin + 1) * (tileYMax - tileYMin + 1)]; HandleUtility.Repaint (); if(selection.selectedTile.id>=0) { for(int i = tileXMin; i<= tileXMax; i++) { for(int j = tileYMin; j<= tileYMax; j++) { int x = i-tileXMin; int y = j-tileYMin; selection.selectedTilesList[x + y * selection.selectedTilesWidth] = new TileInstance(i + j * tilesX); } } } else { selection.selectedTilesList[0]=new TileInstance(-1); } UniTileMarker.Instance.Init(selection); } } } if(Event.current.type==EventType.MouseUp) { selection.tilesPicked = false; selection.selectedTilesWidth = tileXMax - tileXMin + 1; selection.selectedTilesList = new TileInstance[(tileXMax - tileXMin + 1) * (tileYMax - tileYMin + 1)]; HandleUtility.Repaint (); if(selection.selectedTile.id>=0) { for(int i = tileXMin; i<= tileXMax; i++) { for(int j = tileYMin; j<= tileYMax; j++) { int x = i-tileXMin; int y = j-tileYMin; selection.selectedTilesList[x + y * selection.selectedTilesWidth] = new TileInstance(i + j * tilesX); } } } else { selection.selectedTilesList[0]=new TileInstance(-1); } UniTileMarker.Instance.Init(selection); this.selecting=false; } } }
public abstract void Use(TileLayer layer, int tileX, int tileY, Rectangle selectorRect, TileType tileType);
public void SetLayerVisible(TileLayer layer, bool value) { if (layer == TileLayer.Objects) { this.drawObjects = value; } else { this.tileMap.SetLayerVisible(layer, value); } }
public void SetEditLayer(int layer) { this.curEditMode = EditModes.Tiles; if (layer == -3) { this.curEditMode = EditModes.Chests; } if (layer == -2) { this.curEditMode = EditModes.Doors; } if (layer == -1) { this.curEditMode = EditModes.Objects; } if (layer == 0) { this.editLayer = TileLayer.Back2; } if (layer == 1) { this.editLayer = TileLayer.Back1; } if (layer == 2) { this.editLayer = TileLayer.Fore; } }
public bool SetupScene(string mapFile) { this.player = GameEngine.Game.GetPlayer(); this.mapFilename = mapFile; this.objects = new List<BaseObject>(); this.deletedObjects = new List<GameObject>(); this.addedObjects = new List<GameObject>(); this.gameObjects = new List<GameObject>(); this.doors = new List<Door>(); this.editLayer = TileLayer.Fore; this.copyRectangleSource = new Rectangle(0, 0, 0, 0); return this.LoadMap(mapFile, true, true); }
private void RenderMap() { try { txtLoading.Visibility = Visibility.Collapsed; waitCursor.Visibility = Visibility.Collapsed; ESRI.ArcGIS.Client.Bing.TileLayer layer = new TileLayer(); layer.InitializationFailed += new EventHandler<EventArgs>(layer_InitializationFailed); if (ImageryRadioButton.Visibility == System.Windows.Visibility.Collapsed) { layer.Token = Configuration.GetNewInstance().Settings.MapServiceKey; layer.LayerStyle = TileLayer.LayerType.AerialWithLabels; } else if (StreetsRadioButton.Visibility == System.Windows.Visibility.Collapsed) { layer.Token = Configuration.GetNewInstance().Settings.MapServiceKey; layer.LayerStyle = TileLayer.LayerType.Road; } else { layer.Token = null; } GraphicsLayer pointLayer = new GraphicsLayer(); pointLayer.ID = "pointLayer"; GraphicsLayer zoneLayer = new GraphicsLayer(); zoneLayer.ID = "zoneLayer"; GraphicsLayer textLayer = new GraphicsLayer(); textLayer.ID = "textLayer"; ContextMenu menu = new ContextMenu(); MenuItem mnuMarker = new MenuItem(); mnuMarker.Header = "Add marker"; mnuMarker.Click += new RoutedEventHandler(mnuMarker_Click); menu.Items.Add(mnuMarker); MenuItem mnuRadius = new MenuItem(); mnuRadius.Header = "Add zone"; mnuRadius.Click += new RoutedEventHandler(mnuRadius_Click); menu.Items.Add(mnuRadius); MenuItem mnuText = new MenuItem(); mnuText.Header = "Add label"; mnuText.Click += new RoutedEventHandler(mnuText_Click); menu.Items.Add(mnuText); MenuItem mnuClear = new MenuItem(); mnuClear.Header = "Remove all layers"; mnuClear.Click += new RoutedEventHandler(mnuClear_Click); menu.Items.Add(mnuClear); myMap = new Map(); myMap.Background = Brushes.White; myMap.Height = MapContainer.ActualHeight; myMap.Width = MapContainer.ActualWidth; myMap.WrapAround = true; myMap.ContextMenu = menu; myMap.Layers.Add(layer); myMap.Layers.Add(pointLayer); myMap.Layers.Add(textLayer); myMap.Layers.Add(zoneLayer); //<esri:ArcGISDynamicMapServiceLayer ID="California" Opacity="0.4" VisibleLayers="8,10" // Url="http://maverick.arcgis.com/ArcGIS/rest/services/California/MapServer" /> //ArcGISDynamicMapServiceLayer govData = new ArcGISDynamicMapServiceLayer(); //govData.Url = "http://services.nationalmap.gov/ArcGIS/rest/services/govunits/MapServer"; ////govData.Url = "http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer"; //govData.VisibleLayers = new int[] { 19,21,22 }; //myMap.Layers.Add(govData); myMap.MouseMove += new MouseEventHandler(myMap_MouseMove); myMap.MouseRightButtonDown += new MouseButtonEventHandler(myMap_MouseRightButtonDown); myMap.Loaded += new RoutedEventHandler(myMap_Loaded); MapContainer.Children.Add(myMap); ESRI.ArcGIS.Client.Behaviors.ConstrainExtentBehavior extentBehavior = new ESRI.ArcGIS.Client.Behaviors.ConstrainExtentBehavior(); extentBehavior.ConstrainedExtent = new Envelope(new MapPoint(int.MinValue, -12000000), new MapPoint(int.MaxValue, 12000000)); System.Windows.Interactivity.Interaction.GetBehaviors(myMap).Add(extentBehavior); nav = new Navigation(); nav.Margin = new Thickness(5); nav.HorizontalAlignment = HorizontalAlignment.Left; nav.VerticalAlignment = VerticalAlignment.Top; nav.Map = myMap; MapContainer.Children.Add(nav); slider = new TimeSlider(); slider.Name = "slider"; slider.PlaySpeed = new TimeSpan(0, 0, 1); slider.Height = 20; slider.TimeMode = TimeMode.CumulativeFromStart; slider.MinimumValue = DateTime.Now.Subtract(TimeSpan.FromDays(7)).ToUniversalTime(); slider.MaximumValue = DateTime.Now.ToUniversalTime(); slider.Value = new TimeExtent(slider.MinimumValue, slider.MinimumValue.AddHours(2)); slider.Intervals = TimeSlider.CreateTimeStopsByTimeInterval(new TimeExtent(slider.MinimumValue, slider.MaximumValue), new TimeSpan(0, 2, 0, 0)); slider.Padding = new Thickness(0, 100, 0, 0); slider.ValueChanged += new EventHandler<TimeSlider.ValueChangedEventArgs>(slider_ValueChanged); areaSeries.Loaded += new RoutedEventHandler(areaSeries_Loaded); stkTimeLapse.Children.Add(slider); //grdMapDef.Background = Brushes.Black; //myMap.Background = Brushes.Black; SetBackgroundColor(defaultBackgroundColor); AddLayerList(); if (MapLoaded != null) { MapLoaded(this, false); } } catch (Exception ex) { // } finally { } }
void UpdateBaseLayer(Section section, string selection) { if (section.Type != SectionType.Language) { currentOSM = section.OSM.Value; currentSelection = selection; } if (section.Type == SectionType.Vector) { if (currentOSM == "nutiteq.osm") { // Nutiteq styles are bundled with the SDK, we can initialize them via constuctor if (currentSelection == "default") { currentLayer = new CartoOnlineVectorTileLayer(CartoBaseMapStyle.CartoBasemapStyleDefault); } else if (currentSelection == "gray") { currentLayer = new CartoOnlineVectorTileLayer(CartoBaseMapStyle.CartoBasemapStyleGray); } else { currentLayer = new CartoOnlineVectorTileLayer(CartoBaseMapStyle.CartoBasemapStyleDark); } } else if (currentOSM == "mapzen.osm") { // Mapzen styles are all bundled in one .zip file. // Selection contains both the style name and file name (cf. Sections.cs in Shared) string fileName = currentSelection.Split(':')[0]; string styleName = currentSelection.Split(':')[1]; // Create a style set from the file and style BinaryData styleAsset = AssetUtils.LoadAsset("styles/" + fileName + ".zip"); var package = new ZippedAssetPackage(styleAsset); CompiledStyleSet styleSet = new CompiledStyleSet(package, styleName); // Create datasource and style decoder var source = new CartoOnlineTileDataSource(currentOSM); var decoder = new MBVectorTileDecoder(styleSet); currentLayer = new VectorTileLayer(source, decoder); } Menu.LanguageChoiceEnabled = true; ResetLanguage(); } else if (section.Type == SectionType.Raster) { // We know that the value of raster will be Positron or Darkmatter, // as Nutiteq and Mapzen use vector tiles // Additionally, raster tiles do not support language choice string url = (currentSelection == "positron") ? Urls.Positron : Urls.DarkMatter; TileDataSource source = new HTTPTileDataSource(1, 19, url); currentLayer = new RasterTileLayer(source); // Language choice not enabled in raster tiles Menu.LanguageChoiceEnabled = false; } else if (section.Type == SectionType.Language) { if (currentLayer is RasterTileLayer) { // Raster tile language chance is not supported return; } UpdateLanguage(selection); } MapView.Layers.Clear(); MapView.Layers.Add(currentLayer); Menu.Hide(); currentListener = null; currentListener = MapView.InitializeVectorTileListener(VectorLayer); }
//ART LAYER private void GenerateLayer(TileLayer myLayer) { Material defaultMaterial = (Material)Resources.Load("Materials/Sprites") as Material; //Get the default sprite material x = 0; y = 0; int z = myLayer.CurrentLayer; for(int i = 0; i < myLayer.LayerWidth * myLayer.LayerHeight; i++) { int index = int.Parse(myLayer.LayerData[i]); if(x > 0 && x >= myLayer.LayerWidth) { x = 0; y--; } if(index > 0) { GameObject tileObject = new GameObject("Tile"); SpriteRenderer myRenderer = tileObject.AddComponent<SpriteRenderer>(); //Set the position of the GameObjects tileObject.transform.parent = myLayer.GetRoot.transform; tileObject.transform.position = new Vector3(x,y,z); //Set the material and sprite on the GameObject for rendering purposes myRenderer.material = defaultMaterial; myRenderer.sprite = mySpriteList[index-1]; } x++; } }
/*-- Generate your level based on the XML file passed above --*/ void Start() { myTileSet = null; myTileLayers = new List<TileLayer>(); mySpriteList = new List<Sprite> (); int currentLayer = 0; //The current layer being generated - Used to help draw Z displacement /*-- LOAD THE XML FILE --*/ XmlDocument myXML = new XmlDocument(); myXML.Load (new System.IO.StringReader(myTextAsset.text)); XmlNodeList myNodeList = myXML.DocumentElement.ChildNodes; foreach(XmlNode outerNode in myNodeList) { switch(outerNode.Name) { /*-- TILE SET -- */ case "tileset": //Tile data string tileSetName = outerNode.Attributes["name"].InnerText; int firstGid = int.Parse(outerNode.Attributes["firstgid"].InnerText); int tileWidth = int.Parse(outerNode.Attributes["tilewidth"].InnerText); int tileHeight = int.Parse(outerNode.Attributes["tileheight"].InnerText); //Image data string imageSource = outerNode.FirstChild.Attributes["source"].InnerText; int imageWidth = int.Parse (outerNode.FirstChild.Attributes["width"].InnerText); int imageHeight = int.Parse (outerNode.FirstChild.Attributes["height"].InnerText); //Create a new Tileset object for use in the layer myTileSet = new TileSet(imageSource, tileSetName, firstGid, tileWidth, tileHeight, imageWidth, imageHeight); break; /*-- LAYER -- */ case "layer": //Layer Data XmlNode myDataNode = outerNode.SelectSingleNode("data"); int layerWidth = int.Parse(outerNode.Attributes["width"].InnerText); int layerHeight = int.Parse(outerNode.Attributes["height"].InnerText); string layerName = outerNode.Attributes["name"].InnerText; string dataText = myDataNode.InnerText; //Create a "root" for the layers. If it's a collision layer, ignore this step GameObject rootLayer; if(layerName != "Collision") rootLayer = new GameObject(layerName); else rootLayer = null; myTileLayer = new TileLayer(layerName, dataText, layerWidth, layerHeight, myTileSet, currentLayer, rootLayer); if(outerNode.FirstChild.Name == "properties") { //Get the "property" node of the "proeprties" node and take the inner text of the attribute value //This value corresponds to what layer this particular collision layer corresponds to string colliderFor = outerNode.FirstChild.FirstChild.Attributes["value"].InnerText; myTileLayer.ColliderFor = colliderFor; } //Create a new TileLayer object and add it to the list myTileLayers.Add(myTileLayer); currentLayer++; break; } } CreateLevelPrefab(); }
//COLLISION LAYER private void GenerateCollisionLayer(TileLayer layer) { x = 0; y = 0; GameObject rootLayer = null; for(int i = 0; i < myTileLayers.Count; i++) { if(layer.ColliderFor == myTileLayers[i].LayerName) { rootLayer = myTileLayers[i].GetRoot; } } //Generate the layer... for(int i = 0; i < layer.LayerWidth * layer.LayerHeight; i++) { int index = int.Parse (layer.LayerData[i]); if(x > 0 && x == layer.LayerWidth) { x = 0; y--; } if(index != 0 ) { GameObject collisionObject = new GameObject("Collider"); collisionObject.AddComponent<BoxCollider>(); collisionObject.GetComponent<BoxCollider>().center = new Vector3(0.5f, 0.5f, 0.5f); collisionObject.GetComponent<BoxCollider>().size = new Vector3(1.0f,1.0f,10.0f); collisionObject.transform.parent = rootLayer.transform; collisionObject.transform.position = new Vector3(x,y,0); } x++; } }