Java/Android - libGDX/box2d - body has low velocity

104 views Asked by At

I'm trying to create a simple FlappyBird clone, where instead of a bird - there's a hat.

So far the code is simple: A hat (Sprite obj.) at the centre of the screen, which is position.x is equal to camera.x (because the camera moves, the hat "moves" with it as well), the hat's position.y is effected by a dynamic body, which moves by gravity and up forces.

The problem is: the hat is too slow, I even set the world's vector to 0,500 and it still goes slowly + the "up" force is even slower, so the total velocity of the object in the program is VERY low, and I've tried many different ways to change that (change PPM, increase force size, etc.)

Here is the code:

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();
}
1

There are 1 answers

0
Fechy On

You might want to fix the steps to something like:

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
       }
    }
}

This might help the speed.