2014-06-26 126 views
0

我正在从事平台游戏,我遇到了一些碰撞检测问题。游戏设置了许多彼此相邻或间隔开的区块,以便玩家从一个区块跳到另一个区块。现在,玩家可以跳到积木的顶部,跑到积木的侧面,如果跳进积木的底部就会停下来。我现在遇到的问题是,如果我遇到一种罕见的情况,即玩家在某个区域的某个部分之上,则游戏将其识别为该区域旁边的区块的一侧,玩家穿过街区。所以如果我跳到块的边缘[3]并且块[4]紧靠它,游戏就认识到玩家已经跳到了块的边上[4]。任何想法如何我可以去解决这个问题?以下是我的碰撞检测代码。HTML 5碰撞检测平台游戏

function checkBlockCollisions() { 
    // If a player collides with a block, their motion should be stopped. 
for(var i = 0; i < blocks.length; i ++) { 
      var angle = blocks[i].angleTo(player); 
      var thisTop = blocks[i].y - blocks[i].height/2; 
      var thisBottom = blocks[i].y + blocks[i].height/2; 
      var playerTop = player.y - player.height/2; 
      var playerBottom = player.y + player.height/2; 

    if(blocks[i].collidesWith(player)) { 
     if((angle >= 55 && angle <= 360) && player.falling) { 
     // If the player is above the block, then they should stop falling. 
      player.falling = false; 
      player.onBlock = true; 
      player.setDY(0); 
       // Make sure the player is not inside the block. 
      player.setPosition(player.x, thisTop - player.height/2); 
       } 
        //top of block is lower than the middle of the player to the top and bottom of block is higher than the middle of the player to the bottom 
       if(thisTop > (player.y - player.height/2) && thisBottom < (player.y + (player.height/2))) { 
       // If the player runs into the side of a block, only stop the sideways motion. 
        player.setPosition(player.x - player.dx, player.y); 
        player.setDX(0); 
       } // end if 
       else if(player.falling) { 
       // If the player is below the block, then they should keep falling but stop accelerating upwards and sideways. 
        player.setDY(0); 
        player.setDX(0); 
        player.setPosition(player.x, thisBottom + player.height/2 + 1); 
       } // end if 
      } // end if 
     } // end for 
    } // end checkBlockCollisions 
+0

这个问题被问了很多。碰撞检测很难。如果你设法解决这个小错误,你会发现另一个,然后另一个,然后你的引擎将总是处于“工作99%的时间!只有tiiiiny bug,当$ stuff和weirdstuff发生时” 。恕我直言,唯一的出路是使用图书馆...去box2d – Exceptyon

回答