On Wed, 20 Mar 2013 13:19:25 -0700, DaveC <
inv...@invalid.net> wrote:
>> Sounds like homework.
>>
>> But here's a hint: What's the equation of the line traced by the shot
>> from point one? And then what special cases are there?
>
>Your "homework" ear needs tuning: I'll be 60 this year. (c;
Doesn't mean you're not in school with a homework assignment. ;-)
>A friend (in his 50's) is writing a space (ie, "Aliens attack", et. al.) game
>and needs to figure out this kind of math.
>
>I don't know much math (just acting as the messenger...).
>
>The line traced by the shot: isn't that just from point X1,Y1 at an angle of,
>for example, 45 degrees? Don't know what equation that would be...
There are several ways to skin that cat, but a conceptually simple
approach is as follows:
The general equation of a line is:
y=m*x+b (1)
If your projectile is traveling at angle alpha, m is tan(alpha). You
can then subsitute in x1 and y1 and solve for b:
y1=m*x1+b
-or-
b = y1-x1*tan(alpha)
Then you can see if the second point is on the line, by just solving
(1) for x2, and seeing if that value is y2.
That leaves a few loose ends (you'd find a match if the second point
were on the wrong side of the first point, but still on the line), and
the arithmetic falls apart for vertical lines (best to just rotate the
world 90 degrees for lines more than 45 degrees off the X axis).
The bigger problem is that you don't really want exact intersection.
IOW, you count as a hit if you pass within some distance, epsilon, of
the second point.
You can handle that by assuming a line going through the second point,
at a 90 degree angle to the first line. Then you have equations for
two lines, and you can determine where the lines intersect. IOW, you
end up with the following system of equations:
y = m1*x + b1
y = m2*x + b2
Which you can trivially solve to find the point of intersection. That
intersection will be the point of closest approach. You can then
trivially compute the distance between the intersection and the point
with the usual distance formula:
d = sqrt((x2-xi)**2 + (y2-yi)**2)
and the check if (d < epsilon).
Normally you'd compute the square of the distance (avoids the need for
the messy square root calculation), and compare to (epsilon**2)
instead.
This still leaves you the issues of relative positions (the
intersection could, again, be "behind" the first point), and the
arithmetical problems of near vertical lines, both of which you'd need
to handle (usually done with some creative rotations and
translations).