【问题标题】:Java/Android - libGDX/box2d - body has low velocityJava/Android - libGDX/box2d - 主体速度低
【发布时间】:2026-02-02 18:45:01
【问题描述】:

我正在尝试创建一个简单的 FlappyBird 克隆,其中不是鸟,而是一顶帽子。

到目前为止,代码很简单:屏幕中心的一顶帽子(Sprite obj.),即 position.x 等于 camera.x(因为相机在移动,所以帽子也随之“移动” ),帽子的 position.y 受到动态物体的影响,该物体通过重力和向上的力移动。

问题是:帽子太慢了,我什至将世界的向量设置为 0,500,它仍然走得很慢+“向上”力更慢,所以程序中物体的总速度非常低,我尝试了许多不同的方法来改变它(改变 PPM、增加力量大小等)

代码如下:

final float PIXELS_TO_METERS = 100f;
    // The first function to launch, runs only once.
@Override
public void create () {
    camera = new OrthographicCamera(288, 497);
    batch = new SpriteBatch();

    bg = new Texture("bg.png");
    hat = new Sprite(new Texture("hat.png"));
    ground = new Texture("ground.png");

    world = new World(new Vector2(0, -9.18f), true);

    BodyDef bodyDef = new BodyDef();
    PolygonShape shape = new PolygonShape();
    FixtureDef fdef = new FixtureDef();

    bodyDef.type = BodyDef.BodyType.DynamicBody;
    bodyDef.position.set(hat.getX(), hat.getY());
    bhat = world.createBody(bodyDef);

    shape.setAsBox(hat.getWidth()/PIXELS_TO_METERS,
      hat.getHeight()/PIXELS_TO_METERS);
    fdef.shape = shape;
    bhat.createFixture(fdef);

}

@Override
public void render () {
    cameraupdate();

    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    worldupdate();
    worlddraw();

    batch.setProjectionMatrix(camera.combined);
}

public void worldupdate() {
    if(fTouch)  
        world.step(Gdx.graphics.getDeltaTime(), 6, 2);

    if(Gdx.input.justTouched()) {
        if(fTouch == false)
            fTouch = true;
        bhat.applyForceToCenter(new Vector2(0, 30), true);
    }
}

public void worlddraw() {
    batch.begin();
    batch.draw(bg, camera.position.x-144, -268,  bg.getWidth(),
    bg.getHeight()+20);

    batch.draw(hat, camera.position.x, bhat.getPosition().y);
    for (int i = 0; i < 4000; i++) 
        batch.draw(ground, i * ground.getWidth() - 287, -250);
    batch.end();
}

【问题讨论】:

    标签: java android libgdx box2d


    【解决方案1】:

    您可能希望将步骤修复为:

    public static float TIME_STEP = 1/500;
    public float accumulator = 0
    
    public void worldupdate() {
        if(fTouch) {
           this.accumulator += Gdx.graphics.getDeltaTime();
           while (this.accumulator >= TIME_STEP) {
               world.step(TIME_STEP, 6, 2);
               this.accumulator -= TIME_STEP
           }
        }
    }
    

    这可能有助于提高速度。

    【讨论】: