How i could convert my player's position to a tile index using world_to_map?

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

And how to check if the tile is free when the tilemap is flipped (in my game when you press certain buttons, the tilemap is flipped horizontal or vertically but the character and maybe enemies and objects, that makes the character sometimes be stuck) and, if not, move the character (its collision shape) to the nearest free space (being the priorities up and down (depending on the position of the center (if in the middle of the tile, then up) ) and left or right if there’s no space in the previous directions) ? I tried to do it, but always gives me -1.
here’s my code:

extends Node2D


func _process(delta):
    #NodeD2 = center of the viewport.

	if Input.is_action_just_pressed("ui_accept"):
		if $NodeD2.scale.y == 1:
			$NodeD2.scale.y = -1
		else:
			$NodeD2.scale.y = 1
	if Input.is_action_just_pressed("ui_cancel"):
		if $NodeD2.scale.x == 1:
			$NodeD2.scale.x = -1
		else:
			$NodeD2.scale.x = 1
	
	var cell = $NodeD2/TileMap.world_to_map(get_global_position())
	var tile_id = $NodeD2/TileMap.get_cellv(cell)
	print(tile_id)
:bust_in_silhouette: Reply From: njamster

I tried to do it

General rule of thumb when asking a question: if you already tried something, provide people with as much information as possible regarding what you’ve tried!

How i could convert my player’s position to a tile index using world_to_map?

var cell = $TileMap.world_to_map($Player.global_position)
var tile_id = $TileMap.get_cellv(cell)

And how to check if the tile is free

if tile_id == -1:
    print("free")

when the tilemap is flipped

Not sure what you mean here by flipped. Care to elaborate?

if not, move the character (along with its collision shape) to the nearest free space

Why would someone ever want to move a character without their collision shape? Respectively, why do you think that deserves a mention here? Also there is no such thing as one nearest free space in a grid - there are potentially up to four! Moving a character does not work differently when using a TileMap!

Sorry for not being clear in the description and make the question very hastily. I’ll fix it.

Gonz4 L | 2020-09-20 18:42