将玩家位置设置为接触墙边界,而不是将位置移动任意量到相对于墙的未知位置。
您还需要在计算中包括播放器的大小。
我将假设 map.tSizeX
和map.tSizeY
是图块大小,并且玩家移动了一个称为的量this.speed
(我在示例中添加了)并且玩家有一个 size this.sizeX
,this.sizeY
(我也在下面的示例中添加了)
例子
移动玩家然后解决碰撞
// assuming x,y is player top left
this.sizeX = 7; // size of player
this.sizeY = 7;
this.speed = 4; // speed of player any value will do
this.move = function(moveX, moveY) {
const left = map.tSizeX;
const top = map.tSizeY;
const right = gameCanvas.width - map.tSizeX - this.sizeX; // Includes player size
const bottom = gameCanvas.height - map.tSizeY - this.sizeY; // Includes player size
this.x += moveX;
this.y += moveY;
if (this.x < left) { this.x = left }
else if (this.x > right) { this.x = right }
if (this.y < top) { this.y = top }
else if (this.y > bottom) { this.y = bottom }
}
// Best would be to call this.move from the location you call the following functions.
// eg where you have the call this.moveUp() replace with this.move(0, -this.speed);
// these are just here to make it compatible with any existing code.
this.moveUp = function() { this.move(0, -this.speed) }
this.moveDown = function() { this.move(0, this.speed) }
this.moveLeft = function() { this.move(-this.speed, 0) }
this.moveRight = function() { this.move(this.speed, 0) }