Hi there,
I tried the pathfinding tutorial from GDQuest (https://www.youtube.com/watch?v=0fPOt0Jw52s) and came across a problem. The script works perfectly with sprites, but I wanted to use it with KinematicBody2D instead.
The sprite position got updated with position = startPoint.linear_interpolate(path[0], distance / distanceToNext)
, which doesn't work with a KinematicBody2D. I replaced that line with move_and_slide(path[0] - startPoint)
instead.
The script works on its own, but the KinematicBody's speed keeps decreasing as the path contains curves and the KinematicBody changes direction. Is there a way to make sure that the KinematicBody will move with constant speed, regardless of the path? I got a bit confused how the movement here works.
The moveAlongPath function is the main part of the pathfinding tutorial. The path variable is calculated by the simple_path function in another script.
extends KinematicBody2D
var speed := 400.0
var path : = PoolVector2Array() setget setPath
func _ready() -> void:
set_physics_process(false)
func _physics_process(delta: float) -> void:
var moveDistance : = speed * delta
moveAlongPath(moveDistance)
func moveAlongPath(distance: float) -> void:
var startPoint := position
for i in range (path.size()):
var distanceToNext := startPoint.distance_to(path[0])
if distance <= distanceToNext and distance >= 0.0:
move_and_slide(path[0] - startPoint)
break
elif distance < 0.0:
position = path[0]
set_process(false)
break
distance -= distanceToNext
startPoint = path[0]
path.remove(0)
func setPath(value: PoolVector2Array) -> void:
path = value
if value.size() == 0:
return
set_physics_process(true)