How do i make the position of my sprite in a path2D be the closest distance to my player node?

Godot Version

Godot Engine v4.4.1.stable.steam.49a5bc7b6

Question

I wanted to makea sprite’s 2D progress in a path2D be such that its distance to the player node be the shortest, for example:
Position 1:


Position 2:

Is there a way for me to do this?

Path2D seems to contain a Curve2D, which has a .get_closest_offset() that probably does what you want.

1 Like

I just tried using this function but it appears the error: Function “get_closest_offset()” not found in base self.

Try:

    curve.get_closest_offset($"../Player".position)

The Path2D contains a Curve2D, but you have to access it directly.

1 Like

It worked! thank you!


(Sorry for the low quality)

1 Like

Hey, now the get_closest_offset won’t detect the player position somehow…


Do you know what could be the problem?
Here’s the PathFollow2D code:

extends PathFollow2D
@onready var player = $"../../Player"
@onready var RailAimSprite = $RailAimSprite
@onready var RailPath = $".."
var initial_offset

func _ready() -> void:
	Pass

func _process(delta: float) -> void:
	print (RailPath.curve.get_closest_offset(player.position))
	progress = RailPath.curve.get_closest_offset(player.position)

You have a bunch of warnings printing (see the red text at the bottom of the window), I wonder if something isn’t hooking up? You might want to check that RailPath and player are properly initialized.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.