为什么 x 和 y 值不增加?

Why does the x & y values not increment?

我正在构建一个虚拟操纵杆,这是我编写的代码的一部分,因此当操纵杆处于某个值之间时,x 和 y 值将继续增加某个值,例如当操纵杆对于 deltaX,它在 1 到 20 之间,它会每秒递增一次,或者如果它在 21 和 40 之间,它会每秒递增两次,我希望它保持递增而不是保持在相同的值 2。当我尝试此代码时,x 和 y 值只是固定为 1、2 或 3,并且没有增加,有人可以解释为什么会发生这种情况吗?

编辑: If 语句需要在函数外部,因为操纵杆会损坏,如果在内部则不会 运行。

       if (joystick.deltaX() >= 1 && joystick.deltaX() <= 20) {
            (function movex1() {
                x = x + 1;
                setTimeout(movex1, 1000);
            })();
        }

        if (joystick.deltaX() >= 21 && joystick.deltaX() <= 40) {
            (function movex2() {
                x = x + 2;
                setTimeout(movex2, 1000);
            })();
        }

        if (joystick.deltaX() >= 41 && joystick.deltaX() <= 60) {
            (function movex3() {
                x = x + 3;
                setTimeout(movex3, 1000);
            })();
        }

        if (joystick.deltaY() >= 1 && joystick.deltaY() <= 20) {
            (function movey1() {
                y = y + 1;
                setTimeout(movey1, 1000);
            })();
        }

        if (joystick.deltaY() >= 21 && joystick.deltaY() <= 40) {
            (function movey2() {
                y = y + 2;
                setTimeout(movey2, 1000);
            })();
        }

        if (joystick.deltaY() >= 41 && joystick.deltaY() <= 60) {
            (function movey3() {
                y = y + 3;
                setTimeout(movey3, 1000);
            })();
        }

当您的代码执行时,joystick.deltaX() 和 joystick.deltaY() 的值更有可能为 0,因此不会设置超时。

此外,当您可以用除法替换它们时,请避免使用这么多 if。

为什么不使用间隔?

var x = 0, y = 0;

// Execute every second
var intervalId = setInterval(function() {
    x += Math.ceil(joystick.deltaX() / 20);
    y += Math.ceil(joystick.deltaY() / 20);
}, 1000);

// Stop after 20 seconds
setTimeout(function() {
    clearInterval(intervalId);
}, 20000)