Diese Seite ist noch nicht auf Deutsch übersetzt und wird daher auf Englisch angezeigt.
2D-Kerntilemap
game/tilemap draws orthogonal, isometric, staggered, and hexagonal tiled worlds with camera frustum culling, loads Tiled .tmx/.tmj maps (with embedded or external .tsx/.tsj tilesets and animated tiles) and YAML tilesets (*.tileset.yaml), queries tile collision flags and rays, and drives a 2D camera with smoothing, clamping, and screen shake.
import "github.com/nsgo-dev/game/pkg/tilemap"
Camera
Camera maps world coordinates onto a view of Width by Height points centered on (X, Y), scaled by Zoom (<= 0 behaves as 1), and rotated clockwise by Rotation radians:
bounds := m.WorldBounds()
cam := &tilemap.Camera{
Width: 320,
Height: 180,
Zoom: 1,
Bounds: &bounds,
}
Following, clamping, and shaking
Advance camera follow and shake inside game.Loop.Update:
// Exponentially smooth toward player (smoothing <= 0 snaps immediately)
cam.Follow(playerPos, 8, dt)
// Advance active screen shake
cam.Update(dt)
// Trigger a deterministic shake on impact
if tookDamage {
cam.Shake(6, 250*time.Millisecond)
}
Clamp()keepsVisibleBounds()insideBoundswhen set; if the world is smaller than the view on an axis, the camera centers onBoundsalong that axis.FollowcallsClampautomatically.Shake(intensity, duration)applies a deterministic displacement seeded byShakeSeed(decays linearly to zero overduration; non-positive arguments cancel any active shake). Inspect the current offset withShakeOffset().- Convert coordinates with
WorldToView(p)andViewToWorld(p), and inspect the axis-aligned visible world box withVisibleBounds().
Applying the camera during draw
Wrap world-space drawing in d.Save() / d.Restore() and call cam.Apply(d) before drawing tilemaps and world sprites:
d.Save()
cam.Apply(d)
m.Draw(d, cam)
actorsBatch.Draw(d)
d.Restore()
Passing cam to m.Draw(d, cam) or m.DrawLayer(d, layer, cam) visits only the columns and rows intersecting cam.VisibleBounds().
Loading Tiled maps
LoadTiled parses Tiled XML (.tmx) and JSON (.tmj) maps into the same *Tilemap, auto-detecting the format from the input bytes. It supports embedded and external .tsx/.tsj grid and image-collection tilesets (including per-tile images, optional sub-rectangles, tileoffset, objectalignment, and cross-format references such as a .tmx map using a .tsj tileset or a .tmj map using a .tsx tileset), CSV, legacy XML <tile>, and base64 tile data (uncompressed, zlib, and gzip) on both finite layers and infinite-map chunks, image layers, nested group layers, layer tintcolor (multiplied across nested groups), Tiled JSON Wang sets (wangsets in .tmj/.tsj) and per-tile probabilities, GID flip bits (FlipHorizontal, FlipVertical, FlipDiagonal), object layers (including drawn tile objects, text objects as data, and external .tx/.tj object templates), typed custom properties, animated tiles, and the collision shapes drawn on tiles in Tiled's collision editor. zstd compression is refused with a *loaderr.Error pointing at the file, line, and fix hint.
//go:embed resources/maps/*.tmx resources/maps/*.tsx resources/maps/*.tx
var mapFS embed.FS
raw, err := mapFS.ReadFile("resources/maps/level1.tmx")
if err != nil {
return err
}
m, err := tilemap.LoadTiled(raw, tilemap.TilesetLoader{
LoadTileset: func(source string) ([]byte, error) {
return mapFS.ReadFile("resources/maps/" + source)
},
LoadTemplate: func(source string) ([]byte, error) {
return mapFS.ReadFile("resources/maps/" + source)
},
LoadImage: func(imagePath string) (core.ImageSource, error) {
return core.Src("asset:maps/" + path.Base(imagePath)), nil
},
})
if err != nil {
return err
}
Existing callers that set TilesetLoader.LoadJSON continue to work for both .tsj and .tsx tilesets when LoadTileset is nil.
Image-collection tilesets, tile objects, templates, and text objects
- Image-collection tilesets: tilesets with per-tile
<image>entries load intoTileset.TileImages(map[uint32]TileImage, keyed by 0-based local tile ID), preserving each tile's own width, height, and optional sub-rectangle (X,Y,Width,Height) with paths resolved relative to external tilesets.Tileset.TileOffsetX/TileOffsetYshift rendered tiles on both tile layers and tile objects, andTileset.ObjectAlignment(ObjectAlignmentUnspecified,TopLeft,Top,TopRight,Left,Center,Right,BottomLeft,Bottom,BottomRight) controls tile-object anchoring (BottomLeftby default on orthogonal/staggered/hex maps,Bottomon isometric maps). - Drawing tile objects and layer tints:
m.Draw(d, cam)interleavesObjectLayers with tile and image layers in Tiled's layer order, drawing every visibleObjectTileviam.DrawObjectLayer(d, layer, cam)with layer visibility, opacity,TintColor, offset, parallax, object size, clockwiseRotation, GID flip bits,tileoffset,objectalignment, and camera frustum culling.TileLayer.TintColor,ImageLayer.TintColor, andObjectLayer.TintColormultiply each layer's pixels when set (setTinted: truealongsideTintColor: 0to distinguish transparent#00000000from untinted). - Object templates (
.tx/.tj): when an object references a template,LoadTiledloads it throughTilesetLoader.LoadTemplate(caching each template once per map), merges the template's fields, shape, and custom properties with the instance's overrides, and remaps any template tileset GIDs into the map's tilesets (reusing an already-loaded external tileset when the canonical path matches). - Text objects: Tiled
<text>/"text"objects load withShape == ObjectTextandObject.Text(*TextObject:Text,FontFamily,PixelSize,Wrap,Color,Bold,Italic,Underline,Strikeout,Kerning,HAlign,VAlign) as structured data for game-side rendering.
Building tilemaps in code
For procedural maps or tests, build a tileset with NewGridTileset or NewAtlasTileset and populate a Tilemap directly:
ts := tilemap.NewGridTileset(1, core.Src("asset:tiles.png"), 16, 16, 8, 64)
m := tilemap.New(40, 20, 16, 16, ts)
ground := tilemap.NewTileLayer("ground", 40, 20, nil)
m.Layers = append(m.Layers, ground)
m.SetTile(0, 5, 19, 1) // layer 0, col 5, row 19 -> GID 1
Look up layers and objects by name with m.Layer("ground") and m.ObjectLayer("spawns"). Read typed custom properties on maps, layers, tilesets, tiles (m.TileProperties(gid)), and objects via Properties helpers (Bool, Int, Float, String, Color, File, ObjectID, Has). For polygon/polyline objects, obj.WorldPoints() returns vertices translated by (obj.X, obj.Y).
Objects drawn as collision geometry become physics shapes with obj.PhysicsShape(), and layer.PhysicsBodies() returns a static physics.Body per object, moved by the layer's offset, with the object's ID, its type as Tag and the object itself as UserData. Hidden objects count, since collision layers are often hidden:
| Tiled object | Shape |
|---|---|
| Rectangle | Box, or a Polygon when rotated |
| Ellipse | Circle when round, otherwise an 8-vertex Polygon inscribed in it |
| Polygon | Polygon when convex with at most 8 vertices, otherwise a closed Chain along its outline |
| Polyline | Segment for two points, otherwise an open Chain |
| Point, tile | none |
for _, ground := range m.ObjectLayer("collision").PhysicsBodies() {
rigid.AddBody(physics.NewStaticRigidBody(ground.Shape))
}
A missing layer returns no bodies. Like the objects themselves, the bodies are in the map's local coordinates; for a map placed by Origin, move each shape with ground.Shape.Translated(float32(m.Origin.X), float32(m.Origin.Y)).
Tiled Wang sets and multi-terrain autotiling
LoadTiled parses Tiled wangsets (corner, edge, and mixed) from embedded .tmj and external .tsj tilesets into Tileset.WangSets, together with each terrain color (WangColor: Name, Color, Tile, Probability, Properties), each tile's 8-slot clockwise WangID ([Top, TopRight, Right, BottomRight, Bottom, BottomLeft, Left, TopLeft]), and per-tile selection weights (Tileset.TileProbabilities / Tileset.TileProbability).
Use m.SetTerrain and m.SetTerrainRect to paint multi-terrain transitions (such as grass, dirt, water, and cliffs) with Tiled's terrain brush semantics across orthogonal and isometric maps as well as dense and sparse chunked layers:
ws := m.WangSet("Terrains") // or ts.WangSet("Terrains") / ts.WangSetAt(0)
grass, _ := ws.ColorIndex("Grass")
dirt, _ := ws.ColorIndex("Dirt")
water, _ := ws.ColorIndex("Water")
rng := random.New(42)
m.SetTerrainRect(0, 0, 0, m.Width, m.Height, ws, grass, rng)
m.SetTerrain(0, 4, 3, ws, dirt, rng)
m.SetTerrainRect(0, 6, 2, 3, 3, ws, water, rng)
- Corner, edge, and mixed sets:
WangCornermatches the four tile corners,WangEdgematches the four tile edges, andWangMixedmatches all eight slots. Existing neighbors whose shared corners or edges change are updated automatically, including multi-hop transitions (for example creating a dirt shoreline ring when painting water onto grass in a tileset without direct grass-to-water tiles). - Deterministic probability selection: when multiple tiles tie for the best match,
SetTerrainandSetTerrainRectchoose weighted by tile probability from*random.Stream(or anyTerrainRand, so the same seed always picks the same variants). Passrng == nilfor deterministic lowest-TileIDselection. - Code-defined blobs:
AutotileSet,ApplyAutotile, andSetAutotileremain available for code-defined 4-bit (16-tile) and 8-bit corner-gated (47-tile) single-terrain blobs.
YAML tilesets
A YAML tileset (*.tileset.yaml, TilesetDoc) is the text counterpart of Godot's TileSet resource: it says once what each tile is, and the maps that use it only place tiles. Scene files place its tiles in layered grids or single-grid inline tilemaps (Editor & Scene Format). It cuts its tiles from a grid image (image, columns, tileCount, optional spacing and margin) or takes them from frames of a sprite atlas (atlas, frames in local ID order). A tile's local ID is its index in the grid, row by row from the top left, or in frames, from 0.
# yaml-language-server: $schema=https://game.nsgo.dev/schemas/tileset.v1.json
version: 1
name: cave
tileWidth: 16
tileHeight: 16
image: tiles/cave.png
columns: 4
tileCount: 8
terrains:
- name: rock
mode: cardinal
tiles:
- id: 0
solid: true
terrain: rock
- id: 1
solid: true
properties:
friction: 0.5
terrain: rock
neighbors: [east]
- id: 2
shapes:
- kind: polygon
points: [[0, 16], [16, 0], [16, 16]]
- id: 4
animation:
- tile: 4
duration: 200ms
- tile: 5
duration: 200ms
tiles lists the tiles that carry more than their picture, in ascending ID order:
| Field | Meaning |
|---|---|
name |
Optional human-readable tile name shown in inspectors and tools |
solid, oneWay, flags |
TileSolid, TileOneWay and any further TileFlags bits the game defines, set on the tile with SetFlags; *Tilemap implements physics.TileGrid and physics.TileGridOrigin, so a tile marked solid collides through physics.MoveAndSlide directly |
weight |
Optional non-negative variant weight loaded into Tileset.TileProbabilities |
properties |
Custom properties, each a bool, an integer, a number or a string, as TileProperties returns them; the tileset has its own properties too |
shapes |
Collision shapes in the tile's coordinates: rect and ellipse by x, y, width and height, polygon (3 points or more) and polyline (2 or more) by points, each with optional name, type and properties; they load into Tileset.Shapes as Tiled's collision editor's do, for tileshape |
animation |
Frames of tile and positive duration (such as 150ms) that Update cycles through |
terrain, neighbors |
The terrain set from terrains the tile belongs to, and the directions (north, east, south, west, and for a blob terrain also northeast, southeast, southwest, northwest) in which a cell of the same terrain lies next to it; a corner is listed only with both edges beside it (northeast with north and east), since it matches only when they do |
A terrain's mode is cardinal, which matches the four edge neighbours (16 tiles, Autotile4), or blob, which also matches a corner when both edges beside it match (47 tiles, Autotile8). Optional default names the local tile ID used when a cell's neighbour mask has no mapped tile; when omitted, the tile of the terrain that lists no neighbours (mask 0) is the default. No two tiles of a terrain may list the same neighbours.
ParseTileset refuses unknown keys and every rule above with a *loaderr.Error at the line at fault, and EncodeTileset writes the canonical form, so loading and saving a tileset changes no byte; LoadTilesetFS reads one from an fs.FS. m.AddTilesetDoc(doc, firstGID, assets) builds it into a Tileset of m whose GIDs start at firstGID, resolving its image through TilesetAssets.Image (a core.ImageSource{URI: path} when nil) or its atlas through TilesetAssets.Atlas, and sets its tiles' flags on the map:
doc, err := tilemap.LoadTilesetFS(os.DirFS(projectDir), "tilesets/cave.tileset.yaml")
if err != nil {
return err
}
m := tilemap.New(40, 23, 16, 16)
if _, err := m.AddTilesetDoc(doc, 1, tilemap.TilesetAssets{}); err != nil {
return err
}
// Autotile a layer with the rock terrain, or paint a single terrain cell with neighbor updates.
m.ApplyTerrain(0, "rock")
m.SetTerrainTile(0, 4, 3, "rock", true)
Each terrain becomes a Terrain in Tileset.Terrains (also buildable directly from a TilesetDoc via doc.Terrain(name, firstGID)), whose Autotile maps neighbour masks to GIDs for ApplyAutotile and SetAutotile and whose Contains tells its tiles apart. ApplyTerrain and SetTerrainTile look up the named terrain on the map and run ApplyAutotile / SetAutotile directly. ValidTerrainMask, ToggleTerrainMask, TerrainMaskNeighbors and TerrainNeighborsMask convert and edit neighbour bitmasks while preserving 4-bit and 8-bit corner-gating rules. TilesetFrame(doc, atlas, id) gives where a tile lies in its image, as an editor's palette shows it.
Animated tiles
Tiled tile animations load into Tileset.Animations, keyed by 0-based local tile ID. Call m.Update(dt) on every game.Loop.Update step to advance all animated tiles cleanly across cycles:
m.Update(dt)
You can also attach a TileAnimation manually to a tileset by setting ts.Animations[localID] = &tilemap.TileAnimation{Frames: ...}.
Y-sorting tiles with sprites
Enable per-layer Y-sorting on any TileLayer (layer.YSort = true or m.SetLayerYSort(index, true), or via a boolean Tiled layer custom property named y_sort, ysort, ySort, or y-sort) so tall tiles such as trees, walls, and pillars interleave with scene sprites and custom drawables by depth:
m.Layer("trees").YSort = true
// Optional: shift a tree tile's sort line upward from its bottom edge to its trunk base.
// Equivalent to setting a float/int tile custom property "sort_origin_y" = -8 in Tiled.
m.SetTileSortOriginY(treeGID, -8)
world := sc.AddLayer(scene.NewLayer("world", scene.SpaceWorld, 0))
world.DepthSort = scene.SortY
world.AddTilemap(m)
world.AddBatch(actorsBatch)
- Default sort line: each visible tile sorts by its world-space bottom edge (
offY + tileOriginY + TileHeight), which works across orthogonal, isometric, staggered, and hexagonal orientations and matches bottom-pivoted character sprites (OriginY = height). - Per-tile sort origin: attach the custom tile property
sort_origin_y(tilemap.PropSortOriginY, aliasesy_sort_originandysort_origin) in Tiled or callm.SetTileSortOriginY(gid, offsetY)to offset a tile's sort line vertically (negative moves it up into a tree trunk or isometric diamond center; positive moves it down). Inspect it withm.TileSortOriginY(gid). - Layer ordering & culling: inside a
scene.SortYlayer, non-Y-sorted layers before the first Y-sorted layer draw behind sprites (keeping anyCacheStaticLayerfast path), Y-sorted layers interleave individual visible tiles with sprites and drawables, and trailing non-Y-sorted layers (such as roofs or canopies) draw above them. Camera frustum culling (including tall tiles and atlas frames), animated tiles, flip flags, and layer opacity are all respected. - Custom draw loops: use
m.AppendYSortTiles(dst[:0], layer, cam),tilemap.SortYSortTiles(tiles), andtilemap.YSortDrawer(orYSortTile.Draw(d)) to collect, sort, and draw Y-sorted tiles with reusable scratch buffers and zero allocations intilemaponce warmed up.
Tile flags, overlap queries, and raycasts
Associate collision or gameplay TileFlags (TileSolid, TileOneWay, or custom bitflags) with global tile IDs or individual map cells:
m.SetFlags(1, tilemap.TileSolid)
m.SetFlags(2, tilemap.TileOneWay)
// Override a single cell (e.g. a breakable wall cleared at runtime)
m.SetCellFlags(10, 6, 0)
// Restore tile-ID flags later
m.ClearCellFlags(10, 6)
Query the grid without allocating unnecessary geometry:
FlagsAt(col, row)returns the combinedTileFlagsacross all layers (or the cell override if set).TilesInRect(r, mask)returns every cell overlappingrmatchingmask(or any non-empty cell whenmask == 0) in row-major order as[]TileHit. Cells are half-open[col*TileWidth, (col+1)*TileWidth) × [row*TileHeight, (row+1)*TileHeight).Raycast(from, to, mask)traces the segmentfrom -> toand returns the first matchingRaycastHit(Col,Row,TileID,Flags,Point,Normal, and fractionTin[0, 1]).
if hit, ok := m.Raycast(enemyEye, playerPos, tilemap.TileSolid); ok {
// Line of sight blocked at hit.Point with surface normal hit.Normal
_ = hit
}
Isometric, staggered, and hexagonal maps
Set Orientation (OrientationOrthogonal, OrientationIsometric, OrientationStaggered, or OrientationHexagonal) together with StaggerAxis (StaggerY / StaggerX), StaggerIndex (StaggerOdd / StaggerEven), and HexSideLength to project and draw diamond isometric, staggered isometric, and pointy-top or flat-top hexagonal maps:
TileOrigin(col, row)andTileToWorld(col, row)return each cell's bounding-box origin and center in world coordinates, andWorldToTile(p)round-trips any interior world point back to(col, row).HexNeighbors(col, row)andHexDistance(c1, r1, c2, r2)compute exact 6-neighbor adjacency and cube distance for both stagger axes and indices.- For pathfinding and tactics movement ranges on these projections, pass
ai.TopologyFromTilemap(m)togame/ai(AStar.Topology,AStar.MovementRange,ReachableCells), or wrap a hex map directly withai.NewHexGrid(m)forai.GraphSearch(including reconstructed paths to every cell in range). - For line-of-sight visibility and tile-aligned fog rendering over isometric, staggered, and hex maps, build a
game/fogwithfog.NewFromTilemap(m, tilemap.TileSolid).
Sparse chunked layers and streaming
For unbounded 2D sandbox or open-world maps (negative and arbitrarily large coordinates), use a sparse chunked TileLayer created with NewChunkedTileLayer(name, chunkSize) inside NewInfinite(tileWidth, tileHeight, tilesets...). Chunk sizes are fixed powers of two in [MinChunkSize, MaxChunkSize] (default DefaultChunkSize = 16), allowing branch-free shift/mask coordinate lookup (TileToChunk) across negative and positive coordinates:
m := tilemap.NewInfinite(16, 16, ts)
m.Layers = []tilemap.TileLayer{
tilemap.NewChunkedTileLayer("world", tilemap.DefaultChunkSize),
}
m.SetFlags(1, tilemap.TileSolid)
// Arbitrary negative and positive coordinates work through the exact same APIs:
m.SetTile(0, -17, -16, 1)
gid := m.TileAt(0, -17, -16)
hits := m.TilesInRect(rect, tilemap.TileSolid)
rayHit, ok := m.Raycast(from, to, tilemap.TileSolid)
- Infinite Tiled maps:
LoadTiledloads infinite.tmjlayers ("infinite": trueor layers carrying"chunks") directly into sparse chunkedTileLayers, preserving negative chunk coordinates instead of flattening into a giant dense array. - Per-chunk static caches and dirty tracking: editing a tile with
SetTileorFillRectmarks only the affected chunkDirtyandModifiedwithout invalidating other chunks. Bake static chunks withm.CacheStaticChunk(layerIndex, coord, images)or rebake only dirty chunks withm.CacheDirtyChunks(layerIndex, images); inspect and invalidate individual chunks viaChunkCache,InvalidateChunkCache,ClearChunkCache,layer.DirtyChunks(), andlayer.ModifiedChunks(). - Deterministic plain-text chunk persistence:
Chunk.ToDoc()/ChunkFromDocandEncodeChunkYAML/DecodeChunkYAML(orEncodeChunkJSON/DecodeChunkJSON) encode chunks as versioned (ChunkFormatVersion = 1) run-length encoded YAML or JSON that preserves all 32-bit GIDs including flip flags and round-trips byte for byte. Built-in stores includeNewMemoryChunkStore()andNewDirChunkStore(dir, format)(writingchunk_<x>_<y>.yamlor.json). - Bounded streaming:
- Use
tilemap.NewChunkStream(tilemap.ChunkStreamConfig{...})for synchronous 2D streaming with aGenerator,LoadRadius/UnloadRadiushysteresis,MaxLoadsPerUpdate, and automatic save/restore of modified chunks through aChunkStore. - For multi-threaded background chunk loading on top of
world3d.ChunkStreamer, useworld3d.NewTilemapStreamer(world3d.TilemapStreamerConfig{...})(ingame/world3d), which streams*tilemap.Chunkvalues with background workers, cancellation, per-frame integration budgets, and modified-chunk YAML/JSON persistence.
- Use
store := tilemap.NewDirChunkStore(saveDir, tilemap.ChunkFormatYAML)
stream := tilemap.NewChunkStream(tilemap.ChunkStreamConfig{
Map: m,
LayerIndex: 0,
LoadRadius: 2,
UnloadRadius: 3,
Format: tilemap.ChunkFormatYAML,
Store: store,
Generator: func(coord tilemap.ChunkCoord, ch *tilemap.Chunk) error {
// Populate procedural terrain for coord...
return nil
},
})
defer stream.Close()
// Inside your update loop:
stream.Update(playerPos)
Multi-level worlds (LDtk and Tiled .world)
Place multiple tilemaps into one shared world coordinate space using Tilemap.Origin, LDtk world layouts, Tiled .world files, and region-based streaming with WorldStream:
- World origin (
Tilemap.Origin): everyTilemapcarriesOrigin core.Point(defaulting to(0, 0)with zero overhead).Draw,DrawLayer,DrawImageLayer,CacheStaticLayer,AppendYSortTiles,WorldBounds,TileOrigin,TileToWorld,WorldToTile,TilesInRect, andRaycastall honorOrigin, as dofog.NewFromTilemap(fog.Fog.Origin) andphysics.TileGridOrigin: both*Tilemapand*WorldStreamimplementphysics.TileGrid(TileSize,GridSize,TileFlagsAt) andphysics.TileGridOrigin(GridOrigin) directly viaTileFlags.PhysicsFlags(). - LDtk multi-level worlds and IntGrid flags:
LoadLDtkandLoadLDtkAllpopulate each level'sOriginfrom(worldX, worldY)(forFreeandGridVanialayouts) and itsNeighbourslist ([]LevelNeighbour, resolvingIdentifier,IID,UID, and directionn/s/e/w/ne/nw/se/sw/o/</>), and honor LDtk'sintGridValuesGroupswhen mapping IntGrid values toTileFlags. UseLoadLDtkWith,LoadLDtkAllWith, andLoadLDtkWorldWithwithLDtkOptions(orproject.File.LDtkOptionsfromphysics.ldtkIntGridingame.yaml) to map IntGrid identifiers, group names, or numeric values toTileFlags(including mapping decorative values to0).LoadLDtkWorld(data, worldIdentifier, resolveImage)returns a lazy*LevelWorldsupporting both single-world and multi-world.ldtkprojects (refusingLinearHorizontalandLinearVerticallayouts that assign no 2D world coordinates). - Tiled
.worldfiles:ParseTiledWorld(data)parses Tiled.worldJSON files — both explicitmapsentries (fileName,x,y, optionalwidth/height) and regexpatterns(regexp,multiplierX,multiplierY,offsetX,offsetY,mapWidth,mapHeight) — returning*loaderr.Errorwith line, field, and fix guidance on malformed JSON or invalid patterns.TiledWorld.Resolve(fileNames)expands patterns deterministically without duplicating explicit entries, andLoadTiledWorld(data, loader)builds a lazy*LevelWorldthat sets each loaded.tmj'sOriginto its.worldplacement. - Region-based level streaming (
WorldStream): keeps only the levels overlapping a camera or query rectangle (expanded byLoadMargin) loaded at their world origins and unloads levels outsideUnloadMargin, firingOnEnter/OnLeaveand returning[]WorldStreamEventin deterministic world order.WorldStreamalso provides seamless multi-levelDraw,UpdateAnimations,LevelAt,FlagsAtWorld,TilesInRect,Raycast, and directphysics.TileGrid+physics.TileGridOriginmethods (TileSize,GridSize,GridOrigin,TileFlagsAt,GridFlagsAt), so aphysics.Bodyorphysics.CharacterBodywalks across seams between adjacent levels without snagging.
world, err := tilemap.LoadLDtkWorld(ldtkBytes, "", func(relPath string) core.ImageSource {
return core.Src("asset:" + relPath)
})
if err != nil {
return err
}
stream := tilemap.NewWorldStream(tilemap.WorldStreamConfig{
World: world,
LoadMargin: 64,
UnloadMargin: 128,
OnEnter: func(lvl *tilemap.WorldLevel, m *tilemap.Tilemap) {
// Spawn entities or attach fog for lvl.ID...
},
OnLeave: func(lvl *tilemap.WorldLevel, m *tilemap.Tilemap) {
// Clean up entities belonging to lvl.ID...
},
})
defer stream.Close()
// Inside update:
stream.UpdateCamera(cam)
stream.UpdateAnimations(dt)
// Inside draw (after cam.Apply(d)):
stream.Draw(d, cam)
Collision shapes, round-tripping, and change tracking
The collision object group authored on each tile in Tiled's collision editor (.tmj, .tsj, .tmx, or .tsx) is preserved verbatim in Tileset.TileCollisions (map[uint32]*ObjectLayer, keyed by local tile ID, queried with m.TileCollisionGroup(gid)), and its rectangles, polygons, ellipses and polylines also load into Tileset.Shapes as TileShape values in the tile's own coordinates: an ellipse becomes EllipseShapeSegments points, and an object's rotation is applied. m.TileShapes(gid) returns a placed tile's shapes flipped and rotated by its GID's flip bits, the same transform DrawLayer draws the tile with, and m.TileBox(gid) the size of the tile they are measured in. EncodeTiled(m) writes a deterministic Tiled JSON (.tmj) document that preserves tilesets, layers, properties, animations, and per-tile collision object groups across round trips through LoadTiled.
*Tilemap satisfies physics.TileGrid and physics.TileGridOrigin directly (TileSize, GridSize, GridOrigin, TileFlagsAt), so physics.MoveAndSlide(body, m, dt), physics.World{Tiles: m}, and physics.RigidWorld{Tiles: m} work with no adapter.
m.TileRevision() and m.TileChangesSince(rev, fn) track collision flag edits as well as tile edits: SetCellFlags and ClearCellFlags log the cell they change, and SetFlags, which can change every cell showing the tile, asks callers for a full rebuild. Calls that change nothing log nothing. m.Flags(gid) returns the flags set on a tile ID, and m.CellFlags(col, row) the per-cell override, if any.
tileshape builds on both: its View is also a physics.TileGrid, derives slopes from tile shapes, merges solid cells and partial tile shapes into Boxes, StaticShapes, Outline, and light occluders, and rebuilds only around each change.