How to Draw several lines between points dynamically

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

I have few points like area2d. I would like to draw lines dynamically by mouse click. How to do that?

:bust_in_silhouette: Reply From: TTF DPC

Try this:

extends Node2D # important: Use CanvasItem!
class_name LineDrawer #create class
var line: Line2D

func _process(delta):


    if Input.is_action_just_pressed("click"): # check for click
        click()
    if Input.is_action_just_pressed("right_click"):
        delete_points()
func click(): 
    line.add_point(get_global_mouse_position()) #create a Line2D point on mouse position
func delete_points():
    line.clear_points()

And you need a script to create the class

   extends Node2D

var f = LineDrawer.new()

func _ready():
    var l = LineDrawer.new()
    l.line = $Line2D
    add_child(l)

I hope, I could help you

make sure that you use local coords for line2d!

so it would be:

func click(): 
    line.add_point(to_local(get_global_mouse_position()))

scrubswithnosleeves | 2021-05-18 18:25

You´re right. That´s better.

TTF DPC | 2021-05-19 09:21