StallMar
StallMar

Reputation: 31

Calculating the distance between 2 points in 2D Space?

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?

Upvotes: 2

Views: 12808

Answers (3)

Harry.J
Harry.J

Reputation: 31

Math.Sqrt(Math.Pow (a.X-b.X, 2) + Math.Pow (a.Y-b.Y, 2));

Try this. It should work!

Upvotes: 3

Gul Rukh Khan
Gul Rukh Khan

Reputation: 1

yes, you are very right. In my case, I have to calculate distance between two points in 2D. I put x1 for swarm,x2 for intruder along X-Axis and y1 for intruder and y2 for swarm along Y-Axis. d=sqrt((swarm(de,1) - (intruderX)).^2 + (swarm(de,2)-intruderY).^2); [Distance is not calculated accurately, I want when intruder comes inside the circle of any swarm particle, it must be detected][1], some times, intruder comes inside the circle but not be detected. This is my problem. Anyone, who solve my problem, will be very grateful to them. for de = 1:Ndrones
d = sqrt((swarm(de,1) - (intruderX)).^2 + (swarm(de,2)-intruderY).^2); if(d<=rad) % intruder has been detected x = intruderX;
y = intruderY; title('Intruder Detected'); text(x,y+5,sprintf('Intruder')); text(500,900,sprintf('Iterations: %.2f',iter)); plot(swarm(:,1),swarm(:,2)); for i=1:Ndrones swarm(:, 9) = 100; %restart the minimum calculation end return; end end % end of de loop [1]: https://i.sstatic.net/SBP27.png

Upvotes: 0

andand
andand

Reputation: 17487

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.

Upvotes: 5

Related Questions