Calculating the distance between 2 points in 2D Space?
Solution 1
Distance in the sense you describe above will always be a positive value. The sum of the square of real numbers will always be positive, and the square root of a positive number will also always be positive. So, it doesn't matter whether you define xd = x2-x1
or xd = x1-x2
. They only differ by their sign and so both have the same absolute value which means they both square to the same value.
So, there aren't really any special cases here. The formulation of the distance measure accommodates all of the concerns you raise.
Solution 2
Math.Sqrt(Math.Pow (a.X-b.X, 2) + Math.Pow (a.Y-b.Y, 2));
Try this. It should work!
StallMar
Updated on June 08, 2022Comments
-
StallMar almost 2 years
So the formula is basically: xd = x2-x1 yd = y2-y1 Distance = sqrt(xd * xd + yd * yd)
But surely the formula has to be different depending on whether something is above, below, left, or right of the other object?
Like, if I have a sprite in the middle of the screen, and an enemy somewhere below, would that require changing the "x2-x1" (Let's just say the player sprite is x1, enemy is x2) the other way around if the enemy was above instead?
-
Vince Bowdren over 7 yearsHi Gul Rukh Khan, and welcome to Stack Overflow. Your answer looks quite thorough, but it is very difficult to read; can you format it to make it more legible? You should be able to separate out the code snippets and use markdown to make the different parts of your answer clearer.