How to make player move only along the line

I am using Line Renderer to draw a line on 2D scene using a path of multiple Transforms. And I want player to move along the line without the ability to get off it, like if he was on a rail. The simplest method I can see is setting a number of invisible walls along the line, so the player couldn't physically move away from the line. But maybe there's better method?

You have a line with a starting point pStart and an end point pEnd.

To get any point on a line, use the linear function equation:

y = m * x + b


Now you have to get the slope of the line which is simply m = (pEnd.x - pStart.x) / (pEnd.y - pStart.y). Then, you can calculate every x and y pair on the line by simply putting in a value for x. So far for the mathematical background, now to the practical implementation (this is all pseudocode).

In your case, you can build a slope vector for the line

slopeX = pEnd.x - pStart.x
slopeY = pEnd.y - pStart.y


and then normalize it (get it to a lenght of one):

slopeLength = squareroot((slopeX * slopeX) + (slopeY * slopeY))
slopeNormX = slopeX / slopeLength
slopeNormY = slopeY / slopeLength


Now you know in which direction you have to move your player each time step. To move him, simply do the following:

playerX += slopeNormX * deltaTime
playerY += slopeNormY * deltaTime


Also, don't forget to check wether the player is still on the line:

playerX*playerX > pEnd.x*pEnd.x && playerY*playerY > pEnd.y*pEnd.y


We have to square the positions here because we don't know wether the coordinates are positive or negative (abs() would be too slow).

Cheers

• Abs is slow. Since we only care which is greater, it should be faster to compare the squares of both numbers (by simple multiplication, not pow). Commented Jan 10, 2018 at 1:08