Hi everyone. I have a node (a car, kinematic body) which I use for the player but would like to translate the same physics to an NPC version. I've made it follow a Path2D using an offset but would like to have it follow the path using the physics in it's own code if possible.

The code is based on this tutorial: http://kidscancode.org/godot_recipes/2d/car_steering/

Could anyone help? Thank you :)

a month later

So, acceleration would be a constant instead of an input and the steering might be computed by the angle to the next path point?

You could calculate the distance from the car to the point on the Path2D, and then use that as the velocity in a move_and_slide function call. I'm not 100% sure it would work, and you'd need to move the point on the Path2D forward as the car gets closer, but it might be something to look into?

In theory, it would look something like this (untested, pseudo-ish code):

extends KinematicBody2D

const SPEED = 200
const DISTANCE_TO_MOVE_POINT = 100

var velocity = Vector2.ZERO

func _process(delta):
	var path_point = get_node("PathFollow2D").global_position
	var vector_to_path = path_point - global_position
	
	if (vector_to_path.length() <= DISTANCE_TO_MOVE_POINT ):
		# move the path follow 2D node down the path by a little bit
		get_node("PathFollow2D").offset += 20
	
	velocity = vector_to_path.normalized() * SPEED
	velocity = move_and_slide(velocity, Vector2.UP)
2 years later