2017-01-14 170 views
0

我一直在試圖找到/創建在Libgdx的矩形碰撞檢測,但我似乎無法得到任何地方。我有一個長方形,稱爲桶,寬64高,長方形稱爲牆,寬64高。我試圖讓玩家不穿過矩形,可以繼續移動,同時堅持牆逐步或隨機傳送。我的方法工作時,有1塊,但是當有多個,它只是打破,不工作。Libgdx矩形牆碰撞

我知道這個方法是醜陋的,但它只是試驗

private void checkCollisions(Rectangle bucket, Wall wall){ 
    if(bucket.overlaps(wall.getRectangle())){ 
     if(bucket.x > wall.getRectangle().x - 64 && bucket.x < wall.getRectangle().x - 55){ 
      //collision with right side 
      bucket.x = wall.getRectangle().x - 64; 
     } 
     if(bucket.x < wall.getRectangle().x + 64 && bucket.x > wall.getRectangle().x + 55){ 
      //collision with left side 
      bucket.x = wall.getRectangle().y + 64; 
     }       
     if(bucket.y < wall.getRectangle().y + 64 && bucket.y > wall.getRectangle().y + 55){ 
      //collision with top side 
      bucket.y = wall.getRectangle().y + 64; 
     }        
     if(bucket.y > wall.getRectangle().y - 64 && bucket.y < wall.getRectangle().y - 55){ 
      //collision with bottom side 
      bucket.y = wall.getRectangle().y - 64; 
     } 
    } 
} 

,我會很感激,如果有人可以點我在正確的方向或分享一些代碼,會幫助我。

回答

1

LibGDX查看碰撞檢測時,您必須首先注意默認LibGDX座標系的兩個重要方面。

  • 當繪製一個圖像,它的(X,Y)座標是圖像
  • (0,0)的底部左側是屏幕

使用這種底部左側信息我們可以修復邏輯碰撞到以下:

private void checkCollisions(Rectangle bucket, Wall wall){ 
    if(bucket.overlaps(wall.getRectangle())){ 
     if(bucket.x + 64 > wall.getRectangle().x && bucket.x < wall.getRectangle().x){ 
      //collision with right side of bucket 
     } 
     if(bucket.x < wall.getRectangle().x + 64 && bucket.x > wall.getRectangle().x){ 
      //collision with left side of bucket 
     }       
     if(bucket.y + 64 > wall.getRectangle().y && bucket.y < wall.getRectangle().y){ 
      //collision with top side of bucket 
     }        
     if(bucket.y < wall.getRectangle().y + 64 && bucket.y > wall.getRectangle().y){ 
      //collision with bottom side of bucket 
     } 
    } 
} 

該方法將確定哪個剷鬥的側面檢測到碰撞與默認的LibGDX座標系。