如何使用 libGdx 项目弹起球

How to bounce a ball using libGdx project

我正在尝试使用 libGDX 游戏引擎在 android 项目中弹球。

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

跳转函数如下所示:

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

    }

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

球实际上在向上移动,但它不会再下降了。 我还应该在 render() 方法中调用 jumpDown() 吗?

官方wikilibgdx lifecycle表示游戏逻辑更新也是在render()函数中完成的。所以,是的,你也应该在那里打电话给 jumpDown() 。但是,我建议您保持简单,只使用一个这样的函数:

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

这可能看起来有点不稳定,但我希望这是一个好的开始方式。

问题如下:

您的 Ball 上升,直到它的 y 值正好是 100.0f。如果是这样,您将它减 1,这将导致 y 值为 99.0f。
在接下来的 render 中,您再次调用 jumpUp,这导致 y 值为 101。 这次不满足你的条件,jumpDown()没有调用。
即使您将条件更改为 >= 100.0f,您的 Ball 也将始终向上移动 2 并向下移动 1,这会导致 y 值增加。
相反,您应该调用类似 updateBallPos 的方法并存储 boolean up.
updateBallPos你可以简单地检查boolean up,如果是真的,增加y值,如果是假的,减少它。
您还需要在 updateBallPos 方法中更新此 boolean up

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