Detecting if two blocks of a TileMap are the same

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Ryoschin

By block i mean a collection of TileMap cells that touch each other
So, in my 2D platformer game, I’m trying to make a system where you shoot a lance and then pull yourself towards the place where the Lance hit a wall. I have set up a map with the TileMap node, and made everthing work by raycasting towards the Mouse Position to see where is the lance supposed to hit, shooting it to there and then lerping the player towards that location. It works, but what happens if I’m standing on a block of the TileMap and shoot towards it? My player gets lerped towards that position and gets stuck in the wall. To avoid that problem, I thought I could identify if the blocks that my player is standing on and that my lance hit are the same, but no functions that I found on the Godot docs seemed to work (or I’m just too dumb to figure them out), and all the tutorials on TileMaps out there are useless because the most of them are 3.5 or earlier, and I’m using Godot 4.0. I’ve been struggling with this for too long, and any help is appreciated!

:bust_in_silhouette: Reply From: Marco-

To check whether your player is on the same tile you need a reference to both the player and the tile map.

@onready var tm: TileMap = $MyTileMap
@onready var player: CharacterBody2D = $MyPlayer

Save the position from your raycast in a variable target_pos and proceed with:

var target_tile_map_pos: Vector2i = tm.local_to_map(target_pos)
var target_tile_coords: Vector2i = tm.get_cell_atlas_coords(0, target_tile_map_pos)

var player_map_pos: Vector2i = tm.local_to_map(player.global_position)
var player_tile_coords: Vector2i = tm.get_cell_atlas_coords(0, player_map_pos)

if target_tile_coords == player_tile_coords:
    return

This code above extracts the coordinates in your tilemap for the texture of the tile in question and simply checks whether your player is standing on the same texture. Hope this helps. Instead of the return in the if at the end you can write your own code as you see fit. Also remember to swap out the 0 in the tm.get_cell_atlas_coords call and replace it with the index of the correct layer you need. Read the docs on that for more information.

It works as I wanted it to, I was stuck on this for so long, thank you so much!

Ryoschin | 2023-03-30 12:20