Drag to create and set size of a rectangle

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

How can I achieve a drag and create rectangle like In a paint application where a user can press down mouse button and drag to set the size as per needed ? I want to achieve this using code and by not instancing scenes containing the shape.

:bust_in_silhouette: Reply From: Thomas Karcher

See paragraph “Drawing the box” in https://kidscancode.org/godot_recipes/input/multi_unit_select/

(Just omit the “if dragging” line in the draw function to prevent the rectangle from vanishing when releasing the mouse button)

Thanks for the help, this works but as soon as a second rectangle is drawn the first vanishes, how do I store the previous shape ?

shreyk27 | 2021-04-08 03:17

you could maybe store the rectangles (Rect2D’s maybe) in an array, and loop through them in _draw to draw them. Quickly looking at CanvasItem — Godot Engine (stable) documentation in English I couldn’t see an option to not clear the drawing, but I may have overlooked something. Also, only add the rect2 to the array on mouse released

1234ab | 2021-04-08 07:11

As mentioned by 1234ab in the other comment: You’ll need to save and redraw all previous rectangles for that:

extends Control

var mouse_pos = Vector2()
var dragging = false
var drag_start = Vector2.ZERO

var rectangles := []

func _unhandled_input(event):
	if event is InputEventMouseButton and event.button_index == BUTTON_LEFT:
		if event.pressed:
			dragging = true
			drag_start = event.position
			rectangles.push_front(Rect2(drag_start, Vector2.ZERO))
		elif dragging:
			dragging = false

	if event is InputEventMouseMotion and dragging:
		rectangles[0] = Rect2(drag_start, get_global_mouse_position() - drag_start)

func _draw():
	for r in rectangles:
		draw_rect(r, Color(.5,.5,.5), false)

Thomas Karcher | 2021-04-08 09:22