【问题标题】:How to remove both game objects in an array if they collide?如果它们发生碰撞,如何删除数组中的两个游戏对象?
【发布时间】:2021-05-07 18:19:25
【问题描述】:

我正在创建一个随机产生流星的游戏,我想摧毁相互碰撞的流星。我将我的流星放在一个数组中,当我想产生一颗流星时,我将 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)
}

【问题讨论】:

  • 你的意思是meteors.splice(aIndex, 1) 不工作?
  • 我想检查流星之间的任何碰撞。如果流星按顺序排列,我的算法就会删除。

标签: javascript html game-physics


【解决方案1】:

我通过添加另一个 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);

【讨论】:

    猜你喜欢
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多