Hi! In the city-builder I’m making, users can directly interact with the tilesets to place buildings, but when I make the camera zoom anything but 1, it affects the offset of the tile placement, and scale as well.
Here is my code:
extends TileMap
var tilemap_position
var tilemap
var groundlayer = 0
var source_id = 1
func _ready():
pass
func _process(_delta):
pass
func _input(event):
# Mouse in viewport coordinates.
tilemap = $"."
groundlayer = 0
source_id = 1
if Input.is_action_just_pressed("place"):
print("Mouse Click at: ", event.position)
tilemap_position = tilemap.local_to_map(Vector2i(event.position.x -64, event.position.y +40))
print(tilemap_position)
set_cell(0, tilemap_position, source_id, Vector2i(0,0))
$"../Resources".set_cell(0, tilemap_position, source_id, Vector2i(0,0))
It seems that whenever I zoom the camera by a factor of 2, clicking inside one tile allows the user to place houses in four different tiles far away, depending on the area in the tile where the click happens. Same for a zoom factor of 3: 9 houses can be placed.
I have the same issue, and took me a while to realize that it’s happening because zooming the camera doesn’t change the coordinates returned by event.position. Instead, that position is calculated always relative to the game window, no matter what you actually see inside the window (the viewport).
For example, if you have a window size of (300, 200), and you click the top left corner of the window, you get (0, 0). If you zoom in 2x, then the viewport changes to be half the size, and since it zooms towards the center and not the origin (top left), it’s also offset by 50% of its own size. This means the new viewport is size (150, 100), and is at location (75, 50). If we click the top left corner of the screen again, we should get (75, 50), but in reality we get (0, 0), which is probably not what we want.
Having said that, I haven’t yet solved this problem through code.