Tyre marks connecting after drifting (Line2D), how to fix?

extends Line2D

var point
var trail_duration = 3.0
var time_since_drift = 0.0

func _ready():
top_level = true

func _physics_process(delta):
if Input.is_action_pressed(“drift”):
point = get_parent().global_position
add_point(point)
time_since_drift = 0.0
if points.size() > 80:
remove_point(0)
else:
time_since_drift += delta
if time_since_drift > trail_duration:
while points.size() > 0:
remove_point(0)

Above is my script for my Line2D that leaves tyre marks when i drift in my 2d top down car game. But i have a problem with the tyre marks connecting when i stop, then start drifting again. It adds a straight line between the old tyre marks and the new tyre marks, which i don’t want.
Any suggestions to a solution is much appreciated! :smiley:

As far as I know, a Line2D can only have one line.
You need to rethink the system for your tire marks.

Your new system must be capable of instantiating “tire mark” objects that are started/stopped by the vehicle in question (i.e. when you press/release your drift-input).

Solution

Here’s a template for your “trail-spawner” object:

Trail Spawner Code
extends Node2D

var trailScene = preload(#insert path to trail scene here)
var currentTrail: Line2D

func _process(delta):
    if Input.is_action_just_pressed("drift"):
        currentTrail = trailScene.instantiate()
        get_parent().add_child(currentTrail)
        currentTrail.start()
    if Input.is_action_just_released("drift"):
        currentTrail.stop()

And your tire mark prefab (packed scene):

New Tire Mark Code
extends Line2D

@export var trail_duration = 3.0
var isStarted = false
var startTime = 0
# I haven't used get/set before in GDScript but
# it looks like this is how you do it.
var time_since_start: float:
    get: return (Time.get_ticks_msec() - startTime) / 1000.0

func _ready():
    top_level = true

func _physics_process(delta):
    if isStarted:
        point = get_parent().global_position
        add_point(point)
        if points.size() > 80:
            remove_point(0)
    else:
        # Alternatively, you could modify the code to delete the trail
        # x seconds after the trail has stopped (instead of after it is started)
        if time_since_start > trail_duration:
            queue_free()

func start():
    isStarted = true
    startTime = Time.get_ticks_msec()  # Timestamp for when the trail was started
func stop():
    isStarted = false

Disclaimer: I haven’t tested the code myself, but it should work.