1

我正在创建一个简单的基于 JS 画布图块的游戏,我知道它需要重构和更新我计划在我了解更多关于正在发生的事情时执行的语法。

我已经动态地创建了瓷砖尺寸,我认为这就是我苦苦挣扎的原因。碰撞检测并不精确,我很难让它更精确......所谓精确,我的意思是根据显示器的大小,碰撞不会撞到右墙,而是就在它之前或之后.

任何帮助/建议,或指向正确的方向,将不胜感激。

this.moveUp = function(){
    if(this.y > gameCanvas.height / 8){
        this.y -= 7;
    }
};

this.moveDown = function(){
    if(this.y < gameCanvas.height - map.tSizeY * 1.5){
        this.y += 7;
    }
    
};

this.moveLeft = function(){
    if(this.x > gameCanvas.width / 8){
        this.x -= 7;
    }
};

this.moveRight = function(){
    if(this.x < gameCanvas.width - map.tSizeX * 1.25){
        this.x += 7;
    }
}

Github 回购:https ://github.com/MrWalshy/jsLameTileGame

例如,蓝色方块与右墙碰撞

4

1 回答 1

2

将玩家位置设置为接触墙边界,而不是将位置移动任意量到相对于墙的未知位置。

您还需要在计算中包括播放器的大小。

我将假设 map.tSizeXmap.tSizeY是图块大小,并且玩家移动了一个称为的量this.speed(我在示例中添加了)并且玩家有一个 size this.sizeXthis.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) }
于 2020-02-13T15:30:04.600 回答