4.3 Godot Version
Hey there! New to Godot!
I want to make a 2d top-down building game.
I am trying to script a building system where i can build on the floor but not on the player/walls/resources or already built structures.
When i press “B” i managed to switch into a grid view where the mouse locations highlights a 32x32 square green (if the space is free and its possible to build) and switches to red (if its not possible to build because the space is already occupied). This works perfectly for my Player and for my walls. but for some reason, it does not work on my structures and i can’t figure why.
My grid is on layer 1 mask 2
My player is on layer 1 mask 1
My walls are in layer 1 mask 1
My build structures and resources are on layer 2 mask 1 and 2
When i mouse over my structures and ressources, the collision is not detected at all.
heres the script
extends Node2D
var cell_size = 32 # Size of each grid cell
var highlight_position = Vector2.ZERO
var grid_visible = false
var can_place = true
@onready var area_2d = $Area2D
@onready var color_rect = $ColorRect
func _ready():
color_rect.visible = false
# Configure Area2D collision properties
area_2d.collision_layer = 1 # Area2D belongs to layer 1
area_2d.collision_mask = 3 # Area2D detects layers 1 and 2 (binary OR of layers 1 and 2)
func _process(_delta):
if grid_visible:
# Get mouse position relative to the grid’s position
var mouse_position = get_global_mouse_position() - self.global_position
# Snap the mouse position to the nearest grid cell
var grid_x = floor(mouse_position.x / cell_size) * cell_size
var grid_y = floor(mouse_position.y / cell_size) * cell_size
# Update the highlight position
highlight_position = Vector2(grid_x, grid_y)
# Update the positions of the ColorRect and Area2D
color_rect.position = highlight_position
area_2d.position = highlight_position
# Update highlight color
update_can_place()
if can_place:
color_rect.color = Color(0, 1, 0, 0.5) # Green (can place)
else:
color_rect.color = Color(1, 0, 0, 0.5) # Red (cannot place)
func _input(event):
if event.is_action_pressed(“toggle_building”):
grid_visible = not grid_visible
color_rect.visible = grid_visible
func update_can_place():
# Get overlapping bodies from Area2D
var overlapping_bodies = area_2d.get_overlapping_bodies()
can_place = true # Assume placement is valid unless proven otherwise
for body in overlapping_bodies:
print("Overlapping with:", body.name, "Groups:", body.get_groups())
# Check if the body belongs to invalid groups
if body.is_in_group("Ressources") or body.is_in_group("Structures") or body.is_in_group("Player") or body.is_in_group("Environment"):
can_place = false
print("Cannot place due to overlap with:", body.name)