Why does the draw_rect follow the mouse position?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Isccb

I’m trying to do a drag-select with the mouse, but when I draw the rectangle, it’s associated with the mouse position and moves along with it, instead of staying fixed in the initial position.

var dragging = false  # Are we currently dragging?
var drag_start = Vector2.ZERO  # Location where drag began.

func _unhandled_input(event):
	if  event.is_action_pressed("mb_left"):
		if event.pressed:
			dragging = true
			drag_start = event.position

	if event is InputEventMouseMotion and dragging:
		queue_redraw()
	
	if event.is_action_released("mb_left"):
		dragging = false

func _draw():
	if dragging:
		draw_rect(Rect2(drag_start, size), Color.WHITE, true)

If I draw a rectangle at position (0,0), it appears at the tip of the mouse instead of at position (0,0) on the map.

How / where are you setting size?

jgodfrey | 2023-06-23 17:57

:bust_in_silhouette: Reply From: jgodfrey

This seems to work as I’d expect (again, adding the size variable):

var dragging = false  # Are we currently dragging?
var drag_start = Vector2.ZERO  # Location where drag began.
var size

func _unhandled_input(event):
	if  event.is_action_pressed("mb_left"):
		if event.pressed:
			dragging = true
			drag_start = event.position

	if event is InputEventMouseMotion and dragging:
		size = event.position - drag_start
		queue_redraw()

	if event.is_action_released("mb_left"):
		dragging = false

func _draw():
	if dragging:
		draw_rect(Rect2(drag_start, size), Color.WHITE, true)

And, depending on the needs, maybe a slight modification to the _draw() function…

Rectangle outline only so enclosed objects aren’t hidden:

func _draw():
	if dragging:
		draw_rect(Rect2(drag_start, size), Color.WHITE, false, 3)

Filled rectangle, but with some transparency so enclosed objects aren’t completely hidden:

func _draw():
	if dragging:
		draw_rect(Rect2(drag_start, size), Color(Color.WHITE, 0.5), false, 3)

jgodfrey | 2023-06-23 19:36