如何使用libGdx项目反弹球

时间:2015-03-03 09:48:30

标签: java android libgdx

我正在尝试使用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);
}

球实际上向上移动,但它没有再次下降。 我还应该使用jumpDown()方法拨打render()吗?

2 个答案:

答案 0 :(得分:2)

官方维基libgdx 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)
}

这仍然看起来有些不稳定,但我希望这是一个很好的开始方式。

答案 1 :(得分:2)

问题如下:

你的Ball上升,直到它的y值正好是100.0f。如果是这种情况,则将其减1,这将导致y值为99.0f 在下一个render中,您再次致电jumpUp,这会导致y值为101。 这次您的条件不符合,jumpDown()未被调用 即使您将条件更改为&gt; = 100.0f,您的Ball也会一直向上移动2并向下移动1,这会导致y值增加。
相反,您应该调用类似updateBallPos的方法并存储boolean upupdateBallPos中,您只需检查boolean up,如果确实如此,则增加y值,如果是fales,则减少它。
您还需要使用boolean up方法更新此updateBallPos

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