2015-03-03 43 views
0

我想在使用libGDX遊戲引擎的android項目中反彈球。如何使用libGDx項目反彈球

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

回答

2

官方wiki 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) 
} 

這仍然可能看起來有點震盪,但我希望這是一個良好的開端方式。

+0

這是不是導致'Ball',99和101之間來回跳躍,asthe方向總是反轉,如果pos = 100!? – Springrbua 2015-03-03 10:14:44

+0

哎呀,你是對的。我想寫<0.感謝您的領導。 – Nessuno 2015-03-03 10:16:26

+0

是的,我認爲是這樣xD無論如何,這是一個很好的答案,+1 – Springrbua 2015-03-03 12:30:00

2

的問題如下:

Ball上升,直到它的y值是完全100.0f。如果情況如此,則將其減1,這導致99.0f的y值。
在接下來的render中,您再次撥打jumpUp,這會導致y值爲101. 這次不符合您的條件,不會調用jumpDown()
即使您將條件更改爲> = 100.0f,您的Ball將始終向上移動2並減少1,這會導致y值增加。
相反,您應該調用類似updateBallPos的方法並存儲boolean up
updateBallPos你可以簡單地檢查boolean up,如果它是真的,增加y值,如果它是fales,減少它。
還需要在updateBallPos方法來更新這個boolean up

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

有趣的是,你如何指出他的代碼中的另一個錯誤,我完全錯過了。 – Nessuno 2015-03-03 12:51:55

+0

@Nessuno你可能錯過了這個錯誤,但是你的代碼完全可以解決它,並且很容易閱讀。 – Springrbua 2015-03-03 14:33:30