Godot Version
4.4.stable
Question
I am trying to code my own build mechanic, with a preview building function and so far, I was able to figure out how to implement the preview version of the building. The building follows the mouse in an opaque form. However, I’m trying to implement the “build” mechanic by using the set_cell function when the “click” input is done. However, I don’t see the building get built. I feel like I’m close, but I have no idea why this is not happening the way it’s intended. Nodes are organized as follows:
extends TileMapLayer
var source_id: int
var building_vector: Vector2i
var mouse_position: Vector2i
var old_mouse_position: Vector2i
func _ready():
#Ensures no building is shown on the mouse pointer on startup
source_id = -1
#Makes the preview version of the tile the default setting
modulate.a = 0.5
func get_snapped_position(global_pos: Vector2) -> Vector2i:
var local_pos = to_local(global_pos)
var tile_pos = local_to_map(local_pos)
return tile_pos
func _input(event: InputEvent) -> void:
#Creates preview version of building sprite, hovers on mouse position
if event is InputEventMouseMotion:
#Gets the new coordinates of mouse pointer when mouse moves
mouse_position = get_snapped_position(get_global_mouse_position())
#Erases tile in old position, so the building preview 'follows' the mouse
if old_mouse_position != mouse_position:
erase_cell(old_mouse_position)
#Places the building tile onto the grid and stores the new tile coordinates
set_cell(mouse_position, source_id, building_vector)
old_mouse_position = mouse_position
if Input.is_action_just_pressed("click"):
print(mouse_position)
set_cell(mouse_position, source_id, building_vector)
func _on_solar_plant_pressed():
source_id = 0
building_vector = Vector2i(0, 6)
func _on_wind_turbine_pressed():
source_id = 0
building_vector = Vector2i(0, 0)