Feeds:
Posts
Comments

Posts Tagged ‘quadratic’

In this post, SpaceTW asked:

Hi, I need help aiming at moving targets for a program. I have the variables for the speed and direction of the enemies, but the targeting is still not accurate enough.

There’s a very simple solution if you don’t mind the bullets travelling at different speeds, but that can lead to bullets travelling very fast or very slow, so let’s say that we want every bullet to go the same speed. Here’s the solution:

Suppose you have a tower at a fixed position (x_0,y_0), and an enemy at initial position (x_1,y_1) moving in the direction (v_x,v_y).

You want to shoot a bullet travelling at a certain velocity V so that it collides with the enemy.

Let the direction of the bullet be (d_x,d_y).

If d_x=v_x and d_y=v_y, then the bullet will move in parallel with the enemy, always staying the same distance from it.

You can now consider that the enemy is not moving at all, relative to the bullet, and the difference in position between them is (x_1-x_0, y_1-y_0). The bullet can move along this line to collide with the bullet.

If the bullet takes t frames to reach the bullet, we now get:

\begin{array}{rcl}d_x = (x_1-x_0)/t + v_x \\ d_y = (y_1-y_0)/t + v_y \end{array}

As we said that the bullet’s velocity is V, we get

d_x^2 + d_y^2 = V^2

Which expands out to:

\begin{array}{rcl} \left(\frac{1}{t}\right)^2 \left[ (x_1 - x_0)^2 + (y_1 - y_0)^2 \right] && \\ + \frac{1}{t} \left[ v_x (x_1 - x_0) + v_y ( y_1 - y_0) \right] &&\\ + v_x^2 + v_y^2 - V^2 &=& 0 \end{array}

(I had to split that over a few lines so it would fit in the post column, sorry!)

Which is a quadratic equation! So set:

\begin{array}{rcl} a &=& (x_1-x_0)^2 + (y_1-y_0)^2 \\ b &=&  2[ v_x(x_1-x_0) + v_y(y_1-y_0) ] \\ c &=&  v_x^2 + v_y^2 - V^2 \end{array}

Then, using the quadratic formula:

\frac{1}{t} = \frac{-b + \sqrt{ b^2 - 4ac}}{2a}

You can now put that back into the equations for d_x and d_y, and you’re done!

Here’s the result, written in BlitzMax:

diffx:double=x2-x1
diffy:double=y2-y1
v:Double=3                'desired speed of bullet

a:Double=diffx*diffx+diffy*diffy
b:Double=2*(vx*diffx+vy*diffy)
c:Double=vx*vx+vy*vy-v*v

tInv#=(-b+Sqr(b*b-4*a*c))/(2*a)   ' solve 1/t
dx=diffx*tInv+vx
dy=diffy*tInv+vy

That’s it!

Read Full Post »