简体   繁体   English

Box2D(C ++)重力井

[英]Box2D (C++) Gravity Wells

Currently I am using the Box2D physics engine in a game of mine - and I was wondering if I could create a gravity well of sorts, in which all the bodies are attracted to a single arbitrary point. 目前,我在我的游戏中使用Box2D物理引擎-我想知道是否可以创建各种重力井,其中所有物体都吸引到一个任意点。 Is there a certain way to do this, or will i have to apply a custom force of sorts to each body? 有某种方法可以做到这一点,还是我必须对每个身体施加某种自定义力量? (I tried making a static superdense body, but Box2D doesn't apply Newton's Law of Universal Gravitation on a body-to-body basis) (我尝试制作一个静态的超稠密物体,但Box2D不适用于基于牛顿的万有引力定律)

Also, is there a way to make an anti-gravity well? 另外,有没有办法使反重力很好? Could I make a denser sphere centered around an arbitrary point and use buoyancy to achieve this? 我可以制作一个以任意点为中心的致密球体,并使用浮力实现此目的吗?

This functionality isn't built into Box2D unfortunately. 不幸的是,Box2D并未内置此功能。 The easiest thing to do is get the angle and the distance between the gravity well and the rigid body and set the bodies velocity accordingly. 最简单的方法是获得重力井与刚体之间的角度和距离,并据此设置刚体速度。

To get the angle: 要获得角度:

double dx = rigidBodyX - gravityWellX;
double dy = rigidBodyY - gravityWellY;
double angle = atan2(dy, dx);
// angle is in radians, use atan2(dy, dx) / PI * 180 if 
// you need degrees

To get the distance: 获取距离:

double dx = rigidBodyX - gravityWellX;
double dy = rigidBodyY - gravityWellY;
double dist = sqrt(dx * dx + dy * dy);

I whipped up a quick example using flash and a library I wrote called QuickBox2D. 我使用Flash和我编写的名为QuickBox2D的库整理了一个简单的示例。 It might not be that helpful since the syntax is very different from the C++ Box2D library, but the basic principal is the same. 由于语法与C ++ Box2D库非常不同,所以它可能没有帮助,但是基本原理是相同的。 It's also not a perfect example, but it might get you started. 这也不是一个完美的例子,但它可能会让您入门。

See The Flash Example 请参阅Flash示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM