Is this aglorithm any good?

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

Recommended Posts

Hello Coders, recently in my geometry i learned the distance formula. And while working it out , i thought it could be used towards game development? Like for say path finding? I dont know , so i wrote my implementation in C++. Class AI { public: double Distance3D(double x1, double x2, double y1, double y2, double z1, double z2) { double tempA,tempB,tempC,tempD; tempA = (x2-x1); tempB = (y2-y1); tempC = (z2-z1); Math::Squared(tempA); Math::Squared(tempB); Math::Squared(tempC); tempD = tempA + tempB + tempC; sqrt(tempD); return tempD; }; class Math { public: double Squared(double value) { return value*value; } }; int main() { cout<<"3d dist algorithm example:"<<endl; cout<<"Distance3D:"<<AI::Distance3D(2.5,4.5,6.7,8.7,9.8,4.2);<<",!"<<endl; getch(); return 0; } what do you think? Should i use this in a game? Is it a good practice to use this in a game? You see Im a novice at AI and i only started researching various AI's. I think it could actually be useful , for games. But then again i am no expert and only in the 10th grade. Thank You In Advance, CodeSeeker

Share on other sites
Taking distances is certainly a fundamental piece of math in any game system. It's not AI exclusive by any means.

sqrt can be expensive, so makes sure to use the squared distance as much as possible. For instance instead of choosing between 2 enemies based on who is the closest distance you choose based on closest distance squared. You get the same answer with both but save a square root in the latter.

-me

Share on other sites
Like Palidine said: use squared distance as much as possible.

Example:

if (x * x + y * y + z * z < radius * radius)
{
// point is inside sphere @ origin
}

...is faster than:

if (sqrtf(x * x + y * y + z * z) < radius)
{
// point is inside sphere @ origin
}

(Watch out for overflows when using integers)

Also have a look at Manhattan distance (http://en.wikipedia.org/wiki/Taxicab_geometry). It can be useful in game programming.

Share on other sites
Just a friendly advise, if you are going to use that class for your programs:
You are failing to assign the squared values back to the temporary variables.
If you want the squared function to work on the passed argument directly, you'll have to pass it by reference and apply the multiplication on it.

Either:
tempA = Math::Squared(tempA);
...

Or:
void Squared(double& value)
{
value *= value;
}

1. 1
2. 2
Rutin
20
3. 3
khawk
18
4. 4
A4L
14
5. 5

• 12
• 16
• 26
• 10
• 44
• Forum Statistics

• Total Topics
633760
• Total Posts
3013721
×