Bug in selection box

Godot Version



Hello everybody. I am trying to make a selection script(2d) for units for my game but i have been running into a bug and i don’t know how to fix it.
I have been following this tutorial: https://www.youtube.com/watch?v=FRHwG-84tgE to make a selection box and select the selectable object.

This is the whole code for it:

extends ColorRect

var mouse_down : bool
var mouse_start_pos : Vector2
var mouse_end_pos : Vector2
var nodes_in_rect =

signal _units_selected

func _input(event):
if event is InputEventMouseButton:
if event.button_index == 1 and event.is_pressed():
if !mouse_down:
nodes_in_rect =
mouse_down = true
mouse_start_pos = event.global_position
global_position = mouse_start_pos
elif !event.is_pressed():
if mouse_down:
mouse_down = false
mouse_end_pos = event.global_position
size = Vector2.ZERO

if event is InputEventMouseMotion:
	if mouse_down:

func _update():
if get_global_mouse_position().x < mouse_start_pos.x:
scale.x = -1
elif get_global_mouse_position().x > mouse_start_pos.x:
scale.x = 1
if get_global_mouse_position().y < mouse_start_pos.y:
scale.y = -1
elif get_global_mouse_position().y > mouse_start_pos.y:
scale.y = 1

# Size of the recta
size = (get_global_mouse_position() - mouse_start_pos) * scale

func _get_top_left_corner():
var x = mouse_start_pos.x if mouse_start_pos.x <= mouse_end_pos.x else mouse_end_pos.x
var y = mouse_start_pos.y if mouse_start_pos.y <= mouse_end_pos.y else mouse_end_pos.y

func pressed_ended():
# get all nodes inside the rect
var nodes_to_get = get_tree().get_nodes_in_group(“selectable”)
var top_left_corner = _get_top_left_corner()
var search_field : Rect2 = Rect2(top_left_corner.x, top_left_corner.y, abs(size.x), abs(size.y))

if nodes_to_get != null:
	for node in nodes_to_get:
		if search_field.has_point(node.global_position):
			#Sends the array as signal to main control
			emit_signal("_units_selected", nodes_in_rect)

The problem i have now is that the selection box does not work the first time you use it. If I draw the selection box from the bottom left → and up, it doesn’t select my object. If i do it a second time it does.
It always works if i draw the box from the top left-> down.