If you define the area occupied by a vehicle as a circle, things get a lot easier. Consider the vector equation of a line:
p =
a +
xd where
p is any point on the line,
a is a definite point on the line and
d is the direction. Let
a be the position of the shooter and
d the direction of the bullet (i.e. the direction of the shooter when the bullet was released).
Now consider an enemy at point
q with a radius
r.
Basically you want to know if, for any value of
x, does it come within
r of
q (i.e. does it touch or come into the circle).
Distance from
p to
q is |
q-
p|.
Hence, if |
q-
p| =
r then a collision occurred.
To tidy up the left hand side, let's go to cartesian form. Remember the aim here is to find some value of
x that satisfies this new equation.
Let Ex, Ey = enemy position in cartesian form
Let Px, Py = some position on the bullet line in cartesian form
Let Dx, Dy = bullet direction
SQR(((Ex - Px) * (Ex - Px)) + ((Ey - Py) * (Ey - Py))) =
r
Thus:
(Ex - Px)^2 + (Ey - Py)^2 <= r^2
Since Px = Ax + xDx and Py = Ax + xDy:-
(Ex - Ax - xDx)^2 + (Ey - Ay - xDy)^2 = r^2
Expanding:
x^2 Dx^2 - 2x(ExDx - AxDx) - 2ExAx + Ex^2 + Ax^2 + x^2 Dy^2 - 2x(EyDy - AyDy) - 2EyAy + Ey^2 + Ay^2 = r^2
Factorising for co-efficients of common powers of x:
x^2(Dx^2 + Dy^2) - 2x(ExDx - AxDx + EyDy - AyDy) - 2ExAx - 2EyAy + Ex^2 + Ey^2 + Ax^2 + Ay^2 - r^2 = 0
Now you can use the discriminant function to determine whether any real solutions to this equation exist.
Using b^2 - 4ac >= 0
Let f(E, r, A, D) = 4((ExDx - AxDx + EyDy - AyDy)^2 - (Dx^2 + Dy^2)(Ex^2 + Ey^2 + Ax^2 + Ay^2 - 2ExAx - 2EyAy - r^2))
Now, if f(E, r, A, D) >= 0 then the line intersects with the enemy. You will probably want to check the value for 'x' that the intersection occurs at, if it does at all, to make sure that it is in range of the bullet line.
By the way, if you're happy using dot products, etc., you'll find the above mess turns into a much nicer-to-look-at form:
f(E, r, A, D) = 4(( (
E .
D) - (
A .
D) )^2 + (
D .
D)( (
E .
E) + (
A .
A) - 2(
A .
E) -
r^2))
This will give you a value for 'b^2 - 4ac' in the famous auto-magic quadratic-equation-solver-equation:
x = (-b +/- SQR(b^2 - 4ac)) / 2a
So, you can do this to find the value of x that the line intersects at:
x1 = (-b + SQR(f(E, r, A, D))) / 2a
x2 = (-b - SQR(f(E, r, A, D))) / 2a
Notice you end up with 2 values of x; find the point that is closest to the bullet launch position (
A) and that's where abouts the bullet hit on the enemy. You could even use this to spawn a nice particle effect at the correct impact location.
It's very late where I am (5:00 am) so I might have messed up some of that maths. There's quite a bit of theory missing, like checking whether the value of x calculated is too far away from the bullet's current location to count as a hit or not.
Hope this helps a bit.
-shiftLynx