Skip to content

Instantly share code, notes, and snippets.

@saward
Last active July 15, 2022 05:46
Show Gist options
  • Save saward/2e14ec0f4744834e366d436f7c3a8420 to your computer and use it in GitHub Desktop.
Save saward/2e14ec0f4744834e366d436f7c3a8420 to your computer and use it in GitHub Desktop.
Example of Godot path movement using recursion
# MIT licenced. Feel free to use in your project.
# Use recursion to move along path. We move along path, and if there's any
# distance remaining, we call this function again and move further along until
# we reach our destination or there's no distance left to travel
func move_along_path(distance : float) -> void:
# Ensure we have an actual path, otherwise we are done and can stop
# processing
if path.size() == 0:
set_process(false)
return
# If there's no distance available to travel, then nothing to do for this
# tick
if distance <= 0.0:
return
# Check how far until the next point
var distance_to_next_point : = position.distance_to(path[0])
# Assuming there's some distance left to go, let's move it
if distance_to_next_point > 0.0:
# Use the min of distance and distance_to_next_point so that we don't
# overshoot our destination when distance > distance_to_next_point
position = position.linear_interpolate(path[0], min(distance, distance_to_next_point) / distance_to_next_point)
# If this condition is met, we must have reached destination, so remove point
if distance >= distance_to_next_point:
path.remove(0)
# Subtract the amount we used up before moving further along the path. If
# there is no distance left, the next call will check this at the start
# and return
move_along_path(distance - distance_to_next_point)
@hadisajjadi
Copy link

great work. thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment