如何用box2d让b2body匀速移动

发布于 2024-12-06 07:54:20 字数 279 浏览 0 评论 0原文

我正在制作一个 box2d 游戏,让敌人从屏幕左侧飞到屏幕右侧。如果我在刻度方法中施加如下所示的力,敌人会随着时间的推移移动得越来越快。我希望敌人以恒定的速度移动,而不是加快速度。我该怎么办呢。我尝试过冲动和力量,但它们似乎并没有保持恒定的速度

b2Vec2 forceA = b2Vec2(15, -b->GetMass() * world->GetGravity().y);
b->ApplyForce(forceA, b->GetWorldCenter() );

I am making a box2d game and have enemies fly in from the left side of the screen to the right side of the screen. If I apply a force in the tick method like shown below, the enemies increasingly move faster over time. I want the enemies to move at a constant pace instead of increasing their speed. How can I do this. I have tried impulses and forces, but they don't seem to keep a constant speed

b2Vec2 forceA = b2Vec2(15, -b->GetMass() * world->GetGravity().y);
b->ApplyForce(forceA, b->GetWorldCenter() );

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

叹倦 2024-12-13 07:54:20

只需以您想要的速度创建它们:

b2BodyDef bDef;
...
bDef.linearVelocity = myVelocity;
b2Body *b = world->createBody(&bDef);

如果没有向它们施加力,它们将根据牛顿第一定律保持其速度。如果有重力,则每一步都会施加力:

b2Vec2 forceA = b2Vec2(0, -b->GetMass() * world->GetGravity().y);
b->ApplyForce(forceA, b->GetWorldCenter() );

Just create them with the speed you want:

b2BodyDef bDef;
...
bDef.linearVelocity = myVelocity;
b2Body *b = world->createBody(&bDef);

If no forces are applied to them they will preserve their speed according to Newton's first law. If you have gravity then each step apply force:

b2Vec2 forceA = b2Vec2(0, -b->GetMass() * world->GetGravity().y);
b->ApplyForce(forceA, b->GetWorldCenter() );
沙与沫 2024-12-13 07:54:20

使用b->SetLinearVelocity(b2Vec2(thisVel, 0));。如果这个恒定速度最终可能会改变为其他恒定速度,您可以将其包装在一个条件中,例如

if(b->GetLinearVelocity().x != 0){ 
    b->SetLinearVelocity(b2Vec2(0, 0));
}

这样您就不会在每个刻度处重新应用相同的速度(尽管 box2d 可能会为您处理这个问题,对此不太确定)。

我遇到了同样的问题,即如何使身体以恒定速度移动,我建议的另一件事是确保您的身体移动的表面/介质是无摩擦的 - 这样它们在移动后就不会减慢速度你设置他们的速度。

use b->SetLinearVelocity(b2Vec2(thisVel, 0));. If this constant velocity might eventually be changed for some other constant velocity, you could wrap this in a conditional such as

if(b->GetLinearVelocity().x != 0){ 
    b->SetLinearVelocity(b2Vec2(0, 0));
}

So that you're not re-applying the same velocity each tick (although it's possible that box2d takes care of this for you, not sure about that).

I ran into the same issue of how to make bodies move at a constant speed, and the one other thing I recommend is to make sure the surface/medium that your body is moving across is frictionless - that way they'll never slow down after you set their velocity.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文