- Home /
How to find % along path between N points
When the Move() function is activated, the player runs from "start" to "end" while hitting each point in 3d space along the way. IE, he auto runs from point to point until he reaches the end.
These points are Vector3 world positions: Player movement works fine.
What I need to do is figure out the percentage along this path the player is at every frame and feed that value into a Lerp which is driving my camera - so the value should be between 0 and 1
The total distance of the path is easy, lets say it's: float totalDist = 100.0f;
I could find "percentDist" with: percentDist = currentDist / totalDist;
problem with this method:
I'm not sure how to accurately/efficiently find currentDist every frame
I've been at this for 3 days now which tells me there's probably a wicked easy solution I'm missing. Any ideas?
Answer by Nebukam · Dec 04, 2018 at 06:24 AM
Easiest solution : Go with a Catmull Rom spline equation, which will give you a super smooth camera movement. If you don't have time to go through the concept, just use the life saving Unity 3D Math classes by Bit Barrel Media. You're looking for the method GetPointOnSpline Important note : there's a catch with the Catmull Rom equation, you'll need an extra point at the beginning and end of the spline for correct calculations, but you can easily work around that :)
Googling a bit will lead you to this implementation with a few more utility functions for tangents etc.
Happy coding !
Thanks for your reply, this looks interesting, I'm excited to look into it some more, unfortunately on the surface im not sure this answers the question..
The camera does not follow the path here, only the player does. When $$anonymous$$ove() is called, the camera lerps from "where ever it currently is", back to the end point: the time this transition takes should be the time it takes the player to move from start to end. (The player can move the camera independently from the player, but on $$anonymous$$ove(), the camera needs to reset itself)
Answer by hexagonius · Dec 04, 2018 at 06:35 AM
One: you're not dividing by zero. you're dividing zero by distance, which is fine
Two: solved by one
Three: run a loop through your directions. divide each ones magnitude by the total distance. modulor that with your current percentage. if the result is 0, multiply the current distance to the already moved distance (if none, start with adding to the start position). if the result is larger than that, add the full direction and subtract it's percentage from the total and repeat with the next.
if course this can be rewritten with incremental steps so you don't have to run through all directions all the time.
Yeah good point, I'm not sure where the divide by zero error was co$$anonymous$$g from... Edited
Having a hard time understanding your answer for issue three but thinking about these line segments as magnitudes gives me another idea