Let's say that I have the coordinates of a line (25,35 45,65, 30,85 - It would be a two part line). I need to move a point (car) along that line at a constant distance every frame. How can I do this?
Hey, so you have the coordinates (25,35) (45,65) (30,85) for your 2 lines, The point you want to move is going to be placed at the first of these coordinates (25,35) and you want it to move towards the second coordinate (45,65) (the end of the first line segment).
The first step is to get the orientation in which the point is going to move, the orientation is the angle between the point position and the target position. To find this angle you can use the Math.atan2()
, passing in as the first argument the target position Y - the point position Y
, and as the second argument the target position X - the point position X
.
var Point = {X: 25, Y: 35};
var Target = {X:45, Y:65};
var Angle = Math.atan2(Target.Y - Point.Y, Target.X - Point.X);
Now get the Sine and Cosine of that angle, the Sine is the value to move along the Y axis, and the Cosine is how much to move on the X axis. Multiply the sine and cosine by the distance you want to move each frame.
var Per_Frame_Distance = 2;
var Sin = Math.sin(Angle) * Per_Frame_Distance;
var Cos = Math.cos(Angle) * Per_Frame_Distance;
Ok, what is left do to now is just setup the redraw method where you add the sine to the point's Y position and the cosine to the point's X position at each call. Check if the point has arrived to it's destination then do the same process to move towards the end of the second line segment.