How to draw a line in 2D?

in Engine

The CanvasItem node has the function draw_line(...). Add a CanvasItem node to your project and attach a script with this code added to it:

func _draw():
draw_line(Vector2(0,0), Vector2(50, 50), Color(255, 0, 0), 1)

This creates a red diagonal line in the top-left corner. Note that draw_line(...) function must be put in the _draw() function. To call the _draw() function again, call update().

by (156 points)
selected by

by (429 points)

oh, dont see the answer above :)

Function _draw() is executed only once. How to make the function run forever?

by (345 points)

function _draw() is executed *automatically* only once. It is then executed whenever the node calls update(). If you want _draw() to be called forever, then do the following:

1. In ready(), add the line "set_process(true)". This line will allow you to do something every iteration of the game loop.
2. Add function _process(delta). This is the function that is called for every iteration of the game loop. In this function, add "update()"

In summary:

extends Area2D

set_process(true)

func _process(delta):
update()

func _draw():
draw_line(Vector2(0,0), Vector2(50, 50), Color(255, 0, 0), 1)

Thanks. Now I try to draw a curved line on the coordinates of the list ...

Add update() at the end of func _draw()

Solved

var draw_list = []

set_fixed_process(true)
set_process(true)
draw_list = [Vector2(0, 0), Vector2(250, 10), Vector2(50, 300), Vector2(500, 500)]

func _fixed_process(delta):
pass

func _process(delta):
update()

func _draw():
if draw_list != []:
var temp_draw_list = []
for ob in draw_list:
temp_draw_list.append(ob)
if temp_draw_list != []:
if temp_draw_list != draw_list:
draw_line(temp_draw_list[temp_draw_list.size()-1], draw_list[temp_draw_list.size()], Color(1.0, 1.0, 0.5, 1.0), 3)
print(ob)
by (345 points)
edited by

A Line2D node type was added in 3.0

https://docs.godotengine.org/en/3.1/classes/class_line2d.html

In the example below \$MyLine is a reference to a Line2D on my scene. from and to are Vector2D:

func createLine(from, to):