Friday, July 27, 2018

javascript - Get points on a line between two points



I'm making a simple space game in JavaScript, but now I've hit a wall regarding vectors.


The game view is top-down on a 2d grid. When the user clicks on the grid, the space ship will fly to that spot.


So, if I have two sets of points:


{ x : 100.2, y : 100.6 }; // the ship
{ x : 20.5, y : 55.95 }; // the clicked coordinates

If the game loop ticks at 60 iterations per second, and the desired ship velocity is 0.05 points per tick (3 points per second), how do I calculate the new set of coordinates for the ship for each tick of the game loop?


p.s. I do not want to account for inertia, or multiple vectors affecting the ship, I just want the ship to stop whatever it is doing (i.e. flying one way) and move to the clicked coordinates at a static speed.



Answer



In Pseudocode:



speed_per_tick = 0.05
delta_x = x_goal - x_current
delta_y = y_goal - y_current
goal_dist = sqrt( (delta_x * delta_x) + (delta_y * delta_y) )
if (dist > speed_per_tick)
{
ratio = speed_per_tick / goal_dist
x_move = ratio * delta_x
y_move = ratio * delta_y
new_x_pos = x_move + x_current

new_y_pos = y_move + y_current
}
else
{
new_x_pos = x_goal
new_y_pos = y_goal
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...