public RenderLayer(TiledRenderer renderer, string layer)
 {
     this.renderer = renderer;
     this.map      = renderer.map;
     this.layer    = map.Layers[layer];
     Build();
 }
Exemple #2
0
        public void Draw(GameTime gameTime)
        {
            for (var i = 0; i < layerCount; i++)
            {
                TmxLayer layer = tmxMap.Layers[i];
                float    depth = 1f - 0.1f * i;
                for (var j = 0; j < layer.Tiles.Count; j++)
                {
                    int gid = layer.Tiles[j].Gid;
                    if (gid != 0)
                    {
                        int tileFrame = gid - 1;
                        int column    = tileFrame % tilesetTilesWideArray[i];
                        int row       = (int)Math.Floor((double)tileFrame / (double)tilesetTilesWideArray[i]);

                        float x = (j % tmxMap.Width) * tmxMap.TileWidth;
                        float y = (float)Math.Floor(j / (double)tmxMap.Width) * tmxMap.TileHeight;

                        Rectangle tilesetRec = new Rectangle(tileWidthArray[i] * column, tileHeightArray[i] * row, tileWidthArray[i], tileHeightArray[i]);

                        world.SpriteBatch.Draw(tileArray[i], new Rectangle((int)x, (int)y, tileWidthArray[i], tileHeightArray[i]), tilesetRec, Color.White, 0, new Vector2(1, 1), SpriteEffects.None, depth);
                    }
                }
            }
        }
Exemple #3
0
        public Map(string pathName, View view)
        {
            this.view          = view;
            tmxMap             = new TmxMap(pathName);
            WidthInTiles       = tmxMap.Width;
            HeightInTiles      = tmxMap.Height;
            TileSize           = tmxMap.TileWidth;
            layers             = ConvertDrawableLayers(tmxMap.Layers);
            collisionTiles     = GetCollisionTilesLayer(tmxMap.Layers);
            matchingGidTexture = ConvertGidDict(tmxMap.Tilesets);
            mapObjects         = ConvertObjects(tmxMap.ObjectGroups);
            Width            = WidthInTiles * TileSize;
            Height           = HeightInTiles * TileSize;
            CollisionObjects = mapObjects["collision"];
            Shotguns         = new List <Sprite>();
            var shotgunImage   = new Image("images/weapons.png");
            var textureShotgun = new Texture(shotgunImage);

            foreach (var s in mapObjects["shotguns"])
            {
                var sprite = new Sprite(textureShotgun);
                sprite.TextureRect = new IntRect(423, 30, 129, 70);
                sprite.Position    = s.Position;
                sprite.Scale       = new Vector2f((float)0.3, (float)0.3);
                sprite.Rotation    = random.Next(-180, 180);
                Shotguns.Add(sprite);
            }

            Bullets = new List <Bullet>();
        }
        private void DrawVisibleTiles(SpriteBatch batch, Map map, TmxLayer layer, Camera camera)
        {
            TmxMap    mapData      = map.Data;
            Rectangle cameraBounds = camera.GetBounds();

            // calculate how many tiles to draw
            int cameraTilesWidth  = ((int)camera.Width / mapData.TileWidth) + 2;
            int cameraTilesHeight = ((int)camera.Height / mapData.TileHeight) + 2;

            // get camera position in tiles
            int xCameraStartTile = (int)((camera.Position.X - cameraBounds.Width / 2) / mapData.TileWidth);
            int yCameraStartTile = (int)((camera.Position.Y - cameraBounds.Height / 2) / mapData.TileHeight);

            int xCameraEndTile = xCameraStartTile + cameraTilesWidth;
            int yCameraEndTile = yCameraStartTile + cameraTilesHeight;

            // clamp values
            ClampValue(ref xCameraStartTile, mapData.Width);
            ClampValue(ref xCameraEndTile, mapData.Width);
            ClampValue(ref yCameraStartTile, mapData.Height);
            ClampValue(ref yCameraEndTile, mapData.Height);

            for (int y = yCameraStartTile; y < yCameraEndTile; y++)
            {
                for (int x = xCameraStartTile; x < xCameraEndTile; x++)
                {
                    TmxLayerTile tile = layer.Tiles[y * mapData.Width + x];
                    DrawTile(batch, map, tile);
                }
            }
        }
Exemple #5
0
        public void load(TmxMap map, bool createObjects)
        {
            this.map = map;
            // structural recreation
            structure    = map.GetLayer <TmxLayer>(LAYER_STRUCTURE);
            features     = map.GetLayer <TmxLayer>(LAYER_FEATURES);
            nature       = map.GetObjectGroup(LAYER_NATURE);
            worldTileset = map.Tilesets[TILESET_WORLD];
            if (NGame.context.config.enableWalls)
            {
                createWallColliders();                                   // comment out to disable wall collision
            }
            // analysis
            mapRepr        = new MapRepr();
            mapRepr.tmxMap = map;
            analyzeRooms();
            mapRepr.sng = createStructuralNavigationGraph(mapRepr.roomGraph);

            // load entities
            loadFeatures();
            if (createObjects)
            {
                loadNature();
            }

            Global.log.info("loaded data from map");
        }
Exemple #6
0
        /// <summarY>
        /// Draws the map
        /// </summarY>
        /// <param name="map">The map to draw</param>
        /// <param name="camera">The position to draw from</param>
        /// <param name="orientation">The rotation to draw from in degrees</param>
        public void RenderMap(SpriteBatch spriteBatch, Map map, Vector2 camera, float orientation, int cellSize,
                              string wallsLayer)
        {
            TmxMap mapData     = map.Data;
            int    slices      = viewport.Width;
            float  halfFov     = FOV / 2;
            float  focalLength = slices / 2 / (float)Math.Tan(halfFov);
            float  cameraAngle = orientation * (float)(Math.PI / 180.0f);

            float sliceAngle = FOV / slices;
            float beginAngle = cameraAngle - halfFov;

            // draw ceiling and floor
            spriteBatch.Draw(blankTexture, new Rectangle(0, 0, viewport.Width, viewport.Height / 2),
                             Color.FromNonPremultiplied(23, 14, 8, 255));
            spriteBatch.Draw(blankTexture, new Rectangle(0, viewport.Height / 2, viewport.Width, viewport.Height / 2),
                             Color.DarkKhaki);

            // draw all wallslices
            for (int x = 0; x < slices; x++)
            {
                float angle = beginAngle + x * sliceAngle;

                RayCaster.HitData castData;
                if (!RayCaster.RayIntersectsGrid(camera, angle, cellSize, out castData,
                                                 map.GetIsTileOccupiedFunction(wallsLayer)))
                {
                    continue;
                }

                // get the texture slice
                int          tileIndex = (int)(castData.tileCoordinates.Y * mapData.Width + castData.tileCoordinates.X);
                TmxLayer     wallLayer = mapData.Layers[wallsLayer];
                TmxLayerTile tile      = wallLayer.Tiles[tileIndex];
                TmxTileset   tileset   = map.GetTilesetForTile(tile);
                if (tileset == null)
                {
                    continue;
                }

                // fix fisheye for distance and get slice height
                float distance    = (float)(castData.rayLength * Math.Cos(angle - cameraAngle));
                int   sliceHeight = (int)(cellSize * focalLength / distance);
                zBuffer[x] = distance;

                // get drawing rectangles
                Rectangle wallRectangle    = new Rectangle(x, viewport.Height / 2 - sliceHeight / 2, 1, sliceHeight);
                Rectangle textureRectangle = map.GetSourceRectangleForTile(tileset, tile);

                textureRectangle.X =
                    (int)(textureRectangle.X + (textureRectangle.Width * castData.cellFraction) % cellSize);
                textureRectangle.Width = 1;

                // get texture tint
                float dot          = Vector2.Dot(castData.normal, Vector2.UnitY);
                Color lightingTint = Math.Abs(dot) > 0.9f ? Color.Gray : Color.White;

                spriteBatch.Draw(map.Textures[tileset], wallRectangle, textureRectangle, lightingTint);
            }
        }
Exemple #7
0
 // TODO: more efficient initialization
 static void fillWithTile(TmxLayer l, int id)
 {
     foreach (var tile in l.Tiles)
     {
         tile.Gid = id;
     }
 }
Exemple #8
0
    void DrawMesh(int tileCountX, int tileCountZ, TmxLayer layer)
    {
        //Vector3 startingPosition = new Vector3(-tileCountX / 2 - unitSize / 2, 0f, -tileCountZ / 2 - unitSize / 2);
        Vector3 startingPosition = new Vector3(-unitSize / 2, 0f, -unitSize / 2);
        int     index            = 0;

        for (int z = 0; z < tileCountZ; z++)
        {
            for (int x = 0; x < tileCountX; x++)
            {
                int tileId = layer.Tiles[(tileCountZ - z - 1) * tileCountX + x].Gid - 1;
                if (tileId == -1)
                {
                    continue;
                }
                Vector3 currentPosition = new Vector3(startingPosition.x + x * unitSize, startingPosition.y, startingPosition.z + z * unitSize);
                DrawVertex(index + 2, currentPosition);
                DrawVertex(index + 1, currentPosition, unitSize);
                DrawVertex(index, currentPosition, unitSize, unitSize);

                DrawVertex(index + 5, currentPosition);
                DrawVertex(index + 4, currentPosition, unitSize, unitSize);
                DrawVertex(index + 3, currentPosition, 0, unitSize);
                AssignUv(index, tiles[tileId], tileSize);
                index += 6;
                TileManager.main.AddTile(x, z, tileType);
            }
        }
    }
Exemple #9
0
    private void SpawnTile(TmxLayerTile tile, int x, int y, TmxLayer layer, GridLayerConfig gridLayerConfig, int layerNumber)
    {
        Transform container   = GetContainer("TileLayers");
        GridTile  spawnedTile = null;

        if (gridLayerConfig != null)
        {
            if (gridLayerConfig.OverridePrefab)
            {
                spawnedTile = Instantiate(gridLayerConfig.OverridePrefab, scene.transform);
            }
            else
            {
                spawnedTile = Instantiate(config.GridTilePrefab, scene.transform);
            }
        }
        else
        {
            spawnedTile = Instantiate(config.GridTilePrefab);
        }
        Sprite sprite = GetTileSprite(tile.Gid);

        ColliderConfig conf = GetColliderConfig(tile.Gid);

        spawnedTile.Initialize(sprite, x, y, gridLayerConfig, conf, layer.Name, layerNumber);
        GridTileLayerManager.main.AddTile(spawnedTile, layer.Name, container);
    }
Exemple #10
0
        protected override void RenderContent(RenderComposer composer)
        {
            if (ImGui.Button("Choose File"))
            {
                var explorer = new FileExplorer <TextAsset>(LoadFile);
                Parent.AddWindow(explorer);
            }

            ImGui.Text($"Current File: {_file?.Name ?? "None"}");
            if (_file == null)
            {
                return;
            }
            if (ImGui.Button("Reload"))
            {
                LoadFile(FileExplorer <TextAsset> .ExplorerLoadAsset(_file.Name));
            }

            ImGui.Text("Tile Layers");
            for (var i = 0; i < _map.TiledMap.TileLayers.Count; i++)
            {
                TmxLayer curLayer = _map.TiledMap.TileLayers[i];
                ImGui.Text($"{curLayer.Name} {curLayer.Width}x{curLayer.Height}" + (curLayer.Visible ? "" : " Hidden"));
            }

            composer.SetUseViewMatrix(true);
            composer.Render(_map);
        }
Exemple #11
0
        WorldGeoLayerEntity ProcessTmxLayer(TmxMap tmxMap, TmxLayer tmxLayer)
        {
            string tilesetName = tmxLayer.Properties["tileset"];

            if (string.IsNullOrWhiteSpace(tilesetName) ||
                tmxMap.Tilesets.ToList().FindIndex(t => t.Name == tilesetName) < 0)
            {
                throw new InvalidEntityFieldException(nameof(WorldGeoLayerEntity.Tileset), tmxLayer.Name, nameof(WorldGeoLayerEntity));
            }

            TmxTileset tmxTileset = tmxMap.Tilesets[tilesetName];

            WorldGeoLayerEntity layer = new WorldGeoLayerEntity
            {
                Name    = tmxLayer.Name,
                Tiles   = new int[tmxMap.Width, tmxMap.Height],
                Tileset = tmxTileset.Name,
                Opacity = (float)tmxLayer.Opacity,
                Visible = tmxLayer.Visible
            };

            Parallel.ForEach(tmxLayer.Tiles, tile => layer.Tiles[tile.X, tile.Y] = Math.Max(-1, tile.Gid - tmxTileset.FirstGid));

            return(layer);
        }
Exemple #12
0
        private void LoadMapLayers()
        {
            foreach (var layer in _tmxMap.Layers)
            {
                switch (layer.Name)
                {
                case Layer1Name:
                    _mapLayers[0] = layer;
                    break;

                case Layer2Name:
                    _mapLayers[1] = layer;
                    break;

                case Layer3Name:
                    _mapLayers[2] = layer;
                    break;

                case TrapName:
                    _mapLayers[3] = layer;
                    _trapLayer    = layer;
                    break;

                case ObstacleName:
                    _mapLayers[4]  = layer;
                    _obstacleLayer = layer;
                    break;

                default:
                    Log.LogMessage(string.Format("Tmx map layer [{0}] ingnored.", layer.Name));
                    break;
                }
            }
        }
Exemple #13
0
 public static void clear(this TmxLayer self)
 {
     for (int i = 0; i < self.Width * self.Height; i++)
     {
         self.Tiles[i] = null;
     }
 }
Exemple #14
0
    private CombinedMeshLayer SpawnWallLayer(TmxLayer layer, int mapHeight)
    {
        GameObject        wallPrefab = gameConfig.WallPrefab;
        CombinedMeshLayer meshLayer  = Instantiate(gameConfig.CombinedMeshLayerPrefab);

        meshLayer.Initialize(layer.Name, mapHeight);
        Transform wallContainer = GetContainer("Walls");

        meshLayer.transform.SetParent(wallContainer);
        foreach (TmxLayerTile tile in layer.Tiles)
        {
            if (tile.Gid != 0)
            {
                GameObject wall = Instantiate(wallPrefab);
                int        x    = tile.X;
                int        y    = tile.Y;
                wall.transform.position = new Vector2(x, y);
                MeshFilter meshFilter = wall.GetComponent <MeshFilter>();
                if (meshFilter != null)
                {
                    meshLayer.Add(meshFilter);
                }
                wall.transform.SetParent(GetContainer("DudWalls"));
            }
        }
        meshLayer.Build();
        return(meshLayer);
    }
Exemple #15
0
        /// <summary>
        /// Create a grid from a TileMap object.
        /// </summary>
        /// <param name="tileMap">The map to create the grid from.</param>
        /// <param name="layerId">The tile layer to create the grid from.</param>
        /// <param name="impassableTiles">The list of image ids considered impassable.</param>
        public static PathingGrid FromTileMap <T>(TileMap <T> tileMap, int layerId, int[] impassableTiles) where T : TransformRenderable
        {
            if (layerId == -1 || tileMap.TiledMap == null || layerId > tileMap.TiledMap.Layers.Count - 1)
            {
                return(null);
            }
            TmxLayer layer = tileMap.TiledMap.Layers[layerId];

            var newGrid = new PathingGrid(layer.Width, layer.Height, tileMap.TileSize);

            for (var x = 0; x < newGrid.Width; x++)
            {
                for (var y = 0; y < newGrid.Height; y++)
                {
                    int  tileId  = x + y * layer.Width;
                    int  imageId = tileMap.GetTileImageIdInLayer(tileId, layerId, out int _);
                    bool solid   = impassableTiles.IndexOf(imageId) != -1;
                    if (solid)
                    {
                        newGrid.SetWalkable(x, y, false);
                    }
                }
            }

            return(newGrid);
        }
Exemple #16
0
        /// <summary>
        /// Create the tile layer as a child entity
        /// </summary>
        /// <param name="tmxLayer">The tmx layer.</param>
        /// <param name="layerIndex">The layer index</param>
        /// <param name="previousEntities">previousEntities</param>
        private void CreateChildTileLayer(TmxLayer tmxLayer, int layerIndex, IList <Entity> previousEntities)
        {
            var tmxLayerName = tmxLayer.Name;

            Entity        layerEntity  = null;
            TiledMapLayer tileMapLayer = null;

            if (previousEntities != null)
            {
                layerEntity = previousEntities.FirstOrDefault(e => e.Tag.StartsWith(TileLayerTag) && e.Name == tmxLayerName);
                previousEntities.Remove(layerEntity);
            }

            var tileLayerOffset = new Vector2((float)tmxLayer.OffsetX, (float)tmxLayer.OffsetY);

            if (layerEntity != null)
            {
                var tileMapTransform = layerEntity.FindComponent <Transform2D>();
                tileMapLayer = layerEntity.FindComponent <TiledMapLayer>();

                if (tileMapTransform != null &&
                    tileMapLayer != null)
                {
                    tileMapTransform.LocalPosition = tileLayerOffset;
                    tileMapLayer.TmxLayerName      = tmxLayerName;
                    layerEntity.Name = tmxLayerName;
                }
                else
                {
                    this.Owner.RemoveChild(layerEntity.Name);
                    layerEntity = null;
                }
            }

            if (layerEntity == null)
            {
                tileMapLayer = new TiledMapLayer()
                {
                    TmxLayerName = tmxLayerName
                };

                layerEntity = new Entity(tmxLayerName)
                {
                    Tag = TileLayerTag
                }
                .AddComponent(tileMapLayer)
                .AddComponent(new Transform2D()
                {
                    LocalPosition = tileLayerOffset,
                    Origin        = this.transform.Origin,
                    Opacity       = (float)tmxLayer.Opacity
                })
                .AddComponent(new TiledMapLayerRenderer());
            }

            this.Owner.AddChild(layerEntity);
            this.tileLayers.Add(tmxLayerName, tileMapLayer);
        }
Exemple #17
0
        /// <summary>
        /// Unload layer
        /// </summary>
        private void UnloadLayer()
        {
            this.tiledMap  = null;
            this.tileTable = null;
            this.tiles     = null;
            this.tmxLayer  = null;

            this.isLayerLoaded = false;
        }
Exemple #18
0
 public void Init(TmxLayer tmxLayer, TmxMap map)
 {
     config = ConfigManager.main.GetConfig("GameConfig") as GameConfig;
     layer  = tmxLayer;
     width  = map.Width;
     GenerateMesh();
     DeterminePosition();
     transform.SetParent(GameManager.main.WorldParent);
 }
Exemple #19
0
        public TiledMapRenderer(TmxMap tiledMap, string collisionLayerName = null, bool shouldCreateColliders = true)
        {
            TiledMap = tiledMap;
            _shouldCreateColliders = shouldCreateColliders;

            if (collisionLayerName != null)
            {
                CollisionLayer = tiledMap.TileLayers[collisionLayerName];
            }
        }
Exemple #20
0
        public int GetTileGidInLayer(Vector2i mapPoint, TmxLayer layer)
        {
            var index = mapPoint.X + mapPoint.Y * WidthInTiles;

            if (index < 0 || index >= layer.Tiles.Count)
            {
                return(layer.Tiles[0].Gid);
            }
            return(layer.Tiles[mapPoint.X + mapPoint.Y * WidthInTiles].Gid);
        }
Exemple #21
0
        public void SetupTiles()
        {
            if (Core.Scene == null || enabled)
            {
                return;
            }
            //enabled = true;
            TmxMap map    = Core.Scene.Content.LoadTiledMap("Assets/map.tmx");
            Entity entity = Core.Scene.CreateEntity("tiled-map");

            TiledMapRenderer tmr = entity.AddComponent(new TiledMapRenderer(map, "Collision", true));
            TmxLayer         CustomCollisionLayer = (TmxLayer)map.GetLayer("CustomCollision");

            foreach (TmxLayerTile tile in CustomCollisionLayer.Tiles)
            {
                if (tile != null && tile.TilesetTile != null)
                {
                    TmxList <TmxObjectGroup> objgl = tile.TilesetTile.ObjectGroups;

                    if (objgl != null && objgl.Count > 0)
                    {
                        TmxObjectGroup objg = objgl[0];
                        if (objg.Objects != null && objg.Objects.Count > 0)
                        {
                            TmxObject     obj  = objg.Objects[0];
                            TmxObjectType type = obj.ObjectType;

                            if (type == TmxObjectType.Ellipse)
                            {
                                //Draw Ellipse as collision
                                Core.Scene.CreateEntity(obj.Name, new Vector2(tile.Position.X * tile.Tileset.TileWidth + obj.Width / 2, tile.Position.Y * tile.Tileset.TileHeight + obj.Height / 2))
                                .AddComponent(new FSCollisionEllipse(obj.Width / 2, obj.Height / 2))
                                .AddComponent(new CircleCollider((obj.Width + obj.Height) / 4));     // have to get an average of sides, hence / 4
                            }
                            else if (type == TmxObjectType.Polygon)
                            {
                                Vector2[] points = obj.Points;

                                Core.Scene.CreateEntity(obj.Name, new Vector2(tile.Tileset.TileWidth * tile.Position.X + obj.X, tile.Tileset.TileHeight * tile.Position.Y + obj.Y))
                                .AddComponent(new FSCollisionPolygon(points))
                                .AddComponent(new PolygonCollider(points));
                            }
                            //basic is rectangle
                            else if (type == TmxObjectType.Basic)
                            {
                                Core.Scene.CreateEntity(obj.Name, new Vector2(tile.Position.X * tile.Tileset.TileWidth + obj.Width / 2, tile.Position.Y * tile.Tileset.TileHeight + obj.Height / 2))
                                .AddComponent(new FSCollisionBox(obj.Width, obj.Height))
                                .AddComponent(new BoxCollider(obj.Width, obj.Height));
                            }
                        }
                    }
                }
            }
            tmr.SetLayersToRender(new string[] { });
        }
Exemple #22
0
        /// <summary>
        /// Initialize Layer
        /// </summary>
        private void LoadLayer()
        {
            this.tiles = new List <LayerTile>();

            if (this.Owner.Parent == null)
            {
                return;
            }

            this.tiledMap = this.Owner.Parent.FindComponent <TiledMap>();

            if (this.tiledMap != null && this.tiledMap.TmxMap != null)
            {
                this.tmxLayer = this.tiledMap.TmxMap.Layers.FirstOrDefault(l => l.Name == this.tmxLayerName);

                if (this.tmxLayer != null)
                {
                    this.tileTable = new LayerTile[this.tiledMap.Width, this.tiledMap.Height];

                    for (int i = 0; i < this.tmxLayer.Tiles.Count; i++)
                    {
                        var tmxTile = this.tmxLayer.Tiles[i];

                        Tileset selectedTileset = null;

                        if (tmxTile.Gid > 0)
                        {
                            foreach (var tileset in this.tiledMap.Tilesets)
                            {
                                if (tmxTile.Gid <= tileset.LastGid)
                                {
                                    selectedTileset = tileset;
                                    break;
                                }
                            }
                        }

                        LayerTile tile = new LayerTile(tmxTile, selectedTileset);
                        this.tiles.Add(tile);

                        Vector2 tileLocalPosition;
                        this.tiledMap.GetTilePosition(tile.X, tile.Y, selectedTileset, out tileLocalPosition);
                        tile.LocalPosition = tileLocalPosition;

                        int x = i % this.tiledMap.Width;
                        int y = i / this.tiledMap.Width;
                        this.tileTable[x, y] = tile;
                    }

                    this.isLayerLoaded = true;
                    this.NeedRefresh   = true;
                }
            }
        }
Exemple #23
0
        /// <summary>
        /// Create the tile layer as a child entity
        /// </summary>
        /// <param name="tmxLayer">The tmx layer.</param>
        /// <param name="layerIndex">The layer index</param>
        private void CreateChildTileLayer(TmxLayer tmxLayer, int layerIndex)
        {
            var tag          = "TileLayer_" + layerIndex;
            var tmxLayerName = tmxLayer.Name;

            Entity        layerEntity  = null;
            TiledMapLayer tileMapLayer = null;

            layerEntity = this.Owner.FindChildrenByTag(tag).FirstOrDefault();
            var tileLayerOffset = new Vector2((float)tmxLayer.OffsetX, (float)tmxLayer.OffsetY);

            if (layerEntity != null)
            {
                var tileMapTransform = layerEntity.FindComponent <Transform2D>();
                tileMapLayer = layerEntity.FindComponent <TiledMapLayer>();

                if (tileMapTransform != null &&
                    tileMapLayer != null)
                {
                    tileMapTransform.LocalPosition = tileLayerOffset;
                    tileMapLayer.TmxLayerName      = tmxLayerName;
                    layerEntity.Name = tmxLayerName;
                }
                else
                {
                    this.Owner.RemoveChild(layerEntity.Name);
                    layerEntity = null;
                }
            }

            if (layerEntity == null)
            {
                tileMapLayer = new TiledMapLayer()
                {
                    TmxLayerName = tmxLayerName
                };

                layerEntity = new Entity(tmxLayerName)
                {
                    Tag = tag
                }
                .AddComponent(tileMapLayer)
                .AddComponent(new Transform2D()
                {
                    LocalPosition = tileLayerOffset,
                    Origin        = this.transform.Origin,
                    Opacity       = (float)tmxLayer.Opacity
                })
                .AddComponent(new TiledMapLayerRenderer());
                this.Owner.AddChild(layerEntity);
            }

            this.tileLayers.Add(tmxLayerName, tileMapLayer);
        }
Exemple #24
0
 public void Init(int width, int height, TmxLayer layer, Material material)
 {
     meshRenderer.sharedMaterial = material;
     tileSize = unitSize / tilesPerSide;
     CalculateTiles();
     tileType = (TileType)GameManager.IntParseFast(layer.Properties["TileType"]);
     InitMesh(width, height);
     DrawMesh(width, height, layer);
     UpdateMesh();
     gameObject.isStatic = true;
 }
Exemple #25
0
        private static void DrawCollisionLayer(SKCanvas canvas, TmxLayer tmxLayer, SKColor polyColor, SKColor lineColor)
        {
            LayerClipper.TransformPointFunc xfFunc   = (x, y) => new ClipperLib.IntPoint(x, y);
            LayerClipper.ProgressFunc       progFunc = (prog) => { }; // do nothing

            ClipperLib.PolyTree solution = LayerClipper.ExecuteClipper(tmxLayer.TmxMap, tmxLayer, xfFunc, progFunc);

            using (SKPaint paint = new SKPaint())
            {
                // Draw all closed polygons
                // First, add them to the path
                // (But are we using convex polygons are complex polygons?
                using (SKPath path = new SKPath())
                {
                    var polygons = tmxLayer.IsExportingConvexPolygons() ? LayerClipper.SolutionPolygons_Simple(solution) : LayerClipper.SolutionPolygons_Complex(solution);
                    foreach (var pointfArray in polygons)
                    {
                        var pts = pointfArray.ToSkPointArray();
                        path.AddPoly(pts, true);
                    }

                    // Then, fill and draw the path full of polygons
                    if (path.PointCount > 0)
                    {
                        paint.Style = SKPaintStyle.Fill;
                        paint.Color = polyColor;
                        canvas.DrawPath(path, paint);

                        paint.Style       = SKPaintStyle.Stroke;
                        paint.StrokeWidth = StrokeWidthThick;
                        paint.Color       = lineColor;
                        canvas.DrawPath(path, paint);
                    }
                }

                // Draw all lines (open polygons)
                using (SKPath path = new SKPath())
                {
                    foreach (var points in ClipperLib.Clipper.OpenPathsFromPolyTree(solution))
                    {
                        var pts = points.Select(pt => new SKPoint(pt.X, pt.Y)).ToArray();
                        path.AddPoly(pts, false);
                    }
                    if (path.PointCount > 0)
                    {
                        paint.Style       = SKPaintStyle.Stroke;
                        paint.StrokeWidth = StrokeWidthThick;
                        paint.Color       = lineColor;
                        canvas.DrawPath(path, paint);
                    }
                }
            }
        }
Exemple #26
0
        private int GetCurrentTilesGid(Vector2 position, TmxLayer layer)
        {
            var row    = (int)Math.Floor(position.Y / map.Tilesets[0].TileHeight) + 1;
            var column = (int)Math.Floor(position.X / map.Tilesets[0].TileWidth);

            if (column >= map.Width || column < 0)
            {
                throw new ArgumentOutOfRangeException();
            }
            var i = (row - 1) * map.Width + column;

            return(layer.Tiles[i].Gid);
        }
        static void LoadTilemap(string filename, out TmxLayer floor_tiles, out TmxLayer background_tiles, out TmxLayer behind_tiles, out TmxLayer play_tiles, out TmxLayer roof_tiles, out TmxMap map, out Tileset tileset)
        {
            map = new TmxMap("res/maps/game map.tmx");

            floor_tiles      = map.Layers[0];
            background_tiles = map.Layers[1];
            behind_tiles     = map.Layers[2];
            play_tiles       = map.Layers[3];
            roof_tiles       = map.Layers[4];

            using (var stream = File.OpenRead("res/tilesets/tileseta.tsx"))
                tileset = Tileset.FromStream(stream);
            //Console.WriteLine($"{tileset.Name}");
        }
Exemple #28
0
        public Vector2 Move(Vector2 velocity, Entity entity, string collisionLayer = "collision")
        {
            TmxLayer layer = Data.Layers[collisionLayer];

            Vector2   newPosition = entity.position + velocity;
            Rectangle sweptBounds = new Rectangle((int)(newPosition.X - entity.Width / 2),
                                                  (int)(newPosition.Y - entity.Height / 2),
                                                  entity.Width, entity.Height);

            // create swept rectangle
            sweptBounds = Rectangle.Union(sweptBounds, entity.BoundingBox);

            int minTileX = sweptBounds.Left / Data.TileWidth;
            int minTileY = sweptBounds.Top / Data.TileHeight;

            int maxTileX = sweptBounds.Right / Data.TileWidth + 1;
            int maxTileY = sweptBounds.Bottom / Data.TileHeight + 1;

            for (int y = minTileY; y < maxTileY; y++)
            {
                for (int x = minTileX; x < maxTileX; x++)
                {
                    if (x < 0 || x >= Data.Width ||
                        y < 0 || y >= Data.Height)
                    {
                        continue;
                    }

                    TmxLayerTile tile = layer.Tiles[y * Data.Width + x];
                    if (GetTilesetForTile(tile) == null)
                    {
                        continue;
                    }

                    Rectangle tileBounds   = GetTileBounds(x, y);
                    Rectangle intersection = Rectangle.Intersect(tileBounds, sweptBounds);

                    if (intersection.Width < intersection.Height)
                    {
                        velocity.X += -Math.Sign(velocity.X) * intersection.Width;
                    }
                    else
                    {
                        velocity.Y += -Math.Sign(velocity.Y) * intersection.Height;
                    }
                }
            }

            return(velocity);
        }
Exemple #29
0
        protected RenderTarget2D BuildLayerTexture(TmxLayer layer)
        {
            RenderTarget2D texture = new RenderTarget2D(_graphics, Map.Width * Map.TileWidth, Map.Height * Map.TileHeight);

            _graphics.SetRenderTarget(texture);

            using (var spriteBatch = new SpriteBatch(_graphics))
            {
                _graphics.Clear(Color.Transparent);

                int x = 0;
                int y = 0;

                spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

                foreach (var tile in layer.Tiles)
                {
                    TMXTilesheet tilesheet = null;

                    foreach (var ts in this._tilesheets)
                    {
                        if (tile.Gid >= ts.FirstGID && (ts.LastGID == -1 || tile.Gid <= ts.LastGID))
                        {
                            tilesheet = ts;
                        }
                    }

                    if (tile.Gid != 0)
                    {
                        tilesheet.Sheet.SetFrame(tile.Gid);
                        tilesheet.Sheet.Draw(spriteBatch, new Vector2(x, y));
                    }

                    x += Map.TileWidth;

                    if (x >= (Map.Width * Map.TileWidth))
                    {
                        x  = 0;
                        y += Map.TileHeight;
                    }
                }

                spriteBatch.End();

                _graphics.SetRenderTarget(null);

                return(texture);
            }
        } // BuildLayerTexture
Exemple #30
0
        private static void DrawLayerColliders(Graphics g, TmxLayer tmxLayer, Color polyColor, Color lineColor, float scale)
        {
            LayerClipper.TransformPointFunc xfFunc   = (x, y) => new ClipperLib.IntPoint(x, y);
            LayerClipper.ProgressFunc       progFunc = (prog) => { }; // do nothing

            ClipperLib.PolyTree solution = LayerClipper.ExecuteClipper(tmxLayer.TmxMap, tmxLayer, xfFunc, progFunc);

            float inverseScale = 1.0f / scale;

            if (inverseScale > 1)
            {
                inverseScale = 1;
            }

            using (GraphicsPath path = new GraphicsPath())
                using (Pen pen = new Pen(lineColor, 2.0f * inverseScale))
                    using (Brush brush = TmxHelper.CreateLayerColliderBrush(polyColor))
                    {
                        // Draw all closed polygons
                        // First, add them to the path
                        // (But are we using convex polygons are complex polygons?
                        var polygons = tmxLayer.IsExportingConvexPolygons() ? LayerClipper.SolutionPolygons_Simple(solution) : LayerClipper.SolutionPolygons_Complex(solution);
                        foreach (var pointfArray in polygons)
                        {
                            path.AddPolygon(pointfArray);
                        }

                        // Then, fill and draw the path full of polygons
                        if (path.PointCount > 0)
                        {
                            g.FillPath(brush, path);
                            g.DrawPath(pen, path);
                        }

                        // Draw all lines (open polygons)
                        path.Reset();
                        foreach (var points in ClipperLib.Clipper.OpenPathsFromPolyTree(solution))
                        {
                            var pointfs = points.Select(pt => new PointF(pt.X, pt.Y));
                            path.StartFigure();
                            path.AddLines(pointfs.ToArray());
                        }
                        if (path.PointCount > 0)
                        {
                            g.DrawPath(pen, path);
                        }
                    }
        }
        private static void DrawLayerColliders(Graphics g, TmxLayer tmxLayer, Color polyColor, Color lineColor, float scale)
        {
            LayerClipper.TransformPointFunc xfFunc = (x, y) => new ClipperLib.IntPoint(x, y);
            LayerClipper.ProgressFunc progFunc = (prog) => { }; // do nothing

            ClipperLib.PolyTree solution = LayerClipper.ExecuteClipper(tmxLayer.TmxMap, tmxLayer, xfFunc, progFunc);

            float inverseScale = 1.0f / scale;
            if (inverseScale > 1)
                inverseScale = 1;

            using (GraphicsPath path = new GraphicsPath())
            using (Pen pen = new Pen(lineColor, 2.0f * inverseScale))
            using (Brush brush = TmxHelper.CreateLayerColliderBrush(polyColor))
            {
                // Draw all closed polygons
                // First, add them to the path
                // (But are we using convex polygons are complex polygons?
                var polygons = tmxLayer.IsExportingConvexPolygons() ? LayerClipper.SolutionPolygons_Simple(solution) : LayerClipper.SolutionPolygons_Complex(solution);
                foreach (var pointfArray in polygons)
                {
                    path.AddPolygon(pointfArray);
                }

                // Then, fill and draw the path full of polygons
                if (path.PointCount > 0)
                {
                    g.FillPath(brush, path);
                    g.DrawPath(pen, path);
                }

                // Draw all lines (open polygons)
                path.Reset();
                foreach (var points in ClipperLib.Clipper.OpenPathsFromPolyTree(solution))
                {
                    var pointfs = points.Select(pt => new PointF(pt.X, pt.Y));
                    path.StartFigure();
                    path.AddLines(pointfs.ToArray());
                }
                if (path.PointCount > 0)
                {
                    g.DrawPath(pen, path);
                }
            }
        }
 private static int GetMaxTilesHigh(TmxLayer layer)
 {
     return Math.Min(layer.Height, MaxPreviewTilesHigh);
 }
 private static int GetMaxTilesWide(TmxLayer layer)
 {
     return Math.Min(layer.Width, MaxPreviewTilesWide);
 }