View Full Version : Game Math Question
Ojuzu
05-16-2007, 11:28 AM
Hi all - I have a (hopefully) simple question that's been driving me mad. I'm creating a 2D game and I need to find the coordinates of the halfway point between two points in a Cartesian coordinate system. So let's say point one is 10,-5 and the second point is 15,5. I know how to get the angle and distance but I can't for the life of me figure out how to find the coordinate of the halfway point. I'm thinking that maybe you use the distance along with the angle to project a point? But I have no idea how to do it.
I've tried many variations of adding and subtracting the X and Y positions but nothing is giving me consistently accurate results. Is there some super effective algorithm that will solve this?
Thanks in advance for any help.
Dennis
luggage
05-16-2007, 11:54 AM
Try
F32 Maths_Interpolate(F32 start, F32 end, F32 delta)
{
return start + ((end - start) * delta);
}
So..
midX = Maths_Interpolate( -10.0f, 15.0f, 0.5f );
midY = Maths_Interpolate( -5.0f, 5.0f, 0.5f );
Quick and dirty but should work.
Pyabo
05-16-2007, 12:45 PM
Is there some super effective algorithm that will solve this?
You don't need an algorithm, you need basic algebra.
http://en.wikipedia.org/wiki/Line_(mathematics)
Your initial attempt at solving the problem simply from calculations on the X,Y coords should work fine (like luggage's code)... you are doing the math incorrectly if it's not working consistently.
ggambett
05-16-2007, 12:54 PM
If you actually mean halfway, it's ( (x1+x2)/2, (y1+y2)/2 ). For any other fraction Q, the parametric equation solution as shown by Scott is the way to do it (in fact the above expression is a particular case of the parametric solution)
Ojuzu
05-16-2007, 02:29 PM
Thanks for the quick responses. This is the solution I was looking for, it's working perfectly now! I figured it would be a relatively simple solution but I'm embarassed to see just HOW simple! :o I'm not sure how I could've missed this but all of my calculations totally came out wrong. I think I was trying to solve both the X and Y values as vectors.
In any event, math is not my strong suit (obviously) so I really appreciate the help. And thanks for the link to line mathematics.
Thanks again all!
Dennis
ggambett
05-16-2007, 03:04 PM
In fact Scott's solution can be thought in terms of vectors. You have the points P1 and P2 so V=P2-P1 is a vector that "goes from P1 to P2". So to get the halfway point you add P1 plus half V.
In the special case of the halfway point, K = 0.5 so you get P1 + 0.5*(P2-P1) = P1 + 0.5*P2 - 0.5*P1 = 0.5*P1 + 0.5*P2 = 0.5*(P1+P2)
vBulletin v3.6.0, Copyright ©2000-2008, Jelsoft Enterprises Ltd.