我在box2dworld中创建了1个动态和1个静态体,我想通过制作一个斜坡使动态体在水平方向上移动,但它根本不起作用。这是我的代码。
public class Box2dBodyTest implements ApplicationListener
{
World world;
Box2DDebugRenderer debugRenderer;
private OrthographicCamera camera;
@Override
public void create()
{
camera = new OrthographicCamera();
camera.setToOrtho(false);
world = new World(new Vector2(0, -10), true);
debugRenderer = new Box2DDebugRenderer();
createDynamicBody();
createStaticBody();
}
private void createDynamicBody()
{
BodyDef bodyDef = new BodyDef();
// We set our body to dynamic, for something like ground which doesn't move we would set it to StaticBody
bodyDef.type = BodyType.DynamicBody;
// Set our body's starting position in the world
bodyDef.position.set(100, 300);
// Create our body in the world using our body definition
Body body = world.createBody(bodyDef);
// Create a circle shape and set its radius to 6
CircleShape circle = new CircleShape();
circle.setRadius(6f);
// Create a fixture definition to apply our shape to
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f; // Make it bounce a little bit
// Create our fixture and attach it to the body
Fixture fixture = body.createFixture(fixtureDef);
body.applyForceToCenter(10.0f, 0.0f, true);
// Remember to dispose of any shapes after you're done with them!
// BodyDef and FixtureDef don't need disposing, but shapes do.
circle.dispose();
}
private void createStaticBody()
{
// Create our body definition
BodyDef groundBodyDef = new BodyDef();
// Set its world position
groundBodyDef.position.set(new Vector2(0, 10));
// Create a body from the defintion and add it to the world
Body groundBody = world.createBody(groundBodyDef);
// Create a polygon shape
PolygonShape groundBox = new PolygonShape();
// Set the polygon shape as a box which is twice the size of our view port and 20 high
// (setAsBox takes half-width and half-height as arguments)
groundBox.setAsBox(camera.viewportWidth, 10.0f);
// Create a fixture from our polygon shape and add it to our ground body
groundBody.createFixture(groundBox, 0.0f);
// Clean up after ourselves
groundBox.dispose();
}
@Override
public void render()
{
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.update();
world.step(1/60f, 6, 2);
debugRenderer.render(world, camera.combined);
}
}
我已经搜索了很多,并尝试我最好的解决这个问题,通过box2d教程等,但没有得到解决。请大家帮帮我。先谢谢你了。
我建议你在处理Box2d的时候使用现实的尺寸。Box2d假设的比例是每米一个像素,这对大多数程序员来说不是很实用。当你定义你的圆形夹具时,你设置半径为6.0f,这意味着 Box2d创建一个直径为12米或39英尺的圆。 . 这是巨大的。我建议你看看 本视频. 当我为同样的问题而苦恼时,它真的帮助了我。