Chipmunk Drag and Drop using cpMouse

Home / Blog / iPhone Development / Chipmunk Drag and Drop using cpMouse

Even though our latest iPhone app, Scrambled Apps!, wasn’t approved for the app store, it still might be beneficial for me to document some of the work that made it possible. If you’re not familiar with the app, visit http://www.brimllc.com/mobile-applications/scrambledapps/.

The app used Chipmunk physics engine with the cocos2d graphics library to mimic a user’s home screen, which would “fall” apart when clicked. The “falling” was made possible using Chipmunk; however, I had to make some modifications to a 3rd party utility class to enable the dragging and dropping.

On the Chipmunk forums, I found a class called cpMouse. This class managed constraints between objects to allow dragging. The only issue I found was that the version of cpMouse that was available didn’t work with the latest version of Chipmunk, what at the time of this writing is v5.0.0 I believe.

The order yasmin cheap updated cpMouse files are located here: http://www.brimllc.com/wp-content/uploads/2010/08/cpMouse.h and here: http://www.brimllc.com/wp-content/uploads/2010/08/cpMouse.c.

To use this class in an iPhone game, you simply reference this class in your ccTouchesBegan, ccTouchesMoved, and ccTouchesEnded method handlers. Here are examples of each:

ccTouchesBegan

- (void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView: [myTouch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
mouse = cpMouseNew(space);
cpMouseMove(mouse, cpv(location.x, location.y));
cpMouseGrab(mouse, cpv(location.x, location.y));
}

ccTouchesMoved

- (void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView: [myTouch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
//move the nouse to the click
cpMouseMove(mouse, cpv(location.x, location.y));
if(mouse->grabbedBody == nil){
//if there's no associated grabbed object
// try get one
cpMouseGrab(mouse, cpv(location.x, location.y));
}
}

ccTouchesEnded

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self ccTouchesCancelled:touches withEvent:event];
}

- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
cpMouseDestroy(mouse);
}

I would think that the above methods are fairly self explanatory, but I can answer questions if anyone needs more clarification.

Leave a Comment