问题
I am using Box2d and Cocos2d to develop an iPhone game. I have a ball in the center of the screen with a simple boundary created using fixtures etc. What I want to do is add the functionality so that a user can "swipe" the ball to apply force and basically flick it across the screen.
I am using the following code to achieve this:
b2Vec2 force = b2Vec2(30, 30);
_body->ApplyLinearImpulse(force, _ballBodyDef->position);
If I apply a linear impulse during the init function the ball fires off in the correct direction and behaves as it should do. It doesnt do anything, however, if I put it into the handlePan
function that is called when a gesture is done by the user. Here is the full code for the function: (Note that the NSLog
writes out the correct information.
- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer {
if (recognizer.state == UIGestureRecognizerStateEnded) {
CGPoint velocity = [recognizer velocityInView:recognizer.view];
NSLog(@"Vel: %f, newPos: %f",velocity.x,velocity.y);
b2Vec2 force = b2Vec2(30, 30);
_body->ApplyLinearImpulse(force, _ballBodyDef->position);
}
}
回答1:
The force you are applying in handlePanFrom is always b2Vec2(30, 30). It will never change with your current code, and is therefore not going to move in your direction.
来源:https://stackoverflow.com/questions/6795853/applylinearimpulse-doesnt-work-when-called-within-uipangesturerecognizer-functio