Any reliable way to get tile position from collision info's touch()?

My game use a tile map as background, and I set collision with player sprite properly, player could generate collision info when touches specified tile ID.

Now I want to implement a mechanism, that when player touches a "Wall" tile, the tile's ID will be changed.

To do that, according the SDK's document, I need to get the tile via tilemap:getTileAtPosition(x, y) first. But this method require the "row, column" for tilemap, but the collision info's touch() returns a coordinates in screen space.

Is there any reliable way to get touched tile from collision info?

You should be able to calculate this by using the position of the collision, the position at which the tilemap was drawn, the width/height of the tiles, and maybe the current draw offset, if used.

For example, if we have the positions of the collision and of the tilemap in the level, and the width and height of the tiles are known:

xDelta = xCollision - xTilemap
yDelta = yCollision - yTilemap

xTileIndex = math.floor(xDelta/xTileWidth) + 1
yTileIndex = math.floor(yDelta/yTileWidth) + 1

tile = tilemap:getTileAtPosition(xTileIndex, yTileIndex)

Do you know if the collision touch() data accounts for draw offset? If it doesn't, and it actually just gives the position of the collision relative to the top-left corner of the screen, then I guess you will need to calculate the position of the collision in the level first by subtracting the current draw offset.

1 Like