Is my Distance formula right?

This topic is 4493 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I have 2 objects, when i move 1 object over to the other one, the formuala is only reading the x vector, so no matter where object1 is on the y it still detects collision. I need it to check both x and y. Formula: Distance = sqrt(ABS(Obj1Y - Obj2Y) + ABS(Obj2X - Obj2X));

Share on other sites
Umm, Obj2X - Obj2X will always be 0, you probably intended to write Obj1X - Obj2X, which seems to be the correct formula..

Share on other sites
dist = sqrt((x2-x1)^2 + (y2-y1)^2)

You need to square your inside terms, and make sure you're not getting a zero sum like you seem to be in your x component (x2-x2?).

Hope that helped.

Share on other sites
Well i cant do that because it says its illegal!!

c:\documents and settings\jrp\desktop\opengl work\lesson01\lesson1.cpp(276) : error C2296: '^' : illegal, left operand has type 'float'

Quote:
 Umm, Obj2X - Obj2X will always be 0

Oops my mistake!! I just posted it wrong..

Share on other sites
Kool so with a little tinkering i finally got it!! sheesh* thx guys..
Distance = ABS(Obj2X - Obj1X) / 2 + ABS(Obj2Y - Obj1Y) / 2;float sqrtf(Distance);

Share on other sites
its not divided by two it should be ABS(Obj2X - Obj1X) to the second power and ABS(Obj2Y - Obj1Y) to the second power:

Distance = pow(Obj2X - Obj1X,2)+ pow(Obj2Y - Obj1Y,2);
float sqrtf(Distance);

Share on other sites
float deltax = x1 - x2;float deltay = y1 - y2;float distance = sqrtf((deltax * deltax) + (deltay * deltay));

Share on other sites
Actually C/C++ doesn't have a squaring operator.

Julian was using the ^(caret) to symbolize the squaring function. Some languages like BASIC do use the ^(caret) as a squaring operator. But in C, the caret operator is used for the bitwise XOR on integer operands only.

You can square a number(x) in C using the pow(x,2) or x*x which does the same thing(the latter being more efficient).

Distance Formula

Share on other sites
well, why does / 2 work??

Share on other sites
/ 2 doesnt work, it will give you a number just not the right one:
example:
Obj1Y = 0
Obj2Y = 0
Obj1X = 5
Obj2X = 0

this distance between them is 5 but with the way you did it:
Distance = ABS(Obj2X - Obj1X) / 2 + ABS(Obj2Y - Obj1Y) / 2;
the square root of 5/2 + 0/2 = square root of 5/2 which is not 5

if you square them you have the square root of 25 which is 5

1. 1
Rutin
32
2. 2
3. 3
4. 4
5. 5

• 11
• 13
• 89
• 11
• 10
• Forum Statistics

• Total Topics
632973
• Total Posts
3009619
• Who's Online (See full list)

There are no registered users currently online

×