在画布中检测到碰撞后停止播放器移动

Stop Player Movement After Collision Detection In Canvas

本文关键字:播放器 移动 碰撞 布中 检测      更新时间:2023-09-26

我基本上在画布上做了两面墙。一个在顶部,一个在底部。我的玩家被鼠标控制,我想知道如何让玩家不穿过墙壁。

以下是两个对象之间的一般碰撞的函数:

function collides(a, b) {
   var val = false;
   val = (a.x < b.x + b.width) &&
   (a.x + a.width > b.x) &&
   (a.y < b.y + b.height) &&
   (a.y + a.height > b.y);
   return val;        
}

以下是检测碰撞检测的代码:

if (collides(player, block)){
    //I don't know what goes here.
}

如有任何帮助,我们将不胜感激。

按照您已经做的操作重新定位播放器,并且将播放器的y位置固定为始终位于顶墙和底墙之间。

在鼠标移动处理程序中(或玩家被鼠标重新定位的位置):

// reposition the player as you already do
...
// and clamp the player to stay below the top wall
if( player.y < wall.y+wall.height ){ player.y = wall.y+wall.height);
// and clamp the player to stay above the bottom wall
if( player.y+player.height > wall.y ){ player.y = wall.y-player.height);