[comp.sys.mac.programmer] Object/Mouse hit detection

hawley@adobe.COM (Steve Hawley) (08/10/90)

I tried to mail this to the original poster, but it bounced.  Larry
Rosenstein covered a pretty good description of the technique.  Off the
top of my head, I put together the following piece of code, which should
do exactly what the poster asked for.  I can't say if this will work
correctly or not, because I don't have a Mac to try it out on :'(, but
the structure is there, and I have abstracted out the object routines.

Perhaps someone should check to see if this is correct, and bundle it with
Larry's reply for a frequently asked questions posting (or archive).


long bitData;
static BitMap testMap = { /* check this for me - I forget the structure */
	{0, 0, 2, 2}, 2, (Ptr)&bitData
};

GrafPort testPort;

Object *
TestPoint(p)
Point p;
{
	/*
	 * Test to see if a point is on or very near an object.
	 * Returns a pointer to the object hit, or NULL if none
	 * was hit.
	 */
	static int notinited = 1;
	GrafPtr savePort;
	register Object *thingPtr, *FirstObject(), *NextObject();
	/* your object handling code */

	GetPort(&savePort);
	if (notinited) { /* you can have an InitHit() routine, but I
			  * prefer this structure.
			  */
		OpenPort(&testPort); /* OpenPort() does a SetPort() */
		SetPortBits(&testMap);
		notinited = 0;
	}
	else {
		SetPort(&testPort);
	}

	MovePortTo(p.h, p.v);
	bitData = 0;

	for (thingPtr=FirstObject(); thingPtr; thingPtr=NextObject(thingPtr)) {
		DrawObject(thingPtr);
		if (bitData) break;
	}
	SetPort(savePort);
	return(thingPtr);
}

Steve Hawley
hawley@adobe.com
-- 
"Break out the cameras that reshape my face and get someone to carve up my head"
        -Alcatraz, "God Blessed Video"