godotengine / godotengine/godot-docs
TileSet custom metadata section could use some sample code
- Dominant language
- reStructuredText
- Stars
- 5.7k
- Forks
- 3.8k
- Avg merge
- 1d 20h
- Merged PRs (30d)
- 25
Description
**Your Godot version:** 4.2.1/4.3
**Issue description:**
https://docs.godotengine.org/en/latest/tutorials/2d/using_tilesets.html#assigning-custom-metadata-to-the-tileset-s-tiles describes how to assign custom metadata to particular tiles, but not how to use that metadata from script to do the things the section says the metadata is useful for ("damage that a tile should deal when the player touches it, or whether a tile can be destroyed using a weapon"). [`TileMap.get_cell_tile_data()`](https://docs.godotengine.org/en/stable/classes/class_tilemap.html#class-tilemap-method-get-cell-tile-data ) has an example of retrieving the custom metadata on a mouse click, but not for the collisions in the example use cases, and it's hard to find since it's not linked from the tutorial section.
I'm happy to send a PR with improved text, but I'd like to find out what ought to go there before I write it. :) Some ideas:
The sample code should cover the two example use cases, so
1. how to retrieve the data when a `CharacterBody2D` slides into the tile, and
2. how to retrieve it when an `Area2D` fires its `body_entered` signal (actually `body_shape_entered`?) because it hit the tile.
For the first, I think the code is something like:
```gdscript
var tile_damage = 0
for i in get_slide_collision_count():
var collision := get_slide_collision(i)
var tilemap := collision .get_collider() as TileMap
if tilemap:
var rid := collision .get_collider_rid()
var layer := tilemap.get_layer_for_body_rid(rid)
var coords := tilemap.get_coords_for_body_rid(rid)
var tiledata := tilemap.get_cell_tile_data(layer, coords)
if tiledata:
var this_tile_damage = tiledata.get_custom_data("damage") as int
if this_tile_damage:
tile_damage = max(tile_damage, this_tile_damage)
damage_player(tile_damage)
```
For the second, something like:
```gdscript
func _on_body_shape_entered(body_rid: RID, body: Node, _body_shape_index: int, _local_shape_index: int) -> void:
var tilemap := body as TileMap
if tilemap:
var layer := tilemap.get_layer_for_body_rid(body_rid)
var coords := tilemap.get_coords_for_body_rid(body_rid)
var tiledata := tilemap.get_cell_tile_data(layer, coords)
if tiledata:
if tiledata.get_custom_data("breakable") as bool:
break_tile(tilemap, layer, coords)
```
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.