2011-10-22 202 views
-2

我有這樣的事情:2D遊戲瓷磚的碰撞檢測

 // checking on which tile are players corners 
     // ignore this big mess below, please. It can be put in smaller 
     // equations, but for now it does its job 
     left_downX = ((int)Position.X)/32 * 32/32 - map.mapOffsetX/32 * 32/32; 
     left_downY = ((int)Position.Y + height)/32 * 32/32 - map.mapOffsetY/32 * 32/32; 

     right_downX = ((int)Position.X + width)/32 * 32/32 - map.mapOffsetX/32 * 32/32; 
     right_downY = ((int)Position.Y + height)/32 * 32/32 - map.mapOffsetY/32 * 32/32; 

     left_upX = ((int)Position.X)/32 * 32/32 - map.mapOffsetX/32 * 32/32; 
     left_upY = ((int)Position.Y)/32 * 32/32 - map.mapOffsetY/32 * 32/32; 

     right_upX = ((int)Position.X + width)/32 * 32/32 - map.mapOffsetX/32 * 32/32; 
     right_upY = ((int)Position.Y)/32 * 32/32 - map.mapOffsetY/32 * 32/32; 

     // checking if there is collision and responding to it 
     if (map.mapData[left_downX, left_downY] == (int)Map.Tiles.air && 
      map.mapData[left_upX, left_upY] == (int)Map.Tiles.air) 
     { 
      if (keyboardState.IsKeyDown(Keys.A)) 
      { 
       Speed.X = playerSpeed; 
       Direction.X = MOVE_LEFT; 
      } 
     } 
     if (map.mapData[right_downX, right_downY] == (int)Map.Tiles.air && 
      map.mapData[right_upX, right_upY] == (int)Map.Tiles.air) 
     { 
      if (keyboardState.IsKeyDown(Keys.D)) 
      { 
       Speed.X = playerSpeed; 
       Direction.X = MOVE_RIGHT; 
      } 
     } 
     if (map.mapData[left_downX, left_downY] == (int)Map.Tiles.air && 
      map.mapData[right_downX, right_downY] == (int)Map.Tiles.air) 
     { 
      if (keyboardState.IsKeyDown(Keys.S)) 
      { 
       Speed.Y = playerSpeed; 
       Direction.Y = MOVE_DOWN; 
      } 
     } 
     if (map.mapData[left_downX, left_downY] == (int)Map.Tiles.air && 
      map.mapData[right_downX, right_downY] == (int)Map.Tiles.air) 
     { 
      if (keyboardState.IsKeyDown(Keys.W)) 
      { 
       Speed.Y = playerSpeed; 
       Direction.Y = MOVE_UP; 
      } 
     } 

而且因爲它似乎正常工作,它沒有。例如,當玩家與地面碰撞時,它會停留在地面上,不能移動到任何方向。
僅當與側面的瓷磚碰撞時,情況類似,但在那裏,您可以移動到另一側。

我錯了什麼? 也許有更好的方法來檢查碰撞沒有循環所有瓷磚?

回答

1

代碼的前8行應該替換爲一個Rectangle對象,它應該與您的Sprite具有相同的大小/位置。

然後你可以調用Rectangle.Intersects方法針對你正在檢查碰撞的瓷磚。

+0

但它很好地檢查了碰撞,我也不想循環遍歷所有的瓦片。我的迴應有問題,因爲玩家只是站在棍子上,或者在某些情況下漂浮在牆壁上,有時甚至只是幻燈片。 – Neomex

+0

使用基於Tile的地圖最好的辦法是隻檢查碰撞對象附近的Tiles。這應該很容易處理相關對象的座標。對我而言,您的播放器因爲碰撞無法正常工作而卡住了。 – jgallant