Path2D: How to get index of a closest baked point from described point
I want to programatically move a player (Kinematic2D) along a path, not from start to end, but starting from a closest point (from player to curve) to end of the path. I refered this article, changed some code & built a test project as shown below: the player moves, but from start to end position.
My test scene:
var move_speed = 100
onready var patrol_path = get_node("../Path2D")
var patrol_index = 0
patrol_points = patrol_path.curve.get_baked_points()
if patrol_index > patrol_points.size() - 1:
var target = patrol_points[patrol_index]
patrol_index += 1
position = target
Actually what I want is that the player should move to a nearest point on the curve & then move until end. I do not know much about Path2D & related stuff, but what I understood is there are 2 arrays; one for the points that we describe in editor to make the shape of the curve (
get_point_count()=55, in my scene) & another is for the points which are baked at 5px (as per the density) interval (
get_baked_points().size()=329, in the same scene).
func get_curve_point_index_from_offset(curve, offset):
var curve_point_length = curve.get_point_count()
if curve_point_length < 2: return curve_point_length
for i in range(1, curve.get_point_count()):
var current_point_offset = curve.get_closest_offset(curve.get_point_position(i))
if current_point_offset > offset: return i
The above code is from From this post This code returns the index of nearest point in the curve, but that point is from the points which we describe in the editor. Using this code, I changed the code accordingly. I got the required result, but as the number of points in this array are small, the movement is finished very fast, which is not acceptable.
If I can get a point in baked/cached points array a smoother effect can be achieved. So my question is how can I get index of PoolVector2Array array from the index I got in described points.