3
\$\begingroup\$

I'm making a simple game where I shoot things from a certain point on screen (A).

I tap the screen and shoot the projectile from initial point(A) to the tap point(B).

But I want the projectile to move along the same path instead and fly out of bounds of the screen.

How do I calculate a point that is on the same line that these two points, but further away?

This is a simple math, but I can't figure it out.

\$\endgroup\$
12
\$\begingroup\$

If A and B are both 2D vectors, then...

direction = normalize(B - A)
any point on the line = direction * distance + A

Or you can just take normalize(B - A) * speed and add that to the projectile's position every frame.

\$\endgroup\$
2
\$\begingroup\$

The equation of a line is y=mx+b where m is the slope, b is the offset, and x and y are variables (coordinates on the grid).

To get this equation from 2 points, you can use the point-slope formula:

y - A.y = m(x - A.x)

To calculate the slope, m, you need to figure out the change in y values over the change in x values:

(B.y-A.y)/(B.x-A.x) = m

To get the offset, b, you need to plug in the slope and simplify the formula:

y = m*x - m*A.x + A.y

So b = m*A.x + A.y

After you have m and b, you have the equation for the line. Plug in x and y values and it will be on that line.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.