【问题标题】:How can I improve the collision detection in this vanilla JS TileMap game?如何改进这个香草 JS TileMap 游戏中的碰撞检测?
【发布时间】:2020-05-28 11:20:39
【问题描述】:

我正在创建一个基于 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

【问题讨论】:

  • 似乎您应该对除法计算进行四舍五入并仅比较整数阈值。

标签: javascript html5-canvas jstilemap


【解决方案1】:

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

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

我会假设map.tSizeXmap.tSizeY 是棋子大小,并且玩家移动了称为this.speed 的量(我已在示例中添加)并且玩家的大小为this.sizeX,@ 987654325@(我也在下面的例子中添加了)

示例

移动玩家然后解决碰撞

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

【讨论】:

  • 非常感谢!这实际上比我在做什么更有意义哈哈。我刚刚实现了上面的代码,完美无缺。 :D 我删除了 moveUp、moveDown 等功能。当我调用“move()”时,我必须引用“newPlayer.speed”而不是“this.speed”。这是一个错误还是它必须是这样的?
  • @MorganWalsh 如何以及在何处定义速度取决于您,这是您的风格而不是错误。 JS 中的错误是可以抛出的,停止执行,并会出现在 dev-tools -> 控制台(大多数浏览器上 F12 打开开发工具)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多