ios - 似乎无法让 ApplyForce() 以一种有意义的方式工作

标签 ios cocos2d-iphone box2d

我在 IOS/cocos2D/Box2D 游戏中使用 b2Body->ApplyForce() 时遇到问题。我有一个球对象,我正在施加力来模拟高尔夫球杆对它的击打。用户设置射门的角度和力量,然后点击射门按钮射门。我使用的代码如下:

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(@"Angle: %.4f", game.angle);
b2Vec2 point = body->GetWorldPoint(b2Vec2(0.0f, 0.0f));
body->ApplyForce(force, point);

POWER_REDUCTION 只是我在测试时使用的定义常量,因此我可以影响射击的力量并输入正确的数字。在我的 Update 方法中,我正在重新定位与其代表的 Box2D 主体关联的 Sprite :

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 是绑定(bind)到我的球 Sprite 的 b2Body。

无论我如何调整施加的力,球都遵循相同的飞行:

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

另一个:

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

这是我改变角度的一个:

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

我以前从未使用过 Box2D,所以我确定我遗漏了一些可能很基本的东西,但这种行为似乎完全不合理。角度和力似乎都无关紧要。你能指出我做错了什么吗?

谢谢!

-迪克

最佳答案

我想你真的想为此使用 apply impulse...apply force 是为了平滑、连续的运动,而不是突然击打高尔夫球杆。另外,尝试改变冲击点。如果你从顶部直接向下击打篮球,它总是会向上弹出。如果您从侧面击打它,它会向侧面移动。

关于ios - 似乎无法让 ApplyForce() 以一种有意义的方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7115692/

相关文章:

ios - 如何取消选择选定的 UITableView 单元格?

ios - touchUpInside 事件未触发

ios - UIButton 奇怪的状态变化(UIControlState)

box2d - 当 Box2D 主体在时间步外被破坏时,Contact Listener 崩溃

ios - 如何在 cocos2d-iphone 中创建 sprite 后的静态路径?

objective-c - cocos2d动画总是崩溃

c++ - 为什么这个 OpenGL-es 纹理绑定(bind)到 cocos2d 2.0 中的山丘?

ios - 重复将相同的 spritesheet 重新加载到帧缓存中是否浪费?

java - 如何创造漩涡/漩涡效果?