Page 1 of 1

Mouse Joint with cocos2d

Posted: Sun May 05, 2013 2:16 pm
by alih
Hi Scott,
I've looked everywhere for a solution, but I just cant get this to work. I looked at the demo code that you've put up and did the same to get the mouse joint to work. However when I touch on a body it just snaps and moves in a completely different direction.

Here is the code I'm using:

Code: Select all

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    cpShape *shape = cpSpacePointQueryFirst(_space, [self convertTouchToNodeSpace:touch], GRABABLE_MASK_BIT, 0);
    if (shape) {
        cpBody *body = shape->body;
        _mouseJoint = cpPivotJointNew2(_mouseBody, body, cpvzero, cpBodyWorld2Local(body, [self convertTouchToNodeSpace:touch]));
        _mouseJoint->maxForce = 30000.0f;
        _mouseJoint->errorBias = 0.12f;
        cpSpaceAddConstraint(_space, _mouseJoint);
        return YES;
    }
    return NO;
}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
    if (_mouseJoint) {
        cpVect newPoint = cpvlerp(_mouseBody->p, [self convertTouchToNodeSpace:touch], 0.25f);
        _mouseBody->v = cpvmult(cpvsub(newPoint, _mouseBody->p), 60);
        _mouseBody->p = newPoint;
    }
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    [self ccTouchCancelled:touch withEvent:event];
}

- (void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event {
    if (_mouseJoint) {
        cpSpaceRemoveConstraint(_space, _mouseJoint);
        cpConstraintFree(_mouseJoint);
        _mouseJoint = NULL;
    }
}
I would really appreciate if you could tell me what I'm doing wrong.

Thanks
ALI

Re: Mouse Joint with cocos2d

Posted: Sun May 05, 2013 3:32 pm
by slembcke
It sounds like you are either converting the touch coordinates relative to the wrong node or that you aren't updating the mouse body's position/velocity right (see here).

Re: Mouse Joint with cocos2d

Posted: Mon May 06, 2013 4:20 am
by alih
Nope I think I've done it right. I rechecked the code and the touch coordinates are correct.

The problem only occurs when touch starts. When I move the body correctly follows.

Re: Mouse Joint with cocos2d

Posted: Mon May 06, 2013 8:23 am
by slembcke
So in my demo app it's constantly updating the position of the mouse even when the mouse button is not down. Then when the user does click the mouse, it already has the correct position in the ChipmunkDemoMouse variable.

Since you are doing it with touches and you don't get the location of a touch until the user actually touches the screen, I'm guessing your variable is holding whatever the last position of the last touch was, or (0, 0). Do you just need to set the touch position in touchesBegan before setting up the joint?