Skip to content Skip to sidebar Skip to footer

How Can You Find The Coordinates Between Two Given Points On A Straight Line(javascript)?

I want to get all the x,y,z coordinates between 2 given points, on a straight line. I need to be able to do this in JavaScript for checking whether a projectile collides in my game

Solution 1:

Your current approach will need to deal with quadrants in 2D and octants in 3D which is pain in the ass. if you use DDA instead (which is very similar) you will get rid of that. So:

P(t) = P0 + t*(P1-P0)
t=<0.0,1.0

This is also called Linear Interpolation. As there are infinite number of points P(t) between your two endpoints P0,P1 I assume you want just integer ones (representing PIXELS) so you need to select t with single "pixel" step and round or floor the coordinates of P(t). That is simple:

dP = abs(P1-P0)
dt = 1.0/max(dP.x,dP.y,dP.z)

this is called line rasterization and can be also ported to integer arithmetics without the need for floats. The ported version looks like this:

dP =abs(P1-P0)T=max(dP.x,dP.y,dP.z)
t ={0,1,2,...,T}
P(t)= P0 +(P1-P0)*t/T

And even this can be improved by exchanging the *t/T by simple conditional increment/decrement inside loop like this:

There are also different algorithms like Bresenham for this but DDA is faster on modern architectures and also much simpler and easily expandable to any dimensionality.

Solution 2:

Thanks for all of the help, I was able to solve this using the DDA algorithm that was mentioned. I Put the python version in my question and I'll update it to JavaScript if anybody else wants it.

Post a Comment for "How Can You Find The Coordinates Between Two Given Points On A Straight Line(javascript)?"