Communityコーディング&開発github.com

ziva-sh/godot-tilemaplayer

Godot 4.3+のTileMapLayerノードに関する正しいコードを提供します。セルの設定(set_cell(coords, source_id, atlas_coords))、セルとカスタムデータの読み取り、消去、座標変換、地形、TileSet物理レイヤーによるタイル衝突、ボディがヒットしたタイルの特定、そして非推奨のTileMapノードとそのレイヤーインデックスAPIからの移行をカバーします。GDScriptでタイルの配置、読み取り、消去を行う際や、コードでのTileSet構築、手続き的レベル生成、タイル衝突処理、Godot 3またはGodot 4.0からのTileMapコード移植に使用してください。

godot-tilemaplayer とは?

このスキルは、Godot 4.3以降で標準となった`TileMapLayer`ノードを正しく扱うための総合ガイドです。非推奨となった`TileMap`ノードやGodot 3時代の旧APIは使用せず、新しいAPIに焦点を当てています。 主な機能として、`set_cell(coords, source_id, atlas_coords)`によるタイルの配置、`get_cell_source_id()`や`get_cell_atlas_coords()`によるセル情報の読み取り、`erase_cell()`による消去、`local_to_map()`/`map_to_local()`による座標変換をカバー。また、TileSetエディタで設定したカスタムデータレイヤーからの値取得、地形(オートタイル)のコード上での設定、物理レイヤーを用いたタイル衝突の処理、`CharacterBody2D`が衝突したタイル座標の特定方法も解説しています。 さらに、ランタイムでのTileSet構築コード例や、`TileMap`から`TileMapLayer`への移行手順(エディタの自動抽出機能を含む)とAPI対応表も提供。初心者が陥りがちなミス(座標系の誤用、引数の間違い、衝突判定の前提条件など)についても注意喚起しています。 対応プラットフォームはGodot Engine 4.3以上であり、GDScriptユーザーを主な対象としています。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ziva-sh/godot-skills/tree/HEAD/skills/godot-tilemaplayer

Installed? Explore more コーディング&開発 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

TileMapLayer (Godot 4.3+)

Godot 4.3でTileMapLayerノードが追加され、TileMapは非推奨になりました。各TileMapLayerは1つのレイヤーを表すため、地面、壁、装飾からなるレベルは、1つのTileSetを共有する3つの兄弟TileMapLayerノードで構成されます。新しいコードをTileMapに対して書かず、Godot 3のAPI(set_cellv、world_to_map、set_cell(x, y, tile_id))も決して使用しないでください。

セルAPI

セルは整数のマップ座標(Vector2i)で識別されます。タイルは次の3つの値で識別されます。

  • source_id: TileSet内のソース(アトラステクスチャまたはシーンコレクション)のID。最初のアトラスは通常0です。TileSetエディタまたはTileSet.add_source()の戻り値を確認してください。
  • atlas_coords: アトラス内でのタイルの列と行(ピクセルではなくタイル単位)。
  • alternative_tile: 反転または回転した代替タイルを作成していない限り0。
extends TileMapLayer

const SOURCE_ID := 0
const GRASS := Vector2i(0, 0)
const WALL := Vector2i(1, 0)


func _ready() -> void:
	for x in range(10):
		set_cell(Vector2i(x, 5), SOURCE_ID, GRASS)
	set_cell(Vector2i(3, 4), SOURCE_ID, WALL)

	var source_id := get_cell_source_id(Vector2i(3, 4))  # セルが空の場合は-1
	var atlas := get_cell_atlas_coords(Vector2i(3, 4))  # 空の場合はVector2i(-1, -1)
	print(source_id, atlas)

	erase_cell(Vector2i(3, 4))
	print(get_used_cells().size(), " cells, bounds ", get_used_rect())


func cell_at_global(global_point: Vector2) -> Vector2i:
	return local_to_map(to_local(global_point))


func center_of_cell(coords: Vector2i) -> Vector2:
	# map_to_localはこのレイヤーのローカル空間におけるセル中心を返します。
	return to_global(map_to_local(coords))

重要な事実:

  • デフォルトの引数でset_cell(coords)を呼び出すと、セルが消去されます(source_idのデフォルトは-1)。タイルを配置するときは、必ずsource_idとatlas_coordsを渡してください。
  • アトラスに存在しないatlas_coordsを設定しても、セルはエラーなく保存されます(get_cell_source_id()はソースを返します)。後でget_cell_tile_data()を呼び出すと、The TileSetAtlasSource atlas has no tile at (x, y).というログが出力され、nullを返します。
  • local_to_map()とmap_to_local()はレイヤーのローカル空間で動作します。レイヤーが移動または拡大縮小されている場合は、to_local() / to_global()で変換してください。
  • get_used_cells_by_id(source_id, atlas_coords)は、1つのタイルを使用しているすべてのセルを検索します。
  • 変更はフレームの終わりにバッチ処理されます。衝突やシーンタイルをすぐに更新する必要がある場合は、update_internals()を呼び出してください。

タイルごとのカスタムデータ

TileSetでカスタムデータレイヤーを追加し(インスペクター > TileSet > Custom Data Layers、例: int型のdamage)、TileSetエディタで値をペイントしてから、コードで読み取ります:

extends TileMapLayer


func damage_at(coords: Vector2i) -> int:
	var data := get_cell_tile_data(coords)
	if data == null:
		return 0
	return data.get_custom_data("damage")

get_cell_tile_data()は、空のセルやシーンコレクションタイルに対してはnullを返すため、メソッドを呼び出す前にチェックしてください。

地形(オートタイル)

Godot 3のオートタイルビットマスクは地形セットになりました。TileSetで地形セットと地形を追加し、TileSetエディタで各タイルの地形接続ビットをペイントします。コードでは、塗りつぶしたいすべてのセルを渡します:

extends TileMapLayer

const TERRAIN_SET := 0
const DIRT := 0


func paint_room(rect: Rect2i) -> void:
	var cells: Array[Vector2i] = []
	for x in range(rect.position.x, rect.end.x):
		for y in range(rect.position.y, rect.end.y):
			cells.append(Vector2i(x, y))
	set_cells_terrain_connect(cells, TERRAIN_SET, DIRT)

set_cells_terrain_connect()はエッジが接続されるようにタイルを選びます。set_cells_terrain_path()はパスとして描かれる道や川のためのものです。結果に間違ったタイルや欠落したタイルが表示される場合、TileSetの接続ビットが不完全です。コードで修正することはできません。

衝突

タイルが衝突するのは、TileSetに物理レイヤーがあり(TileSetインスペクター > Physics Layers > Add Element)、そのレイヤーにタイルの衝突ポリゴンが設定されている場合のみです(TileSetエディタでタイルを選択し、Physics > Physics Layer 0; タイル全体の長方形にするにはFキーを押します)。レイヤーのcollision_enabledプロパティはデフォルトでオンです。物理レイヤーにはcollision_layerとcollision_maskもあり、これらはノードではなくTileSetで設定します。

CharacterBody2Dがどのタイルに接触したかを調べるには、衝突点を使用します。get_coords_for_body_rid()はセルの座標ではなく物理クアドラントの座標を返します(physics_quadrant_sizeが1の場合を除く。Godot 4.5+ではデフォルトで最大16x16セルが1つのボディにマージされます):

extends CharacterBody2D

@export var level: TileMapLayer


func _physics_process(delta: float) -> void:
	velocity += get_gravity() * delta
	move_and_slide()
	for i in get_slide_collision_count():
		var collision := get_slide_collision(i)
		if collision.get_collider() == level:
			# 接触点はタイルのエッジ上にあるため、少しタイルの内側に進む。
			var inside := collision.get_position() - collision.get_normal()
			var coords := level.local_to_map(level.to_local(inside))
			print("Touching tile ", coords)

コードでのTileSet構築

手続き的レベルや、TileSetエディタを使用できないテストに便利です。衝突ポリゴンの点はタイル中心を基準とします。

extends Node2D


func _ready() -> void:
	var tile_set := TileSet.new()
	tile_set.tile_size = Vector2i(16, 16)
	tile_set.add_physics_layer()

	var source := TileSetAtlasSource.new()
	source.texture = load("res://tiles.png") as Texture2D
	source.texture_region_size = Vector2i(16, 16)
	source.create_tile(Vector2i(0, 0))
	var source_id := tile_set.add_source(source)

	var data := source.get_tile_data(Vector2i(0, 0), 0)
	data.add_collision_polygon(0)
	data.set_collision_polygon_points(0, 0, PackedVector2Array([
		Vector2(-8, -8), Vector2(8, -8), Vector2(8, 8), Vector2(-8, 8),
	]))

	var layer := TileMapLayer.new()
	layer.tile_set = tile_set
	add_child(layer)
	layer.set_cell(Vector2i(0, 0), source_id, Vector2i(0, 0))

TileMapからの移行

エディタで: TileMapを選択し、TileMapボトムパネルを開き、ツールボックスアイコンをクリックして「Extract TileMap layers as individual TileMapLayer nodes」を選択します。その後、スクリプトを更新します。layerインデックスを受け取っていたすべてのTileMapメソッドは、そのレイヤーのノード上のメソッド(インデックスなし)になります。

旧コードTileMapLayer
tile_map.set_cell(0, coords, source_id, atlas_coords)ground.set_cell(coords, source_id, atlas_coords)
tile_map.get_cell_source_id(1, coords)walls.get_cell_source_id(coords)
tile_map.get_used_cells(0)ground.get_used_cells()
tile_map.set_layer_enabled(2, false)decoration.enabled = false
tile_map.set_layer_z_index(1, 5)walls.z_index = 5
Godot 3 set_cellv(pos, id), world_to_map(p), map_to_world(c)set_cell(coords, source_id, atlas_coords), local_to_map(p), map_to_local(c)

よくある間違い

  • set_cell()にピクセル位置を渡す。最初にlocal_to_map()で変換してください。
  • 1つの数値でset_cell(coords, tile_index)を呼び出す: 2番目の引数はソースIDであり、atlas_coordsのデフォルトはVector2i(-1, -1)のため、セルが消去されます。
  • 物理レイヤーのないTileSet、またはポリゴンがペイントされていないタイルからの衝突を期待する。
  • デフォルトのphysics_quadrant_sizeでget_coords_for_body_rid()を使用し、クアドラント座標を取得してしまう。
  • nullチェックなしでget_cell_tile_data()のメソッドを呼び出す。
  • 古いチュートリアルに従って新しい作業にTileMapノードを追加する。レイヤーごとに1つのTileMapLayerを使用してください。

Individual skills in this repo

This repo contains 4 individual skills — each has its own dedicated page.

ziva-sh/godot-4-api-pitfalls

Fixes Godot 3 APIs and GDScript syntax that AI assistants write into Godot 4 projects, such as KinematicBody2D, move_and_slide(velocity), export, onready, setget, yield, string connect(), instance(), rand_range, the Tween node, File, change_scene, Spatial, rect_* properties, Pool*Array, OS time functions and the old TileMap API. Use when writing, reviewing or porting GDScript for Godot 4.x, when a script fails with "not declared", "not found in base", "was removed in Godot 4" or "is not present

ziva-sh/godot-control-layout

Builds Godot 4 Control UIs that resize instead of clipping or overlapping - containers versus anchors, anchor presets from code, size flags, custom_minimum_size, MarginContainer margins, Label wrapping, mouse_filter, CanvasLayer HUDs, Godot 4 theme override names (add_theme_color_override and friends) and the display/window/stretch settings for multiple resolutions. Use when creating or fixing menus, HUDs, dialogs and inventory screens, when UI elements are cut off, zero-sized, overlapping, igno

ziva-sh/godot-scene-organization

Structures Godot 4 projects so scenes stay reusable and references do not break - when to make a scene, a script or a Resource, instancing with @export PackedScene, preload and load, @onready and %UniqueName node access, _ready order, groups, autoloads, class_name, and resource UIDs with the .uid files added in Godot 4.4, including how to move or rename files safely. Use when creating new scenes or scripts, deciding how nodes find each other, adding global state or an event bus, moving or renami

ziva-sh/godot-signals

Godot 4 signal patterns and their failure modes - declaring typed signals, emit(), connect() and disconnect() with Callables, bind() and unbind(), lambdas, CONNECT_ONE_SHOT and CONNECT_DEFERRED, await on signals and timers, editor-made connections stored in .tscn files, and the call down, signal up rule. Use when wiring UI buttons, timers, Area2D or body events and custom game events, when replacing Godot 3 connect("signal", self, "method") or yield code, or when debugging "already connected", "

関連スキル