javascript - 创建精灵时如何避免重叠?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 不足以将它们分开,有些人告诉我创建一个网格,但就像我说的我是新手,搜索网格找不到任何我可以用来做这个的例子,谢谢你能帮助我:)
解决方案
一种选择是为每艘敌舰分配一个可以开始的特定区域。如果你有 2 艘船,这意味着第一艘船可以在 X 轴的前半部分的任何位置,第二艘船可以在 X 轴的后半部分的任何位置。
为此,您应该更新您的resetShip
函数以接受minX
and 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)
})
}
推荐阅读
- python - 更改包含字符串的列并替换行
- python - 如何使用 PyQt5 显示实时 OpenCV 视频源
- r - 根据 R 中存在的值添加新列
- java - Java JMenuBar 分布在窗口的整个宽度上
- javascript - 如何从 Node.js 中的工作簿中删除工作表?// 类型错误:无法读取未定义的属性“删除”
- cookies - 如何在不担心 GDPR 或 cookie 的情况下使用 Google Analytics?
- prolog - 使用 Prolog 库 Simplex 求解线性方程组
- javascript - 无法从响应标头访问访问令牌和 uid
- matlab - 使用 plot 命令绘制任何原始数据矩阵的任何段,x 轴为时间,y 轴为电压(实际数据)
- r - 使用 plotly 跨动画帧的恒定热图