首页 > 解决方案 > 如果它们发生碰撞,如何删除数组中的两个游戏对象?

问题描述

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

标签: javascripthtmlgame-physics

解决方案


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

推荐阅读