Weird behavior when drawing rect

Godot Version

Godot Engine v4.3.stable.official

Question

I’m trying to draw some rectangles stacked together but Godot is giving me some weird behaviors.

I have two gd scripts.

parent.gd

extends Node2D
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	position = Vector2(10, 10)
	for i in range(4):
		add_child(Child.new(Vector2(0, i * 40)))

child.gd

class_name Child extends Node2D

func _init(p_position) -> void:
	position = p_position

func _draw() -> void:
	draw_rect(Rect2(position, Vector2(40, 40)), Color.BEIGE, false)

My scene is just one Parent node that has the parent.gd script attached

What I expect to have:
image

What I got after running the code:
image

I also noticed that if I set the position of the 2nd child manually in the remote mode, it stacks it right below the first rectangle.

but then if I click the visible checkbox off and on again. the rectangle goes to the correct location (0, 0), same location as the first rect.

I’m new to Godot, but I am an experienced programmer (not with game dev). I had no idea what was going on here and how I could draw my rectangles correctly. In the end, I might have thousands of rectangles so they need to be instantiated with the script.

The reason is you are moving your rectangle in your initializer:

by setting the position property.
But then you Offset the drawing of the Rect2 by the position again, which leads to it being drawn away twice the amount that you actually want.

To fix that write this:

func _draw() -> void:
	draw_rect(Rect2(Vector2(0, 0), Vector2(40, 40)), Color.BEIGE, false)
1 Like

It all makes sense now. I should not have used the rectangle position as the drawing position, because the drawing position is relative to the position of the rectangle I’ve set.

Thank you so much @herrspaten !

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.