Build a trail that follows mouse click until mouse is released

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

I am trying to build a trail follows the mouse only while the player is clicking a button. So far I have followed another tutorial and i’m only able to make one that follows the mouse, even when it is not being clicked. Can you help me make it so that the trail is only visible when the mouse is clicked?

I have a Node2D with a Line2D as a child.

The Node2D has script:

extends Node2D

# Called when the node enters the scene tree for the first time.
func _ready():
	global_position = get_global_mouse_position()

Node2D’s child Line2D has script:

extends Line2D

var length = 5
var point = Vector2()

func _process(delta):
	global_position = Vector2(0,0)
	global_rotation = 0
	point = get_parent().global_position
	add_point(point)
	while get_point_count() > length:
		remove_point(0)

I have tried adding a statement if Input.is_action_just_pressed("click"): to func _process(delta):, but the trail doesn’t even show up when I add that.

Thanks for your help. I’m new to Godot and this is really challenging for me!

:bust_in_silhouette: Reply From: jgodfrey

Really, something as simple as this should work with just a single Line2D node:

extends Line2D

var length = 5

func _process(delta):
	if Input.is_action_pressed("click"):
		add_point(get_global_mouse_position())
		while get_point_count() > length:
			remove_point(0)

That assumes you’ve added a click input (via Project | Project Settings | Input Map and connected it to the left-mouse button…

that works! Thank you! But the line still stays up on screen when i release the mouse. Do I need to add a que_free() anywhere to get rid of that?

miss_bisque | 2020-11-15 02:22

what I mean by that is: the line only disappears once the while statement is finished counting. Is there some logic I can add in that stops the trail once the mouse button is released?

miss_bisque | 2020-11-15 02:28

You can just clear the points when the click action is released. So, change the function to this:

func _process(delta):
	if Input.is_action_pressed("click"):
		add_point(get_global_mouse_position())
		while get_point_count() > length:
			remove_point(0)
	if Input.is_action_just_released("click"):
		clear_points()

jgodfrey | 2020-11-15 02:40

Ah, that clear_points command is just what I was looking for. Thank you

miss_bisque | 2020-11-15 02:42