Duplicate blocks spawning on each other

Godot Version

Godot 4.5.1

Question

Hey guys, i’m new to godot, so i don’t understand the innerworkings of the engine.

I’ve tried to make a simple project, where the view is separated into 36x36 squares and in whichever square the cursor is, it gets colored in (A static body is put there).

I accomplished this by moving a Area2D “Check“ into the square and checking if there is a static body already there and if there is not, i spawn one

I think that there is an simpler way, however, i drifted off to fixing a problem of multiple static bodies spawning on top of eachother.

I just don’t understand why it keeps happening, cause before a new check occurs, the new static body should already be there.

Could you please explain to me why it keeps happening?

main_scene.tscn

  • Node2D
    • Check (Area2D)
      • CollisionShape2D

square.tscn

  • Square (StaticBody2D)
    • Polygon2D
    • CollisionShape2D

game.gd on Node2D

extends Node2D

func _process(_delta: float) -> void:
	print(get_child_count())
	var vec = floor(get_viewport().get_mouse_position() / 36)
	if vec.x < 0 or vec.x > 31 or vec.y < 0 or vec.y > 17:
		return
	vec *= 36
	%Check.global_position = vec
	if len(%Check.get_overlapping_bodies()) == 0:
		var sqr = preload("res://square.tscn").instantiate()
		sqr.global_position = vec
		add_child(sqr)

The code naturally does what you tell it to, and not what you thing it’s ought to be doing. Identify the point where it deviates from your intent. A Square should already be there, but the if() check passes anyway. This means get_overlapping_bodies() does not detect the Square when you expect it to, right? With this, go to the get_overlapping_bodies documentation and see what might be causing that. There is one possible, likely reason written there. Then you google. Then, if that still doesn’t help, you come to the forum. At least by the time you already understand the problem enough to name the topic and ask the right questions. That is how it works for most of us.

You explained nothing to me but still thank you

I figured it out

I used _physics_process instead and tweaked it a bit