在 Canvas 中进行碰撞检测后停止玩家移动

Stop Player Movement After Collision Detection In Canvas

我基本上在canvas做了两堵墙。一个在顶部,一个在底部。我的播放器由 MOUSE 控制,我想知道如何让播放器不穿墙。

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

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位置固定在顶墙和底墙之间。

在您的 mousemove 处理程序中(或玩家通过鼠标重新定位的任何位置):

// 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);