首页 > 解决方案 > 创建精灵时如何避免重叠?JS-PHASER3

问题描述

我是这方面的新手,我正在用 JS 制作一个小游戏,我现在遇到的问题是当我创建敌人时它有时会重叠,创建这个:

在此处输入图像描述

创建它们的方法很简单,

resetShip(enemy_spaceship) {
    enemy_spaceship.y = 0;
    enemy_spaceship.x = Phaser.Math.Between(10,globalThis.config.width);
}

在 X 中,每个精灵都会有一个从 10 到屏幕宽度(画布)的随机数,问题是如果一个精灵在 X 中具有 440,而另一个精灵在 X 中具有 450,那么这 10px 不足以将它们分开,有些人告诉我创建一个网格,但就像我说的我是新手,搜索网格找不到任何我可以用来做这个的例子,谢谢你能帮助我:)

标签: javascriptphaser-framework

解决方案


一种选择是为每艘敌舰分配一个可以开始的特定区域。如果你有 2 艘船,这意味着第一艘船可以在 X 轴的前半部分的任何位置,第二艘船可以在 X 轴的后半部分的任何位置。

为此,您应该更新您的resetShip函数以接受minXand maxX,并在定义它的位置时使用它:

resetShip (enemy_spaceship, minX, maxX) {
  enemy_spaceship.y = 0;
  enemy_spaceship.x = Phaser.Math.Between(minX, maxX);
}

然后,您需要找到一种方法来休息这组船,为每艘船提供有效区域。像这样的东西:

resetEnemies(ships) {
  //Each ship may be in a region that is 1/Nth of the width 
  let regionWidth = globalThis.config.width / ships.length
  //We need to know the shipWidth so we don't let ships get too
  //close to the left edge.
  let shipWidth = 64 

  ships.forEach((ship, i) => {
    //Assuming you just want padding on the left so it is no closer than 10px, 
    //this will define the minX for the Nth ship
    const minX = Math.min(10, i*regionWidth)
    //The maxX should not let a ship overlap the next region. So, we subtract the shipWidth
    //to ensure that, at worst, it is right next to the next ship
    const maxX = (i+1)*regionWidth-shipWidth

    //Use the updated restShip to put it in a valid location for it's region
    resetShip(ship, minX, maxX)
  })
}


推荐阅读