Math problem - Calculating if an object is in range of another

Started by Rocco, Fri 11/02/2011 16:11:01

Previous topic - Next topic

Rocco

i had this several times and dont know a convenient solution.

i want to know if an object is in range within say 10px of another one, and have to write the complicate way like:

if((object[0].X - object[[1].X) < 10 && (object[0].X - object[[1].X) > -10)
do stuff

this construct works, but i'm knowing there is an easier way for this,
cause i have to calculate these several times in my script.

Calin Leafshade

#1
Pythagoras!

in pseudo:
distance = sqrt ( (x1 - x2) ^ 2 + (y1 - y2) ^ 2 )

EDIT: the syntax for squaring is not the same in AGS so just multiply the term by itself to square it

Rocco

well thx, this will work, but it needs nearly the same effort as before, and i guess it costs more cpu_power.
i thaught in another direction, lets say

pseudo:
distance = (x1 - x2);
if(distance < 0)
make distance positive (exp. convert -13 to 13)



Calin Leafshade

your original calculation isnt really that accurate since it uses a kind of 'box' to calculate distance. Mine uses a circual radius around a point.

And on the subject of CPU, unless you are doing this thousands and thousands of times a second it really wont be an issue.

Rocco

thats right, i will using your suggestion, big thx.  :)

btw:
for my interest, maybe you know how to make a value positve?

if(distance < 0)
make distance positive (exp. convert -13 to 13)

Calin Leafshade


Code: ags

function AbsInt(int value){

if (value < 0) return value * (-1);
else return value;

}


EDIT: functionised

Kweepa

If you are just interested in the linear distance as your code suggests, here is the simplest way.

Code: ags

bool InRange(Object *o1, Object *o2, int range)
{
   int offset = o1.X - o2.X;
   // squaring both sides makes them positive
   return (offset*offset < range*range);
}

if (InRange(o1, o2, 10)
{
   // do stuff
}
Still waiting for Purity of the Surf II

monkey0506

Calin, you don't have to actually multiply by -1, you can just do this (with the same result, but simpler syntax).

Code: ags
if (distance < 0) distance = -distance;

Calin Leafshade

Quote from: Kweepa on Fri 11/02/2011 17:08:19
If you are just interested in the linear distance as your code suggests, here is the simplest way.

I completely didnt notice that the y value wasnt a factor.

Rocco

big thx, that solutions suits my needs completly.
in this case i also need the y.value,
but the linear approach might come also in handy soon, cause i stumbled often over this kind of calculations in my projects.  :)

SMF spam blocked by CleanTalk