Player collision being offset by one tile on TileMap

Godot Version

4.4.1

Question

`The players collision with the tiles in my tilemap layer is being offset by one tile. This results in the player colliding with the floor tiles just before the wall tiles to the top and the left and passing through the first wall tiles to the right and the bottom.

This is the script attached to the player:

extends Area2D

@export var cell_size := 16
@onready var tilemap = get_parent().get_node("Map/TileMapLayer")

var input_direction := Vector2.ZERO

func _ready():
	position = position.snapped(Vector2.ONE * cell_size)
    position += Vector2.ONE * cell_size / 2
	
func _process(delta):
	if Input.is_action_just_pressed("move_left"):
		try_move(Vector2.LEFT)
	if Input.is_action_just_pressed("move_right"):
		try_move(Vector2.RIGHT)
	if Input.is_action_just_pressed("move_up"):
		try_move(Vector2.UP)
	if Input.is_action_just_pressed("move_down"):
		try_move(Vector2.DOWN)
		
func try_move(direction: Vector2):
	var target_position = position + (direction * cell_size)
	var target_tile_pos = tilemap.local_to_map(target_position)
	
	var tile_data = tilemap.get_cell_tile_data(target_tile_pos)
	if tile_data and tile_data.get_custom_data("walkable"):
		position = target_position
	else:
		print("Bonk! Can't move there.")

I could get rid of the issue if I did this:

var target_tile_pos = tilemap.local_to_map(target_position + vector2(cell_size, cell_size))

But I want to know if there is any other way to resolve the issue.

Thank you for your responses in advance.
`

I think this might just be a position issue. IIRC local_to_map also takes the top left corner of the tile as the position, like many other “position” methods in godot. Hardcoding the off-set after calling position, like you did, is a decent solve IMO.

1 Like

Thanks for the response. Yeah, I’ve looked around and haven’t really found any other way to resolve it so, I just decided to go with that.