Repository
Time-Based Pathing
Overview
An interesting challenge that I’ve come across is one that seems simple, but is actually much more complex under the surface is time-based pathing. Imagine this: you have an NPC that has a specific schedule and needs to be at certain places at certain times, how would you handle that? What if time can be reversed? Or sped up? How would you make sure that the NPC is at the right part of their path at the right time at the right speed?
“The Legend of Zelda: Majora’s Mask” is a good example of this in practice. Time can be reversed, sped up, and slowed down, with NPC’s depending on this time.
Even without time-manipulation, this concept is important in the context of Unity games. Like other engines, GameObjects within a scene are instanced when the scene loads. So if there is some form of global time NPC’s depend on, this concept will still be important to make sure they are on the right part of their path when loading into a scene.
So how do we solve it?
The Solution
The solution to the problem, is this scary looking formula:
This is a piecewise function that defines the point q for all possible segments in the path. This function covers all possible values of l (and therefore t). It works by determining which segment the NPC is on at time t and then linearly interpolating between the endpoints of that segment to find the exact position of the NPC.
While this is obviously pretty scary looking, it’s easier to understand in code.
This function will return a point on a line (defined by Vector3 points in the NPCPath object) based on the current time. If this function runs every single frame, it will properly move the NPC along the path.