This is a fairly common question both here and in other places like Reddit. But I am a bit stuck as the commonly proposed solution does not seem to work for me.
When a KinematicBody2D collides with a tile in a TileMap, I want to get that tile's id. Here is how I am doing this:
var velocity = Vector2.ZERO
velocity.x = 0
velocity.y = 100
velocity.x = -60
velocity.x = 60
velocity = move_and_slide(velocity, Vector2.UP)
for i in range(get_slide_count()):
var collision = get_slide_collision(i)
if collision.collider is TileMap:
var cell = collision.collider.world_to_map(collision.position - collision.normal)
var tileId = collision.collider.get_cellv(cell)
print("tileId ", tileId)
The commonly proposed solutions seems to rely on
tilemap.world_to_map(collision.position - collision.normal)
But I am finding this only works if the collision occurs on the left side of the tile. If it occurs on the right half, I end up with
-1 as the tile id.
I made a tiny Godot project that shows the issue I am having:
If you run that project, then hold down the left arrow key, you'll see in the output console the tile id go from
0. I am expecting it to always be
The above code is from this project. My actual project has more complex code, but ultimately seems to have the same problem.
Can anyone tell me what I am doing wrong?
I am using Godot 3.2.2.stable