+1 vote

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!

in Engine by (45 points)

1 Answer

0 votes
Best answer

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...

by (10,932 points)
selected by

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?

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?

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()

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

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 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 webmaster@godotengine.org with your username.