Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!tut.cis.ohio-state.edu!rutgers!psuvax1!swatsun!jackiw From: jackiw@cs.swarthmore.edu (Nick Jackiw) Newsgroups: comp.sys.mac.programmer Subject: Hit Check for Lines Message-ID: Date: 10 Aug 90 14:07:17 GMT Sender: jackiw@cs.swarthmore.edu (Nick Jackiw) Organization: Visual Geometry Project, Swarthmore College, PA Lines: 84 Following up yesterday's discussion, I've heard from a number of people who would like to see the algebra for testing if a line is hit efficiently. Here it is. ----- Hit Detection for Geometric Lines Address questions or comments to Nick Jackiw -> jackiw@cs.swarthmore.edu My application involves several types of geometric objects--lines, rays, segments, circles and polygons--and therefore prior to calling an object- type-specific hitCheck I first check if the hit-point is within a bounding rectangle of the object. (This rectangle is computed when the object is created, or when it is dynamically transformed.) While the formulas below apply to full geometric lines (infinitely extending), a preliminary bounding-rectangle check throws away hits which are on the line but off the segment. If your application uses segments, you'll have to make a similar check before (or after) evaluating this formula. Given point P(p,q) line L through two points (x1,y1), (x2,y2) Test: Is the distance D from P to L less than k units? [You may want to let k=2 or even 3 so the user has some latitude in selecting the line] [Terminology: |n|=absolute value of n n^m=n raised to mth power] Let dX=x2-y1 dY=y2-y1 dP=p-x1 dQ=q-y1 The distance between the P and the line is therefore |dQ*dX-dP*dY| D= ----------------- sqrt(dX*dX+dY*dY) So D