KinematicBody2D slows down when using move_and_slide()

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

Hi there,

I tried the pathfinding tutorial from GDQuest ( 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:
func _physics_process(delta: float) -> void:
	var moveDistance : = speed * delta
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)
		elif distance < 0.0:
			position = path[0]
		distance -= distanceToNext
		startPoint = path[0]
func setPath(value: PoolVector2Array) -> void:
	path = value
	if value.size() == 0:
:bust_in_silhouette: Reply From: deaton64

I’ve no idea, maybe it’s the loop, but I based mine on Kids can code example.
Works fine for me.

:bust_in_silhouette: Reply From: p7f

You are not using move_and_slide as its supposed to be used.
move_and_slide function needs a velocity as parameter, and you are giving a distance. That distance will be interpreted by the engine as the velocity you should have passed instead.

If you want the body move to a constant speed, so pass a constant velocity to move and slide. You can take the direction with:

var direction = startPoint.direction_to(path[0])

and then use that direction, with a given constant speed variable you should define before, to get a velocity

var velocity = direction * speed

And finaly pass velocity to move and slide instead of a distance.

Thank you very much, know it works fine :slight_smile:

Droggelbecher | 2020-09-06 17:19

glad to help!

p7f | 2020-09-06 17:23