检测canvas边框上的碰撞

我正在和我的朋友们进行一场小游戏,但是当我碰到canvas的墙壁时,我正试图检测碰撞,我让它发挥作用,但是当我撞到墙壁时,我的角色卡住了……我不知道如何找到让他再次行动的方法。 你认为你们中的任何人都可以帮助我解决这个问题。 谢谢大家的帮助!

Javascript / jQuery:

function Player() { this.w = 50; this.h = 60; this.x = (cW / 2) - (this.w / 2); this.y = (cH / 2) - (this.h / 2); this.name = username.value; this.nw = ctx.measureText(this.name).width; // username.clientWidth + 1; this.src = playerImage; this.dx = 0; this.dy = 0; this.render = function() { ctx.drawImage(this.src, this.x, this.y, this.w, this.h); ctx.fillStyle = 'orange'; ctx.font = '15px Arial, sans-serif'; // fixa x-värdet ctx.fillText(this.name, (this.x + this.w / 2) - (this.nw / 2), (this.y - 6)); } } var player = new Player(); function animate() { if(player.x > 0 && player.y > 0 && player.x + player.w < cW && player.y + player.h < cH) { player.x += spd * player.dx; player.y += spd * player.dy; } else { // Need code here to release player from wall } ctx.save(); ctx.clearRect(0, 0, cW, cH); ctx.drawImage(bg, 0, 0); player.render(); ctx.rotate(-.4); raining(); ctx.restore(); } var animateInterval = setInterval(animate, 1000/60); document.addEventListener('keydown', function(e) { var key_press = String.fromCharCode(e.keyCode); switch(key_press) { case 'W': player.dy = -1; break; case 'A': player.dx = -1; break; case 'S': player.dy = 1; break; case 'D': player.dx = 1; break; default: break; } }); document.addEventListener('keyup', function(e) { var key_press = String.fromCharCode(e.keyCode); switch(key_press) { case 'W': player.dy = 0; break; case 'A': player.dx = 0; break; case 'S': player.dy = 0; break; case 'D': player.dx = 0; break; default: break; } }); 

您遇到的问题如下:

假设你的角色以每帧10个像素的速度移动,角色位置当前是595px(角色的右侧),canvas宽度是600。

在当前帧上,您正在检查是否存在碰撞:没有,因此您将速度添加到当前位置并获得605px。 现在在下一帧中,角色超出界限,你不能再移动他了,因为player.x + player.width> canvas.width

你可以做什么:

1:检查碰撞并将角色移回视口内:

 if (player.x + player.width > canvas.width) { player.x = canvas.width - player.width; } 

因为碰撞检查现在失败了,所以你可以随意移动他。

你应该检查所有的边,但每边的逻辑是不同的,这是与左墙碰撞的示例代码:

 if (player.x < 0) { player.x = 0; } 

2:在你的if语句中,你应该在计算中添加速度,如果player.x + player.vx超过canvas.width,则不要移动角色,但我更喜欢第一种方法,因为你实际上可以在视口的一侧

使用canvas位置的提示:始终在渲染级别舍入您的位置:

 this.render = function() { ctx.drawImage(this.src, Math.round(this.x), Math.round(this.y), this.w, this.h); ... }