2014-03-29 55 views
0

我想做一個簡單的平臺遊戲,顯然我需要瓷磚碰撞。到目前爲止,代碼的問題在於它首先移動角色,然後檢查它是否與某件事發生衝突,但有時它會認爲它在不正確的時間發生碰撞,這取決於我是否首先檢查x軸是否發生了碰撞或者首先是y軸。我是否以這種錯誤的方式去做?這裏有一些代碼。如何做基於瓷磚的碰撞

function checkCollision(val, axis, oldPos) 
    if axis == "x" and char.tX then 
     local tileX = math.ceil(val/absoluteTileSize) 
     local tileY = math.floor(oldPos/absoluteTileSize) 

     local tl, tr, bl ,br = getTouchingTiles(tileX, tileY) 
     local isOnFlatSurface = math.abs(oldPos/absoluteTileSize-tileY) <= .00001--might not be a good i 

     if isOnFlatSurface then 
      if tr.canCollide then 
       char.tX = nil 
       char.x = tileX * absoluteTileSize - absoluteTileSize 
      end 
     else 
      if br.canCollide then 
       char.tX = nil 
       char.x = tileX * absoluteTileSize - absoluteTileSize 
      end 
     end 
    elseif axis == "y" then 
     local tileX = math.ceil(oldPos/absoluteTileSize) 
     local tileY = math.floor(val/absoluteTileSize) 

     local tl, tr, bl ,br = getTouchingTiles(tileX, tileY) 

     if bl.canCollide or br.canCollide then 
      char.tY = nil 
      char.y = tileY * absoluteTileSize --// - absoluteTileSize 
      --/////////////idk why i don't need to subtract that but it works 
     elseif not char.tY then--start falling if walk off something 
      char.tY = love.timer.getTime() 
      char.yi = char.y 
      char.vyi = 0 
     end 
    end 
end 

回答

0

當地tileX = math.ceil(VAL/absoluteTileSize)
當地tileY = math.floor(oldPos/absoluteTileSize)

這似乎很奇怪,你會使用math.ceil爲y的x值和math.floor。這可能是你出現一些奇怪現象的原因。我會推薦這個小的調試技巧,可以幫助你:

-- Since you are using LÖVE, this is what you would use: 
love.graphics.setColor(255, 0, 0, 255) 
love.graphics.rectangle('line', (tileX - 1) * absoluteTileSize, (tileY - 1) * absoluteTileSize, absoluteTileSize, absoluteTileSize) 
-- assuming absoluteTileSize represents the width/height of the tiles? 

這會去你的繪圖功能的結束,將在「平鋪」畫一個紅色的框您的播放器是目前內。