javascript - 如果它们发生碰撞,如何删除数组中的两个游戏对象?
问题描述
我正在创建一个随机产生流星的游戏,我想摧毁相互碰撞的流星。我将我的流星放在一个数组中,当我想产生一颗流星时,我将 Meteor 类推到该数组中。我有我的 2D 碰撞算法,但我无法弄清楚如何选择要摧毁的流星的逻辑。这是我的流星类相关代码。谢谢你。
const meteorCollision = (a, aIndex, b, bIndex) => {
if (a !== undefined && b !== undefined) {
if (a.x < b.x + 50 &&
a.x + 50 > b.x &&
a.y < b.y + 50 &&
a.y + 50 > b.y) {
meteors.splice(aIndex, 1);
meteors.splice(bIndex, 1);
}
}
}
meteorCollision(meteor, meteorIndex, meteors[meteorIndex + 1], meteorIndex + 1);
const spawnMeteorP = () => {
setInterval(() => {
let x, y;
if (Math.random() < 0.5) {
x = Math.random() < 0.5 ? -50 : cvs.width + 50;
y = Math.random() * cvs.height;
} else {
x = Math.random() * cvs.width;
y = Math.random() < .5 ? -50 : cvs.height + 50
}
const angle = Math.atan2(rocketY - y, rocketX - x);
const velocity = {
x: Math.cos(angle),
y: Math.sin(angle)
}
meteors.push(new MeteorP(x, y, velocity))
}, 1500)
}
解决方案
我通过添加另一个 forEach 来映射数组中的所有项目来获得它。不确定这是否是最有效的解决方案,但这就是我想出的。
const meteorCollision = (a, aIndex,) => {
meteors.forEach((b, bIndex) => {
if (a !== undefined && b !== undefined && a !== b) {
if (a.x < b.x + 50 &&
a.x + 50 > b.x &&
a.y < b.y + 50 &&
a.y + 50 > b.y) {
meteors.splice(aIndex, 1);
meteors.splice(bIndex, 1);
meteorexp.play();
}
}
})
}
meteorCollision(meteor, meteorIndex);
推荐阅读
- python - 将 pandas 数据帧从 tsv 转换为 parquet
- python-3.x - 没有秒的Python格式本地化日期时间?
- sql-server - SQL Server 存储过程从链接服务器插入表并使用最大 ID 更新另一个表
- python - 在远程机器上运行测试并使用 pytest 捕获输出
- docker - 如何在 powershell 跨平台中捕获 docker 版本
- c# - Api 调用返回异常
- axios - Firebase Cloud Functions - 一次为多个用户提供服务
- c# - 索引超出范围错误。但是当我执行 item.count() 返回 1
- excel - 转置行后得到 6 列而不是 5 列
- python - Django 服务器重新加载不适用于每个 .py 文件