开发者

Can't seem to get ApplyForce() to work in a way that makes sense

I’m having a problem utilizing b2Body->ApplyForce() in an IOS/cocos2D/Box2D game. I have a ball object, and I’m applying force to simulate a golf club strike on it. The user sets the angle and power of the shot, then taps a shoot button to shoot the ball. The code I’m using follows:

CGPoint ballPosition = game.theBall.position;
b2Vec2 force;
force.x = ((game.power*POWER_REDUCTION) * cos(game.angle))/PTM_RATIO; // cocos2D angle
force.y = ((game.power*POWER_REDUCTION) * sin(game.angle))/PTM_RATIO;
CCLOG(@"Force: %f, %f", force.x, force.y);
CCLOG(开发者_JAVA百科@"Angle: %.4f", game.angle);
b2Vec2 point = body->GetWorldPoint(b2Vec2(0.0f, 0.0f));
body->ApplyForce(force, point);

POWER_REDUCTION is just a defined constant I’m using while testing so I can affect the power of the shot and dial in the right numbers. In my Update method, I’m re-positioning the sprite associated with the Box2D body it represents:

GolfBallObject *ballSprite = [self getChildByTag:GOLF_BALL_SPRITE_TAG];
if (!ballSprite)
{
    CCLOG(@"in PlayLayer->update: [self getChildByTag:GOLF_BALL_SPRITE_TAG] returned nil");
}

b2Vec2 p = theBall->GetWorldPoint(b2Vec2(0.0f, 0.0f));
CGPoint newPosition = ccp(p.x*PTM_RATIO, p.y*PTM_RATIO);
ballSprite.position = newPosition;
game.theBall.position = newPosition;

        CCLOG(@"In Flight - ball position: %.2f, %.2f", game.theBall.position.x, game.theBall.position.y);

theBall is the b2Body tied to my ball sprite.

No matter how I adjust the force applied, the ball follows the same flight:

Shooting - ball position: 120.00, 455.00
Force: -0.004102, 0.004030
Angle: 14.9314
In Flight - ball position: -1441.75, -731.84
In Flight - ball position: -3015.97, -1961.38
In Flight - ball position: -4591.16, -3192.20

another:

Shooting - ball position: 120.00, 455.00
Force: -0.410169, 0.402972
Angle: 14.9314
In Flight - ball position: -1441.75, -731.84
In Flight - ball position: -3015.97, -1961.38
In Flight - ball position: -4591.16, -3192.20

Here’s one where I change the angle:

Shooting - ball position: 120.00, 455.00
Force: -0.561694, 0.122985
Angle: 78.3243
In Flight - ball position: -1441.75, -731.84
In Flight - ball position: -3015.97, -1961.38
In Flight - ball position: -4591.16, -3192.20

I’ve never used Box2D before, so I’m sure there is something I’m missing that’s probably elementary, but this behavior seems totally irrational. Both the angle and the force seem to be non-relevant. Can you please point out what I’m doing wrong?

Thanks!

-Dick


I think you really want to use apply implulse for thiS...apply force is for a smooth, continuous motion, not a sudden strike of a golf club. Also, try changing the point of impact. If you strike a basketball straight downward from the top it will alway pop upwards. If you strike it from the side, it will move sideways.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜