0
votes

I am trying to bounce a ball in an android project using the libGDX game engine.

    ball = new Texture("football.jpg");
    batch = new SpriteBatch();
    sprite = new Sprite(ball);
    render(float delta)
    {
    batch.begin();
    sprite.draw(batch);
    batch.end();
    stage.draw();
    jumpUp();    //here i call the jump function..
    }

The jump function looks like this:

public void jumpUp()
{
    sprite.setY(sprite.getY()+2);
    dem=sprite.getY();
    if(dem==100.0f)
    {
        jumpDown();

    }

}
public void jumpDown()
{
    sprite.setY(sprite.getY()-1);
}

The ball is actually moving upward but it's not coming down again. Should I also call jumpDown() in the render() method?

2

2 Answers

2
votes

The official wiki libgdx lifecycle states that game logic updates are also done in the render() function. So, yes you should also call jumpDown() there. I would however propose that you keep it simple and only use one function like this:

private Texture ballTexture;
private Sprite  ballSprite;
private SpriteBatch batch;
private dirY = 2;

create(){
  ballTexture = new Texture("football.jpg");
  ballSprite = new Sprite(ballTexture);
  batch = new SpriteBatch();
}

render(float delta){
  recalculateBallPos(delta);          
  batch.begin();
  sprite.draw(batch);
  batch.end();
  stage.draw();    
}

private void recalculateBallPos(delta){
  float curPos = ballSprite.getY();

  if(curPos + dirY > 100 || curPos + dirY < 0){
    dirY = dirY * -1 //Invert direction 
  }

  ballSprite.setY(curPos+dirY)
}

This still might look a bit choppy but I hope it's a good way to start.

2
votes

The problem is the following:

Your Ball goes up, until it's y-value is exactly 100.0f. If thats the case, you decrease it by 1, which results in an y-value of 99.0f.
In the next render you call jumpUp again, which results in a y-value of 101. This time your condition is not met, the jumpDown() is not called.
Even if you change your condition to >= 100.0f, your Ball will always move up by 2 and down by 1, which results in an increasing y-value.
Instead you should call the method something like updateBallPos and store a boolean up.
In updateBallPos you can simply check the boolean up, if it is true, increase the y-value, if it is fales, decrease it.
Also you need to update this boolean up in the updateBallPos method:

if (up && sprite.getY() >= 100.0f)
    up = false
else if (!up && sprite.getY() <= 0.0f)
    up = true