Hi Fernando Castro,
as David T already said:
David T wrote: "
(...)
sqrt() is slow on computers and so if you need to compare against a value I suggest not square rooting the above result, and simply comparing the sum again a squared version of what you need to compare against. I.E.
(...)
"
if you have to check the distances of hundreds of enemies in a level, it really does matter how fast the computation for each one is. Therefore you should not use square root, but preferably square the value with which you are comparing (if it is variable), or, if it is constant just write it squared into you code (e.g. instead of 5, write 25, instead of 3, write 9 etc...)
square root is x^0.5 = sqrt(x) = dbSQRT(x) (in helpfile its written in capitals)
the opposite is: to square a value... x^2 = x*x
btw, the distance between 2 points in 2dimensions is calculated by using pythagoras formula:
where c is the distance, a the difference of the x-values, and b the difference of the y-values.(you should know or at least learn that, since this formula for rectangular triangles is more than 2000 years old...
)
for 3D, the formula looks like this:
where d is the distance, a the diff of the x-values, b the diff of the y-values, c the diff of the z-values (where each point is defined by a x, y and z-koordinate).
the code would be something like this:
//initialize variables
double x_dif = 0;
double y_dif = 0;
double z_dif = 0;
double dist_squared = 0;
// you dont need to take the absolute value of the differences, since you will square them (-> value will be positive anyways)
x_dif = dbObjectPositionX(1) - dbObjectPositionX(2);
y_dif = dbObjectPositionY(1) - dbObjectPositionY(2);
z_dif = dbObjectPositionZ(1) - dbObjectPositionZ(2);
dist_squared = x_dif*x_dif + y_dif*y_dif + z_dif*z_dif;
if (dist_squared <= 81) { // if object distance <= 9
// control enemy's AI
}
As you can see you need to compare with 81 instead of 9, since 9^2 = 81.
if you need to compare with a variable number, e.g. a size of an object (or something that is not known at compile-time):
if (dist_squared <= my_variable_dist * my_variable_dist) {
// dist <= my_variable_dist...
// control something
}
that's it. I think there is really nothing else to it.
hope this eliminates any concern.
greets,
Barnski.
-- I just started with DarkSDK, by translating DBP Projects. --