Search code examples
javascriptjoystick

Why does the x & y values not increment?


I am building a virtual joystick and this is part of the code that I made so that when the joystick is in between a certain value the x and y value will keep on incrementing by a certain value for instance when the joystick is between 1 and 20 for deltaX it will keep incrementing every second once or if it is in between 21 and 40 it will increment twice every second and I want it to keep incrementing and not staying at the same value of two. When I try this code, the x & y values just stick to 1, 2 or 3 and doesn't increment, could anyone suggest why this happens?

edit: The If statements need to be outside the function as the joystick breaks and doesn't run if its inside.

       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);
            })();
        }

Solution

  • When your code executes, joystick.deltaX() and joystick.deltaY() more likely have a value of 0, so no timeout is ever set.

    Also, avoid so many ifs when you can just replace them with a division.

    Why not use an interval?

    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)