【问题标题】:How can I avoid overlapping when creating sprites? JS - PHASER3创建精灵时如何避免重叠? JS-PHASER3
【发布时间】:2020-09-20 10:25:21
【问题描述】:

我是新手,我正在用 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 是不够的将它们分开,有些人告诉我创建一个网格,但就像我说的我是新手,搜索网格找不到任何我可以使用的示例,谢谢你能帮助我:)

【问题讨论】:

  • 您是要在更新期间避免它们之间的冲突,还是要确保它们最初不会被放置在重叠的位置?
  • 如果是在初始创建期间,您是否尝试创建 N 艘不同的船,每艘都不会重叠?

标签: javascript phaser-framework


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2013-02-06
    • 2019-11-05
    • 1970-01-01
    • 2013-03-24
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多