I am currently facing a problem I cannot wrap my head around. In my 2D game which in the end should become some kind of virtual model railway, I can create a path, consisting of different railtypes. Each rail has it's own waypoints. Now the issue is as follows:
Straight rails don't need many waypoints, since they only need two to be defined; The start and the end point. Curves on the other hand need a lot more waypoints, so the objects movement on them is not all jaggy and unsmooth. The problem I am facing is, that the waypoints then are so unevenly distributed on the whole railway, it makes the speed which the object moves along the path very uneven.
I also already know the issue: The points are so cramped in the curve sections that the distribution looks like this:
See this picture for an example with red Gizmo.Spheres as waypoints
Now when I move an object along that said path, I do it like this:
wagon.transform.position = Vector2.MoveTowards(wagon.transform.position, wagon.GetNextPosition(), wagon.GetSpeed());
The third parameter of the method Vector2.MoveTowards() is the maxDistanceDelta, so it can only move that amount into the direction of wagon.GetNextPosition(), which is constantly updated.
The twist is, that the densly packed points result in a way shorter distance than the maxDistanceDelta. So in those parts of the railway, the object moves way slower then wagon.GetSpeed() per frame.
I already have a solution to this, which sadly I cannot use: I took every waypoint and distributed them evenly on the path. I don't want that; I want the path to stay as is, but the speed to the eye to be uniform.
Thanks in advance for your help!
PS: I already looked in similar threads, but none of those solutions seems to work for me :( Namely:
CodePudding user response:
I would comment this but unfortunately I don't have enough reputation, so here it is:
The best idea I can think of is to create 2 waypoints for your curve (at the start and finish) and use a parabolic function to define the movement between them. So in other words, your train follows a parabola instead of moving towards waypoints directly.
I found a useful answer on a unity forum about parabolic trajectories which you may find useful for your project (It is the first answer beneath the question at the time of writing).
CodePudding user response:
How are you generating those waypoints? Could you use bezier curves instead? If yes, there it's typical to run into exactly this issue and solutions have been found. Not solutions with absolute accuracy, but usually sufficient for games (aka visualizations that in the end only need to be as accurate as the pixels you see).
There is this awesome video about the topic: https://www.youtube.com/watch?v=aVwxzDHniEw