detecting distance of two objects

Discussion in 'iOS Programming' started by macfanboy, Jan 22, 2009.

  1. macfanboy macrumors 6502a

    Joined:
    Jun 5, 2007
    #1
    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
     
  2. chbeer macrumors member

    chbeer

    Joined:
    Sep 22, 2008
    Location:
    Berlin
    #2
    The solution lies anywhere between cosinus and sinus...
     
  3. xsmasher macrumors regular

    xsmasher

    Joined:
    Jul 18, 2008
    #3
    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.
     

Share This Page