77 game-dev skills for AI coding agents — Godot, Unity, Unreal, Phaser, PixiJS, three.js, Bevy, pygame, LÖVE, Roblox. Portable SKILL.md Agent Skills (the format Anthropic launched as Claude Skills), with a router that loads the right skill for your engine and task. Runs in Claude Code, Cursor, Kiro, Codex, Copilot, Gemini CLI and more.
Python agent-skillsai-agentsantigravityawesome-listclaude-codeclinecodexcursorgame-devgame-developmentgamedevgemini-cligithub-copilotgodotkirooh-my-piskillsunityunrealwindsurf
feat(godot): add godot-2d-movement, godot-tilemap, godot-physics skills
AbhishekBarali166a8b96f68f9
diff --git a/skills/godot/godot-2d-movement/SKILL.md b/skills/godot/godot-2d-movement/SKILL.mdnew file mode 100644index 0000000..272591f--- /dev/null+++ b/skills/godot/godot-2d-movement/SKILL.md@@ -0,0 +1,155 @@+---+name: godot-2d-movement+description: >+ Implement 2D kinematic character movement in Godot 4.x with CharacterBody2D and+ move_and_slide(): platformer run/jump with gravity, top-down 8-direction motion,+ slope handling, and reading collisions. Use when coding a 2D player or enemy+ controller, a platformer or top-down character, or fixing move_and_slide()/+ is_on_floor() behavior in a .tscn with a CharacterBody2D.+license: Apache-2.0+compatibility: Godot 4.3++metadata:+ engine: godot+ category: godot+ difficulty: intermediate+---++# Godot 2D Movement (4.x)++Build responsive 2D character controllers with `CharacterBody2D` and the argument-less+`move_and_slide()`. Targets **Godot 4.3+**.++## When to use++- Use when scripting a 2D player/enemy that moves and collides: platformer (gravity ++ jump) or top-down (free 8-direction), slope walking, or wall/floor detection.+- Use when `move_and_slide()` "does nothing", the character sinks through floors, or+ `is_on_floor()` is always false.++**When *not* to use:** dynamic rigid bodies, areas, raycasts, collision layers →+`godot-physics`; tile-based levels → `godot-tilemap`; full platformer game template →+the `platformer` genre skill; engine-agnostic feel tuning → `physics-tuning`.++## Core workflow++1. **Use `CharacterBody2D`** with a `CollisionShape2D` child. It is script-driven: it+ does not fall or react to forces on its own.+2. **Set the `velocity` property, then call `move_and_slide()`** (no arguments in 4.x).+ The method reads `velocity`, moves the body, slides along surfaces, and updates+ `velocity` to reflect what actually happened.+3. **Do it in `_physics_process(delta)`** — `move_and_slide()` uses the physics step's+ delta internally, so do not multiply `velocity` by `delta` yourself.+4. **Platformer:** add gravity to `velocity.y` each tick, jump by setting `velocity.y`+ negative when `is_on_floor()`.+5. **Top-down:** build a direction from input and scale by speed; set+ `motion_mode = MOTION_MODE_FLOATING` so there is no "floor/wall" distinction.+6. **Read results** with `is_on_floor()`, `is_on_wall()`, `get_wall_normal()`, and+ `get_slide_collision(i)` after the call.++## Patterns++### 1. Platformer controller (gravity, jump, slopes)++```gdscript+extends CharacterBody2D++@export var speed := 200.0+@export var jump_velocity := -400.0+@export var gravity := 1200.0 # pixels/sec^2 (tune to taste)++func _physics_process(delta: float) -> void:+ # Apply gravity while airborne.+ if not is_on_floor():+ velocity.y += gravity * delta++ # Jump only when grounded (Input action set in Project Settings > Input Map).+ if Input.is_action_just_pressed("jump") and is_on_floor():+ velocity.y = jump_velocity++ # Horizontal input: -1, 0, or 1.+ var dir := Input.get_axis("move_left", "move_right")+ if dir != 0.0:+ velocity.x = dir * speed+ else:+ velocity.x = move_toward(velocity.x, 0.0, speed) # decelerate to a stop++ move_and_slide() # 4.x: no arguments; uses and updates `velocity`+```++### 2. Top-down 8-direction movement++```gdscript+extends CharacterBody2D++@export var speed := 220.0++func _ready() -> void:+ motion_mode = CharacterBody2D.MOTION_MODE_FLOATING # no floor/ceiling concept++func _physics_process(_delta: float) -> void:+ # get_vector returns a normalized-ish Vector2 from four input actions.+ var input := Input.get_vector("move_left", "move_right", "move_up", "move_down")+ velocity = input * speed+ move_and_slide()+```++### 3. Reading slide collisions after moving++```gdscript+func _physics_process(delta: float) -> void:+ # ... set velocity ...+ move_and_slide()+ for i in get_slide_collision_count():+ var c := get_slide_collision(i)+ var other := c.get_collider()+ if other and other.is_in_group("enemies"):+ take_damage(1) # touched an enemy while moving+```++### 4. Coyote time (forgiving jump just after leaving a ledge)++```gdscript+@export var coyote_time := 0.1+var _coyote := 0.0++func _physics_process(delta: float) -> void:+ if not is_on_floor():+ velocity.y += gravity * delta+ _coyote -= delta+ else:+ _coyote = coyote_time++ if Input.is_action_just_pressed("jump") and _coyote > 0.0:+ velocity.y = jump_velocity+ _coyote = 0.0+ # ... horizontal input + move_and_slide() ...+```++## Pitfalls++- **3.x signature is gone.** `move_and_slide(velocity)` (returning the new velocity) was+ removed. In 4.x set the `velocity` property and call `move_and_slide()` with no args.+ `move_and_slide(velocity, Vector2.UP)` will not parse.+- **Multiplying velocity by delta.** `move_and_slide()` already accounts for the physics+ delta. Setting `velocity = dir * speed * delta` makes the body crawl.+- **Movement in `_process`** instead of `_physics_process` causes frame-rate-dependent,+ jittery motion. Always move in `_physics_process`.+- **`is_on_floor()` always false** when `up_direction` is wrong (default `Vector2.UP`),+ there is no `CollisionShape2D`, or you never called `move_and_slide()` this frame.+- **Sinking through floors** usually means the collision shape is missing/zero-sized, the+ floor body is on a layer this body's mask doesn't include, or you moved the body via+ `position +=` instead of velocity + `move_and_slide()`.+- **Slope slipping while idle:** keep `floor_stop_on_slope = true` (default) and set a+ `floor_snap_length` so the body sticks to downward slopes.++## References++- For one-way platforms, moving platforms, jump buffering, variable jump height, and+ `move_and_collide()` (manual collision response), read `references/controller-recipes.md`.++## Related skills++- `godot-physics` — collision layers/masks, areas, raycasts, rigid bodies.+- `godot-tilemap` — building the levels this character walks on.+- `godot-animation` — driving sprite/skeletal animation from movement state.+- `platformer` / `input-systems` — full genre template and rebindable input.diff --git a/skills/godot/godot-2d-movement/references/controller-recipes.md b/skills/godot/godot-2d-movement/references/controller-recipes.mdnew file mode 100644index 0000000..f9f6c78--- /dev/null+++ b/skills/godot/godot-2d-movement/references/controller-recipes.md@@ -0,0 +1,91 @@+# 2D controller recipes (Godot 4.3+)++Depth companion to `godot-2d-movement`.++## Variable jump height (release to cut the jump short)++```gdscript+func _physics_process(delta: float) -> void:+ if not is_on_floor():+ velocity.y += gravity * delta+ if Input.is_action_just_pressed("jump") and is_on_floor():+ velocity.y = jump_velocity+ # Releasing jump early dampens upward velocity -> shorter hop.+ if Input.is_action_just_released("jump") and velocity.y < 0.0:+ velocity.y *= 0.5+ # ... horizontal + move_and_slide()+```++## Jump buffering (press slightly before landing still jumps)++```gdscript+@export var buffer_time := 0.1+var _buffer := 0.0++func _physics_process(delta: float) -> void:+ if Input.is_action_just_pressed("jump"):+ _buffer = buffer_time+ else:+ _buffer = max(_buffer - delta, 0.0)++ if _buffer > 0.0 and is_on_floor():+ velocity.y = jump_velocity+ _buffer = 0.0+ # ... gravity + horizontal + move_and_slide()+```++## One-way platforms++On the platform's `CollisionShape2D` / static body, enable **one-way collision** in the+editor (the shape gets a one-way arrow). The `CharacterBody2D` passes through from one+side. To drop through deliberately, briefly disable the body's collision with that layer+or use `set_collision_mask_value()` for a few frames.++## Moving platforms++Make the platform an `AnimatableBody2D` (moves via animation/code, pushes bodies) and+animate it with an `AnimationPlayer` or a `Tween`. A `CharacterBody2D` standing on it+inherits the platform's velocity automatically through `move_and_slide()` (controlled by+`platform_floor_layers` and `platform_on_leave`).++## move_and_collide() — manual collision response++When you want full control (custom bounce, no sliding), use `move_and_collide()`:++```gdscript+func _physics_process(delta: float) -> void:+ var motion := velocity * delta # here you DO scale by delta+ var collision := move_and_collide(motion)+ if collision:+ # Reflect velocity off the surface normal (a simple bounce).+ velocity = velocity.bounce(collision.get_normal())+```++`KinematicCollision2D` exposes `get_normal()`, `get_collider()`, `get_position()`,+`get_remainder()`, and `get_travel()`.++## Acceleration-based feel++Instead of snapping `velocity.x` to `dir * speed`, ramp it for weightier movement:++```gdscript+@export var accel := 1500.0+@export var friction := 1800.0++func _physics_process(delta: float) -> void:+ var dir := Input.get_axis("move_left", "move_right")+ if dir != 0.0:+ velocity.x = move_toward(velocity.x, dir * speed, accel * delta)+ else:+ velocity.x = move_toward(velocity.x, 0.0, friction * delta)+ move_and_slide()+```++## Useful CharacterBody2D properties++- `floor_max_angle` (rad) — steepest slope still treated as floor (default 45°).+- `floor_snap_length` — keeps the body glued to downward slopes.+- `floor_stop_on_slope` — prevents sliding when idle on a slope.+- `max_slides` — iteration cap per `move_and_slide()` (default 4).+- `up_direction` — defines floor/wall/ceiling; `Vector2.UP` for side-scrollers.+- `slide_on_ceiling` — slide vs. stop when hitting a ceiling mid-jump.diff --git a/skills/godot/godot-physics/SKILL.md b/skills/godot/godot-physics/SKILL.mdnew file mode 100644index 0000000..546a13b--- /dev/null+++ b/skills/godot/godot-physics/SKILL.md@@ -0,0 +1,144 @@+---+name: godot-physics+description: >+ Use Godot 4.x physics bodies and detection in 2D and 3D: RigidBody, StaticBody,+ Area, and CharacterBody; collision layers vs masks; contact/overlap signals; and+ raycasts (RayCast nodes and direct space-state queries). Use when configuring+ collision layers/masks, detecting overlaps with Area2D/Area3D, applying forces to a+ RigidBody, or casting rays in a Godot project (.tscn with physics bodies).+license: Apache-2.0+compatibility: Godot 4.3++metadata:+ engine: godot+ category: godot+ difficulty: intermediate+---++# Godot Physics (4.x, 2D + 3D)++Pick the right physics body, wire up collision layers/masks, detect overlaps, and cast+rays. Concepts apply to both 2D and 3D (swap the `2D`/`3D` suffix). Targets+**Godot 4.3+**.++## When to use++- Use when choosing between body types, setting collision layers/masks so the right+ things collide, detecting overlaps (triggers, hurtboxes) with `Area`, applying+ forces/impulses to a `RigidBody`, or casting rays for line-of-sight/ground checks.++**When *not* to use:** kinematic character controllers (`move_and_slide`) →+`godot-2d-movement`; tile collision setup → `godot-tilemap`; tuning the *feel* of physics+(timestep, mass, jitter) → `physics-tuning`.++## Core workflow++1. **Choose the body type:**+ - `StaticBody` — never moves (floors, walls). Collides, no simulation.+ - `RigidBody` — fully simulated (gravity, forces, bouncing). Don't set its+ `position` directly; apply forces/impulses or set `linear_velocity`.+ - `CharacterBody` — script-driven kinematic (see `godot-2d-movement`).+ - `Area` — detects overlaps and can apply gravity/damping; no solid collision.+ Every body needs a `CollisionShape` (or `CollisionPolygon`) child.+2. **Configure layers and masks.** A body is *on* its **layers** and *scans for* its+ **masks**. Two bodies interact only if one's layer is in the other's mask. Name layers+ in Project Settings > Layer Names for clarity.+3. **Detect overlaps** with `Area` signals (`body_entered`, `area_entered`).+4. **Drive RigidBodies with forces/impulses**, or override `_integrate_forces` for full+ control.+5. **Cast rays** with a `RayCast2D/3D` node (polled each frame) or a one-shot space-state+ query from code.++## Patterns++### 1. Collision layers vs masks (set from code)++```gdscript+# Player is on layer 1, scans layers 2 (walls) and 3 (enemies).+func _ready() -> void:+ set_collision_layer_value(1, true) # I am on layer 1+ set_collision_mask_value(2, true) # I collide with things on layer 2+ set_collision_mask_value(3, true) # ...and layer 3+ # Bit-field forms also exist: collision_layer = 1; collision_mask = 0b110+```++### 2. Area2D as a trigger / hurtbox++```gdscript+extends Area2D # e.g. a damage zone++func _ready() -> void:+ body_entered.connect(_on_body_entered)+ area_entered.connect(_on_area_entered)++func _on_body_entered(body: Node2D) -> void:+ if body.has_method("take_damage"):+ body.take_damage(10)++func _on_area_entered(area: Area2D) -> void:+ print("Overlapped area: ", area.name)+```++### 3. Applying force and impulse to a RigidBody3D++```gdscript+extends RigidBody3D++func push(direction: Vector3) -> void:+ apply_central_impulse(direction * 8.0) # instantaneous velocity change++func _physics_process(_delta: float) -> void:+ apply_central_force(Vector3.FORWARD * 4.0) # continuous force (per tick)+ # Never set `position` on a RigidBody to move it; use forces/impulses or+ # set linear_velocity. Use freeze=true if you must hold it in place.+```++### 4. Raycast two ways++```gdscript+# A) RayCast2D node: enable it, then poll after physics has updated.+@onready var ray: RayCast2D = $RayCast2D # set target_position in the editor++func _physics_process(_delta: float) -> void:+ if ray.is_colliding():+ var hit := ray.get_collider()+ var point := ray.get_collision_point()++# B) One-shot query from code (no node needed).+func ground_under(global_from: Vector2) -> Dictionary:+ var space := get_world_2d().direct_space_state+ var query := PhysicsRayQueryParameters2D.create(global_from, global_from + Vector2(0, 64))+ query.collision_mask = 1 # only layer 1+ return space.intersect_ray(query) # {} if nothing hit, else collider/position/normal+```++## Pitfalls++- **Layer vs mask confusion** is the #1 bug. Layer = "what I am"; mask = "what I look+ for". For A to detect B, B's layer must be in A's mask. Detection can be one-directional.+- **Moving a RigidBody by `position`** fights the solver and causes tunneling/jitter.+ Use impulses/forces, set `linear_velocity`, or `freeze` it. To teleport, set position+ and zero the velocities inside `_integrate_forces`.+- **`Area` doesn't fire** when neither monitoring nor monitorable is set, or layers/masks+ don't overlap. `monitoring` must be on for the Area to detect; `monitorable` lets others+ detect it.+- **RayCast2D/3D read stale or no data** if `enabled` is false, or if you read it before+ physics updated — read in `_physics_process`, and call `force_raycast_update()` after+ moving it within the same tick.+- **Forgetting a `CollisionShape`** (or leaving it empty) means the body never collides.+- **Fast objects tunnel** through thin walls; enable **continuous CD** on the RigidBody+ (`continuous_cd`) or use a raycast-based check.+- **`intersect_ray` excludes its own body?** Pass `query.exclude = [self]` (array of RIDs)+ to skip self-hits.++## References++- For `_integrate_forces`, joints, one-way collision, `PhysicsServer` direct access,+ shape queries (`intersect_shape`), and 3D `move_and_collide`, read+ `references/bodies-and-queries.md`.++## Related skills++- `godot-2d-movement` — kinematic `CharacterBody2D` controllers.+- `godot-tilemap` — tile collision shapes and their layers.+- `physics-tuning` — engine-agnostic feel: timestep, mass, drag, CCD.+- `godot-3d-essentials` — 3D scene setup these bodies live in.diff --git a/skills/godot/godot-physics/references/bodies-and-queries.md b/skills/godot/godot-physics/references/bodies-and-queries.mdnew file mode 100644index 0000000..8f11fa5--- /dev/null+++ b/skills/godot/godot-physics/references/bodies-and-queries.md@@ -0,0 +1,95 @@+# Physics bodies & space queries reference (Godot 4.3+)++Depth companion to `godot-physics`. Use the `2D`/`3D` suffix to match your world.++## Body type cheat sheet++| Node | Moves? | Simulated? | Move it by | Use for |+|------|--------|-----------|-----------|---------|+| `StaticBody2D/3D` | No | No | (don't) | Level geometry, walls, floors |+| `AnimatableBody2D/3D` | Yes (scripted/anim) | No | animation / `position` | Moving platforms, doors |+| `RigidBody2D/3D` | Yes | Yes | forces / impulses / `linear_velocity` | Props, debris, balls |+| `CharacterBody2D/3D` | Yes (scripted) | No | `velocity` + `move_and_slide()` | Players, enemies |+| `Area2D/3D` | Yes | No (detection only) | `position` | Triggers, hurt/hitboxes, water |++## Collision layer/mask helpers++```gdscript+set_collision_layer_value(bit, enabled) # 1-based bit (matches editor checkboxes)+set_collision_mask_value(bit, enabled)+get_collision_layer_value(bit) -> bool+collision_layer = 0b0101 # raw bitmask (advanced)+```++Name layers in Project Settings > Layer Names > 2D/3D Physics so the editor checkboxes+read like `Player`, `Walls`, `Enemies`.++## RigidBody control++```gdscript+apply_central_impulse(v) # instant velocity change at center of mass+apply_impulse(v, pos) # impulse at an offset -> adds spin+apply_central_force(v) # continuous force (apply each _physics_process)+apply_torque_impulse(t) # instant angular change+linear_velocity = v # direct set (use sparingly)+freeze = true # stop simulation; freeze_mode = FREEZE_MODE_KINEMATIC|STATIC+gravity_scale = 0.0 # disable gravity for this body+```++Full control via `_integrate_forces`:++```gdscript+func _integrate_forces(state: PhysicsDirectBodyState3D) -> void:+ state.linear_velocity = state.linear_velocity.limit_length(max_speed)+ # To teleport safely: state.transform = new_transform; state.linear_velocity = Vector3.ZERO+```++Enable `contact_monitor` and set `max_contacts_reported > 0` to receive+`body_entered`/`body_exited` on a RigidBody.++## Space-state queries (code-driven, no node)++```gdscript+var space := get_world_3d().direct_space_state++# Ray+var rq := PhysicsRayQueryParameters3D.create(from, to)+rq.collision_mask = 0b0010+rq.exclude = [self.get_rid()]+var hit := space.intersect_ray(rq) # {position, normal, collider, collider_id, rid, shape}++# Shape overlap (e.g. "what's inside this sphere?")+var shape := SphereShape3D.new(); shape.radius = 2.0+var sq := PhysicsShapeQueryParameters3D.new()+sq.shape = shape+sq.transform = Transform3D(Basis(), global_position)+var hits := space.intersect_shape(sq, 32) # array of {collider, rid, shape}+```++`intersect_point` (2D) and `cast_motion`/`collide_shape` cover point picks and swept+tests. Space-state queries must run during physics (`_physics_process`) for valid data.++## RayCast node tips++- Set `target_position` (relative to the node) and `enabled = true`.+- `is_colliding()`, `get_collider()`, `get_collision_point()`, `get_collision_normal()`.+- `collide_with_areas` / `collide_with_bodies` toggle what it detects.+- After moving the ray within a frame, call `force_raycast_update()` before reading.+- `add_exception(node)` / `add_exception_rid(rid)` to skip specific colliders.++## Joints++`PinJoint`, `HingeJoint`, `SliderJoint`, `Generic6DOFJoint` (3D) and `PinJoint2D`,+`GrooveJoint2D`, `DampedSpringJoint2D` (2D) connect two bodies. Assign `node_a`/`node_b`+to the bodies' paths. Use for ragdolls, chains, vehicles, swinging platforms.++## One-way collision++On a `CollisionShape2D`/`CollisionPolygon2D`, enable **one_way_collision** so bodies pass+from one side only (platforms). The pass-through direction is the shape's local up.++## Areas with physics influence++An `Area` can override gravity/damping in its region (`gravity_space_override`,+`gravity`, `linear_damp`) — useful for water, wind, or low-gravity zones affecting any+RigidBody inside.diff --git a/skills/godot/godot-tilemap/SKILL.md b/skills/godot/godot-tilemap/SKILL.mdnew file mode 100644index 0000000..6ed005d--- /dev/null+++ b/skills/godot/godot-tilemap/SKILL.md@@ -0,0 +1,136 @@+---+name: godot-tilemap+description: >+ Build and edit tile-based 2D levels in Godot 4.3+ with TileMapLayer and TileSet:+ paint layers, set up collision/navigation/custom-data on tiles, autotile with+ terrain sets, and read/write cells from code (set_cell, get_cell_tile_data,+ local_to_map). Use when working with TileMapLayer nodes, .tres TileSets, autotiling,+ or migrating a deprecated TileMap node to TileMapLayer.+license: Apache-2.0+compatibility: Godot 4.3+ (TileMapLayer; TileMap node deprecated)+metadata:+ engine: godot+ category: godot+ difficulty: intermediate+---++# Godot TileMap (4.3+ TileMapLayer)++Author tile-based levels with `TileMapLayer` + `TileSet`, add per-tile collision and+custom data, autotile with terrains, and manipulate cells at runtime. Targets+**Godot 4.3+**, where `TileMapLayer` replaces the now-deprecated `TileMap` node.++## When to use++- Use when designing 2D levels from a tile grid, configuring a `TileSet` (collision,+ navigation, custom data, terrains), or reading/writing tiles from code.+- Use when migrating a `TileMap` node (single node, many layers) to multiple+ `TileMapLayer` nodes (one layer each).++**When *not* to use:** moving the player across the tiles → `godot-2d-movement`; general+physics bodies/raycasts → `godot-physics`; procedural map *generation* algorithms →+`procedural-gen`; level *design* practice → `level-design`.++## Core workflow++1. **Add a `TileMapLayer` node** (one per visual/logical layer: background, walls,+ foreground). Each holds exactly one layer of tiles.+2. **Create or assign a `TileSet`** on the layer's `tile_set` property. Add an atlas+ source (a texture sliced into tiles) in the TileSet editor. Save the TileSet as an+ external `.tres` so multiple layers/levels reuse it.+3. **Add tile data in the TileSet editor:** physics layers (collision polygons),+ navigation layers, occlusion, and **custom data layers** (typed per-tile values like+ `damage` or `is_ladder`).+4. **Paint** in the TileMap bottom panel (Paint/Line/Rectangle/Bucket). For self-+ connecting tiles, define a **terrain set** and paint with Connect/Path mode.+5. **Enable per-layer collision/navigation** via the layer's `collision_enabled` /+ `navigation_enabled` properties.+6. **Read/write from code** with `local_to_map`, `set_cell`, `get_cell_source_id`, and+ `get_cell_tile_data(...).get_custom_data(...)`.++## Patterns++### 1. Convert mouse position to a cell and read its custom data++```gdscript+extends TileMapLayer++func _unhandled_input(event: InputEvent) -> void:+ if event is InputEventMouseButton and event.pressed:+ # local_to_map expects local coords; convert from global first.+ var cell := local_to_map(to_local(event.position))+ var data := get_cell_tile_data(cell) # TileData or null+ if data:+ var dmg: int = data.get_custom_data("damage") # custom data layer+ print("Cell %s deals %d damage" % [cell, dmg])+```++### 2. Place and erase tiles at runtime++```gdscript+# set_cell(coords, source_id, atlas_coords, alternative_tile = 0)+func place_wall(cell: Vector2i) -> void:+ set_cell(cell, 0, Vector2i(2, 1)) # source 0, atlas tile at column 2, row 1++func dig(cell: Vector2i) -> void:+ erase_cell(cell) # same as set_cell(cell, -1)++func clear_level() -> void:+ clear() # remove every tile on this layer+```++### 3. Autotiling a region with a terrain set++```gdscript+# Paint a filled area with terrain `terrain` of terrain set `terrain_set`;+# Godot picks the correct edge/corner tiles to connect them.+func fill_with_grass(cells: Array[Vector2i]) -> void:+ var terrain_set := 0+ var grass_terrain := 0+ set_cells_terrain_connect(cells, terrain_set, grass_terrain, true)+```++### 4. Iterate placed tiles (e.g. find all spawn tiles)++```gdscript+func find_spawns() -> Array[Vector2i]:+ var spawns: Array[Vector2i] = []+ for cell in get_used_cells():+ var data := get_cell_tile_data(cell)+ if data and data.get_custom_data("is_spawn"):+ spawns.append(cell)+ return spawns+```++## Pitfalls++- **`TileMap` node is deprecated in 4.3.** Use `TileMapLayer` nodes (one layer per node);+ group them under a parent `Node2D`. Old `TileMap` calls that took a `layer` argument+ (`set_cell(layer, ...)`) do not apply to `TileMapLayer`.+- **`local_to_map` needs local coordinates.** Mouse/global positions must be converted+ with `to_local(...)` first, or cells will be offset.+- **`get_cell_tile_data` returns `null`** for empty cells or non-atlas sources — always+ null-check before `get_custom_data`.+- **Custom data is typed.** A layer declared as `int` returns `int`; reading it as the+ wrong type or referencing a non-existent layer name errors. Define the layer in the+ TileSet first.+- **Terrains need every combination defined.** `set_cells_terrain_connect` produces odd+ results if the TileSet's terrain bitmask peering is incomplete.+- **Runtime edits are batched** to end-of-frame. If you must read updated internals+ immediately after `set_cell`, call `update_internals()` (expensive — avoid in loops).+- **Collision not working?** Check the layer's `collision_enabled`, that the tile has a+ physics layer with a polygon, and that the TileSet's physics layer mask matches your+ bodies.++## References++- For TileSet setup (atlas sources, physics/navigation/custom-data layers, terrain+ bitmasks), scene tiles, Y-sorting, and runtime tile-data overrides+ (`_use_tile_data_runtime_update`), read `references/tileset-and-terrains.md`.++## Related skills++- `godot-2d-movement` — characters that walk on these tiles.+- `godot-physics` — collision layers/masks the tile collisions participate in.+- `procedural-gen` — generating tilemaps from noise/RNG.+- `level-design` / `roguelike` — design practice and grid-based genres.diff --git a/skills/godot/godot-tilemap/references/tileset-and-terrains.md b/skills/godot/godot-tilemap/references/tileset-and-terrains.mdnew file mode 100644index 0000000..a61d8ab--- /dev/null+++ b/skills/godot/godot-tilemap/references/tileset-and-terrains.md@@ -0,0 +1,95 @@+# TileSet & terrains reference (Godot 4.3+)++Depth companion to `godot-tilemap`.++## TileSet sources++A `TileSet` holds one or more **sources**, each with an integer `source_id`:++- **Atlas source** (`TileSetAtlasSource`) — a single texture sliced into a grid of tiles.+ Most common. Tiles are addressed by `atlas_coords: Vector2i` (column, row).+- **Scene collection source** (`TileSetScenesCollectionSource`) — places whole scenes as+ tiles (e.g. a tile that is a particle emitter). `atlas_coords` is always `Vector2i(0,0)`+ and the `alternative_tile` selects the scene.++In code, `set_cell(coords, source_id, atlas_coords, alternative_tile)` fully identifies a+tile. `alternative_tile` selects flips/rotations or alternative tiles you defined.++## Per-tile data layers++Configured in the TileSet editor; each layer applies to every tile you paint data onto:++- **Physics layers** — collision polygons per tile. The TileSet defines layer index ++ collision layer/mask; `TileMapLayer.collision_enabled` toggles them at the node level.+- **Navigation layers** — navigation polygons for pathfinding. Note the docs caution that+ built-in tile navigation has limits; consider baking a `NavigationRegion2D` for large+ maps.+- **Occlusion layers** — light occluder polygons per tile.+- **Custom data layers** — named, typed values (`String`, `int`, `bool`, `Vector2`, ...).+ Read with `tile_data.get_custom_data("name")`. Ideal for gameplay metadata+ (`is_ladder`, `friction`, `damage`, `is_spawn`).++## Terrains (autotiling)++1. In the TileSet, create a **terrain set** (choose a matching mode: Match Corners and+ Sides, Match Corners, or Match Sides).+2. Add one or more **terrains** to that set.+3. Paint terrain **peering bits** onto each tile's edges/corners so Godot knows how tiles+ connect.+4. In the TileMap panel's **Terrains** tab, paint with **Connect** (auto-connect to+ neighbors on the layer) or **Path** (connect only along the current stroke).++From code:++```gdscript+set_cells_terrain_connect(cells, terrain_set, terrain, ignore_empty_terrains)+set_cells_terrain_path(path_cells, terrain_set, terrain, ignore_empty_terrains)+```++Both require the TileSet to have all needed bit combinations defined; missing+combinations yield placeholder/odd tiles.++## Coordinate conversions++```gdscript+local_to_map(local_pos: Vector2) -> Vector2i # pixel (local) -> cell+map_to_local(cell: Vector2i) -> Vector2 # cell -> centered local pixel pos+get_neighbor_cell(cell, TileSet.CELL_NEIGHBOR_RIGHT_SIDE)+get_surrounding_cells(cell) # all edge neighbors+```++For global coordinates wrap with `to_local()` / `to_global()` (Node2D methods).++## Y-sorting (top-down depth)++Enable `CanvasItem.y_sort_enabled` on the `TileMapLayer` and set per-tile+`y_sort_origin` (and the layer's `y_sort_origin`) so taller tiles and characters overlap+correctly. The rendering quadrant optimization is bypassed for Y-sorted layers (tiles are+grouped by Y instead).++## Runtime tile-data overrides++To vary a tile's data at runtime without editing the shared TileSet, override on a+`TileMapLayer` subclass:++```gdscript+extends TileMapLayer++func _use_tile_data_runtime_update(coords: Vector2i) -> bool:+ return get_cell_atlas_coords(coords) == Vector2i(3, 0) # only these tiles++func _tile_data_runtime_update(coords: Vector2i, tile_data: TileData) -> void:+ # Duplicate sub-resources before editing — they are shared with the TileSet!+ tile_data.modulate = Color(1, 0.6, 0.6)+```++Call `notify_runtime_tile_data_update()` when the result of `_use_tile_data_runtime_update`+should change. These updates are computationally expensive — restrict them to the few+tiles that need them.++## Migrating from the TileMap node++A deprecated `TileMap` node with N layers becomes N `TileMapLayer` nodes. Godot offers a+"Extract TileMap layers as individual TileMapLayer nodes" tool from the TileMap node's+toolbar. After extraction, update scripts: drop the leading `layer` argument from cell+calls and target the specific `TileMapLayer` node instead.