I’m currently trying to create a system where the camera follows the player along a path. Basically I have created a 3D path using Itween where the camera should find the closest point towards the player along that path and stick to it. How could this be done? I was able to make the camera stick to a porcentage of the path but have no idea how to make that porcentage be equal to the closes point towards the player.
This page lists a function called PointOnPath which essentially gives you a parametric equation describing that path.
What you can do using this is sample the path at multiple parts, and keep track of the distance that is the minimum. (This is pseudocode because I don’t know how paths are structured in iTween.)
float minDistance = float.PositiveInfinity;
float minPercent = 0;
for (float t = 0; t <= 1; t += 0.02f) {
float dist = Vector3.Distance(playerPosition, PointOnPath(/* path */, t));
if (dist < minDistance) {
minDistance = dist;
minPercent = t;
}
}
This will give you an approximation of the closest distance and the percent along the path that corresponds to it. For most purposes, an approximation like this should be good enough.
Modifying @_Gkxd 's answer, you can use a (much much much much) more optimized version of it as follows:
for (float t = 0; t <= 1; t += 0.005f) {
float dist = (Player.transform.position - iTween.PointOnPath (iTweenPath.GetPath("CameraPath" ), t)).sqrMagnitude;
if (dist < minDistance) {
minDistance = dist;
minPercent = t;
}
}
I’m using sqrMagnitude here because we’re just comparing distances, and we don’t actually need the actual distance so we can avoid the expensive Sqrt operation which @_Gkxd was performing 20 times (you were doing it 1000 times!!!) every frame in his code - of course it’ll be laggy! You might have noticed I’ve also increased the step value in the loop to 0.005, which depending on the length of your path can be increased more. If it is a long path, you don’t need a high step value, but if it’s a short one, you might want to keep a smaller step.