0 votes

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.

in Engine by (44 points)
edited by

1 Answer

0 votes
Best answer

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)

by (1,750 points)
selected by

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 ?

you could maybe store the rectangles (Rect2D's maybe) in an array, and loop through them in _draw to draw them. Quickly looking at https://docs.godotengine.org/en/stable/classes/class_canvasitem.html 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

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)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.