How to draw a dotted / dashed line ?

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

Given initial and final Vector2( ) position, How can a dotted / dashed line be drawn ?

:bust_in_silhouette: Reply From: miskotam

Unfortunately, there is no built-in function for that in Godot yet. You must implement it yourself.

Here is one example I found which might helps you to start with it:
https://github.com/juddrgledhill/godot-dashed-line

There is a built-in way to achieve this with Godot using the Line2D node, but you need to supply your own dashed/dotted line texture.

Calinou | 2020-10-06 20:18

:bust_in_silhouette: Reply From: IHate

You can use draw_multiline() and save positions from a point to another.

You can see how it works in this video:
In the video the dotted line follows a sine.

min: 13:20

:bust_in_silhouette: Reply From: GrayDwarf

In 3.4.2+, you can use Line2D (add at least two points) and then specify a Texture and set ‘Texture Mode’ to ‘Tile’. Super easy and works really well. You can even drag the ends around in your editor.

As for what to use for the texture, here’s a an example: Make a png that is 16x4. Make it gray on the left half and then transparent on the right. Save and reference this as your Texture. Make sure to import your texture with Repeat. You can then play with other settings like Width and Self_Modulate.

Here’s a gdscript example if you want to do it from code instead. node1 and node2 are two existing objects in the scene that I want to draw a dashed line between.

var line = Line2D.new()
line.texture = load("res://assets/map/dotted-line.png")
line.texture_mode = Line2D.LINE_TEXTURE_TILE
var poolVectorArray : PoolVector2Array = []
poolVectorArray.append(node1.position)
poolVectorArray.append(node2.position)
line.points = poolVectorArray
add_child(line)

P.S. If you want to do a dotted line, just change your texture so half is a filled circle and the other half is transparent.

Make sure to import your texture with Repeat enabled for it to work.

Poobslag | 2022-08-31 14:19

@Poobslag Ah, updated the verbiage to include that. Thanks for calling it out!

GrayDwarf | 2022-08-31 15:01

:bust_in_silhouette: Reply From: domo106

draw_dashed_line() was added in 4.x

:bust_in_silhouette: Reply From: mingganglee

This is the project I wrote, hope he can help you.