PDA

View Full Version : detecting distance of two objects




macfanboy
Jan 22, 2009, 07:05 PM
maybe this is a noob question (sorry!)
but im using CGRect to create multiple rectangles. How could i detect if they got within 5 pixels of each other?

sorry again if this is a noob question



chbeer
Jan 23, 2009, 02:17 AM
The solution lies anywhere between cosinus and sinus...

xsmasher
Jan 23, 2009, 02:56 AM
maybe this is a noob question (sorry!)
but im using CGRect to create multiple rectangles. How could i detect if they got within 5 pixels of each other?

sorry again if this is a noob question

As beer implied, there's nothing built-in for this, but you can use trigonometry to figure it out. Specifically the Pythagorean theorem - think of your two points as being on the hypotenuse of a triangle. In code:

dx = a.x - b.x;
dy = a.y - b.y;
distance = sqrt(dx*dx + dy*dy);

That will give you the distance between the centers (not the edges) of the objects, which may be good enough for you.