View Full Version : Calculating Distance Between 2 Chars
nico173
June 11th, 2006, 02:11 AM
How would I go on about to calculate the distance of 2 characters. Calculating only the _x-axis between the two. And how would I go on to make a certain action if a certain distance between the two is reached?
Thanks in advance.
TheCanadian
June 11th, 2006, 02:29 AM
One Dimension:
d = x1 - x2
Two Dimension:
d = sqrt((x1 - x2)^2 + (y1 - y2)^2)
Joppe
June 11th, 2006, 08:18 AM
Canadian, I tought for one dimension you had to do something like this
d = x1._x - x2._x
distance = Math.sqrt(d*d)
stoodder
June 11th, 2006, 11:27 AM
Canadian, I tought for one dimension you had to do something like this
d = x1._x - x2._x
distance = Math.sqrt(d*d)
actually you juist take
d = x1._x - x2._x
then d = Math.abs(d); // take the absolute value
cobrasniper555
June 11th, 2006, 04:45 PM
Stooder is right, one dimension woud be:
d = x1._x-x2._x
d = Math.abs(d);
But...the problem is, there can be 2 x-distance values.
d = x1._x-x2._x;//The first one
d = x2._x-x1._x;//The second one
Joppe
June 11th, 2006, 07:12 PM
^Cobra, both of those two will give the same outcome.. Aswell as the code I wrote, all is correct :s
stoodder
June 11th, 2006, 07:33 PM
^Cobra, both of those two will give the same outcome.. Aswell as the code I wrote, all is correct :slol ya i sjut relized all ur code did was trurn the nmber posotive XD but i think what he means is one will giv eyou a negative distance i fyou dont take its absolute value, dunno fi theres any value in that information in this project but none the less
TheCanadian
June 11th, 2006, 08:35 PM
Canadian, I tought for one dimension you had to do something like this
d = x1._x - x2._x
distance = Math.sqrt(d*d)
Guess what the square root of a number squared is ;)
The sign of the distance depends on which position you use as your reference.
NiñoScript
June 12th, 2006, 02:45 AM
yep, thats right :)
if you need to know if its on the left or the right, the answer is:
d = x1 - x2
but if you just need the distance (which in fact is an absolute value)
d = Math.abs(x1 - x2)
... note that with bidimensional distance, d will always be absolute, soo to know where is the other object, you need an angle. I mean, you'll need trygonometric functions to calculate the angle of the distance vector. (Math.atan2() should work in that case ;))
Powered by vBulletin® Version 4.1.10 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.