p5.js 中的弹跳球未激活条件语句

Conditional statement not activated for bouncing ball in p5.js

我对 JavaScript 和 p5.js 完全陌生。我知道这不是最有效的弹跳球代码,但我尝试编写自己的弹跳球机制作为自学。

function draw() {
    background (col); // background
    col = map(cir.x, 0, 600, 0, 255) // map function

    fill (350, 200, 200);
    ellipse (cir.x, cir.y, cir.diameter, cir.diameter);

    // Bounding ball mechanic
    var speed = 3;
    var hitRightWall = false;
    var hitLeftWall = false;

    if (cir.x >= 300) {
        hitRightWall == true;
        hitLeftWall == false;
    }
    else if (cir.x <= -50) {
        hitLeftWall == true;
        hitRightWall == false;
    }
    if (hitRightWall==true) {
        speed == -3;
    }
    else {
        speed == 3;
    }
    cir.x = cir.x + speed;
}

由于某种原因,if (hitRightWall==True) 条件从未被激活,即使 if (cir.x >= 300) 已被激活。球继续向右移动并离开屏幕。

这里发生了一些事情。首先,您要将每帧的 hitRightWallhitLeftWall 的值重置为 false。是你想要的吗?

其次,看这样的语句:

hitRightWall == true;

== 双等号是比较,不是赋值。你可能想要这样的东西:

hitRightWall = true;

= 单个等号为变量赋值。

最后,我完全不确定您为什么需要这些变量。不能在第一个 if / else if 语句中直接修改 speed 变量吗?

无耻的自我推销:here是碰撞检测的教程。它是为处理而写的,但同样的想法也适用于 P5.js.