Godot Version
4.4.1.stable
Question
In my current project, I am implementing a feature where you place cargo in a ship. I was able to implement invisible boundaries so the player cannot place too much cargo, but any cargo placed outside of the boundaries just…disappear. My goal is to prevent the cargo tiles from being placed, forcing the player to place then within the boundaries. Video shown below:
My code is below:
extends TileMapLayer
@onready var cargo: TileMapLayer = $"."
@onready var placed_cargo: TileMapLayer = $"../Placed_cargo"
@onready var h_box_container: HBoxContainer = $"../HUD/Panel/HBoxContainer"
var source_id: int
var mouse_position: Vector2i
var old_mouse_position: Vector2i
var cargo_vector = Vector2i(0, 0)
func button_pressed(btn: Button):
match btn.text:
"Coal": cargo_vector = Vector2i(2,2)
"Propane": cargo_vector = Vector2i(0,1)
"Timber": cargo_vector = Vector2i(1,1)
"Apples": cargo_vector = Vector2i(0,2)
"Metal Ingots": cargo_vector = Vector2i(2,1)
"Monitors": cargo_vector = Vector2i(1,2)
Input.set_mouse_mode(Input.MOUSE_MODE_HIDDEN)
source_id = 1
btn.queue_free()
func _input(event):
if event.is_action_pressed("LEFT_CLICK"):
if mouse_position.x > 2 or mouse_position.x < 12 or mouse_position.y == 4:
if placed_cargo.get_cell_atlas_coords(mouse_position) == Vector2i(-1, -1):
Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
placed_cargo.set_cell(local_to_map(get_local_mouse_position()), source_id, cargo_vector)
source_id = -1
cargo_vector = Vector2i(0, 0)
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta: float):
mouse_position = local_to_map(get_local_mouse_position())
set_cell(mouse_position, source_id, cargo_vector)
if old_mouse_position != mouse_position:
erase_cell(old_mouse_position)
old_mouse_position = mouse_position
if mouse_position.x < 2 or mouse_position.x > 12 or mouse_position.y != 4:
source_id = -1
else:
source_id = 1
if placed_cargo.get_cell_atlas_coords(mouse_position) != Vector2i(-1, -1):
modulate = Color.RED
modulate.a = 0.5
else:
modulate = Color.TRANSPARENT
modulate.a = 1