2012-12-21 51 views
0

我已經提出了一些線程,要求與過去碰撞的幫助,並取得了一些進展,我正在製作一個2D Java遊戲,屏幕上的播放器隨鍵盤輸入一起移動,問題是,在我的背景(地圖)上有很多障礙,目前我的播放器只是直接穿過它們,到目前爲止,在本論壇的用戶的幫助下,我已經在代碼中獲得了此代碼以檢測碰撞:Java碰撞無法正常工作

public void changeBuckyPos(float deltaX, float deltaY) { 
    float newX = buckyPositionX + deltaX; 
    float newY = buckyPositionY + deltaY; 

    // check for collisions 
    Rectangle rectOne = new Rectangle((int)newX, (int)newY, 40, 40); 
    Rectangle rectTwo = new Rectangle(-100, -143, 70,70); 

    if (!rectOne.intersects(rectTwo)) { 
    buckyPositionX = newX;   
    buckyPositionY = newY;   
    } 
} 

當我把它放到我的遊戲中時,現在這個代碼沒有錯誤,但是發生了更大的問題,雖然這段代碼沒有錯誤,但它什麼也沒有做,我的意思是當我進入遊戲時,沒有碰撞,當兩人再次發生什麼事情時ctangles相交,任何人都可以幫助我,我一直堅持了很長時間。

謝謝。

+1

那麼......當兩個r長方形會見?您提供的代碼僅僅是這樣做的,如果新位置相交,那麼位置不會更新。 – SJuan76

+0

你如何使用這個功能? –

+0

調試方法,嘗試添加一些完整的日誌記錄並瀏覽結果。它被稱爲?它是否被正確的參數調用?它的輸出是否被使用?如此多的問題...... –

回答

0
  • 這是更好地保持着獨特的數據類型爲你的遊戲實體
  • 更新[類遊戲]應該在一個單獨的線程定期調用
  • 繪製在另一個線程還會定期

你遊戲邏輯應該是類似於(幾乎完整的Java Psydocode):

public class Block{ 
    int speedX; 
    int speedY; 
    Rectangle rect; 
    public void update(){ 
     rect.x+=speedX; 
     rect.y+=speedY; 
    } 
    public void draw(/*Graphics g..or somthing*/){ 
     //draw this single object 
    } 
    ..getters and setters.. 
} 

public class Game{ 
    List<Block> obstacles; 
    Block myBlock(); 
    ...... 
    void update(){ 
     ... 
     myBlock.update(); 
     for(Block ob: obstacles){    
      if(myBlock.getRect().intersects(ob.getRect())){ 
        processCollision(ob); 
      } 
      ob.update(); 
     } 
     ... 
    } 
    public void draw(/*Graphics g..or somthing*/){ 
      //background draw logic 
      myBlock.draw(g); 
      for(Block ob: obstacles) 
       ob.draw(g); 
    } 
    void processCollision(Rect ob){ 
      .. 
      do whatever you want with ob 
      .. 
    } 
}