• Godot Help
  • How to get the position of the cell or sprite the player left?

I'm trying to create a mechanic that makes the player return to the last cell he touched before falling into a killzone
the system works I tested it as follows

LastcollidedTileMap.gd

extends Area2D

@onready var collision = $CollisionShape2D

func _on_body_exited(body):
    if body.name == "TileMap":
        Global.last_position_before_jump = collision.global_position

killzone.gd

extends Area2D

@onready var timer = $Timer
var player = null

func _on_body_entered(body):
    print("You Died!")
    player = body
    timer.start()

func _on_timer_timeout():
    player.global_position = Global.last_position_before_jump

The problem is if the player stays on the edge of the cell
it will respawn on the edge obviously and this can make the player die easily

my idea is to obtain the central position of the last cell that the player stopped touching based on the location of "collision"

  • xyz replied to this.

    paralhama Use TileMap::local_to_map() to get the cell coordinate and then TileMap::map_to_local() to get the actual coordinate that's snapped to a cell. Alternatively you can use snapped() to align to the cell

    Thank You!
    Let me see if understand
    I use local_to_map() to get tile position on grid
    and then i use map_to_local() to convert to a global position
    Correct me if i misunderstood...

    I'm tryng to read documentation about snapped() but my english still crawling (I wold stay greatful if you explain to me)

    Then i made it on my code:
    LastcollidedTileMap.gd

    extends Area2D
    
    @onready var player = $".."
    
    
    func _on_body_exited(body):
    	if body.name == "TileMap":
    		var tile = body.local_to_map(player.global_position)
    		var PositionTile = body.map_to_local(tile)
    		Global.last_position_before_jump = PositionTile

    Seems works fine, I passed a long time testing and the problem with the player reappearing on the edge of tile not happens again
    but if you have a suggestion to improve mt code i will be greatful again xD

    • xyz replied to this.

      paralhama Let me see if understand
      I use local_to_map() to get tile position on grid
      and then i use map_to_local() to convert to a global position
      Correct me if i misunderstood...

      Yes that's the idea. To center the player more precisely you might want to calculate the center of the tile, and position player's center to align with that center. But it really depends where the player origin is in respect to its sprite.