繁体   English   中英

为什么我的 JavaScript 浏览器游戏中的弹跳 Actor 不起作用?

[英]Why do bouncing Actors in my JavaScript browser game not work?

我想实现一个在太空中飞行的火箭,它会从传入的流星雨中反弹。 目前我已经通过比较两个演员的 x 和 y position 并在碰撞时交换他们的速度来实现它。 碰撞检测和速度交换确实有效(由 console.log 证明),但在屏幕上它们有时只会反弹。

我试图确保比较演员的速度对象不引用相同的 JavaScript object(使用cSpeedX等)。

游戏是用 Pixi JS 构建的。

碰撞检测function,为每个actor执行(所有流星和火箭)

export const checkCollision = (current, objects) => {
    objects.forEach((o) => {
        if (current !== o) {
            const dx =
                current.x < o.x
                    ? o.x - o.width / 2 - (current.x + current.width / 2)
                    : current.x - current.width / 2 - (o.x + o.width / 2);

            const dy =
                current.y < o.y
                    ? o.y - o.height / 2 - (current.y + current.height / 2)
                    : current.y - current.height / 2 - (o.y + o.height / 2);

            if (dx < 0 && dy < 0) {
                const cSpeedX = current.speed.x;
                const cSpeedY = current.speed.y;
                const oSpeedX = o.speed.x;
                const oSpeedY = o.speed.y;

                current.speed.x = oSpeedX;
                current.speed.y = oSpeedY;
                o.speed.x = cSpeedX;
                o.speed.y = cSpeedY;
            }
        }
    });

移动 function 在火箭和流星上实现

this.move = (delta) => {
            this.x += this.speed.x * delta;
            this.y += this.speed.y * delta;
        };
export const checkCollision = (current, objects) => {
    objects.forEach((o) => {
        if (current !== o) {

您还写了: The collision detection function, executed for each actor (all meteroids and the rocket)

所以我想某处也有类似的循环:

objects.forEach((o) => {
    checkCollision(o, objects);
});

这意味着对于每对对象,碰撞检查两次。

让我们假设o1o2是一些不同的对象,并且它们发生碰撞。 那时会发生什么?

checkCollision(o1, objects); <-- swap speed between o1 and o2
...
checkCollision(o2, objects); <-- swap speed between o2 and o1

因此速度将在它们之间交换 2 次 - 换句话说:两个对象的速度将保持不变。

要调查是否确实是这种情况,您可以像这样放置console.log (或打印对象 id 的东西):

            if (dx < 0 && dy < 0) {
                console.log('swapping speed of of objects:');
                console.log(current);
                console.log(o);
                const cSpeedX = current.speed.x;

然后准备 2 个对象碰撞时的情况并检查控制台日志。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM