Home > Enterprise >  Why is my player moving faster and faster when I use the controls. HTML web game
Why is my player moving faster and faster when I use the controls. HTML web game

Time:12-24

I am making an HTML5 web game and am in the process of making the player movement. I am not using any game engine, just pure HTML, CSS, and JavaScript. My problem is that whenever I load my game, it starts out fine where I can move around at normal speeds but if I move back and forth a few times, the player starts speeding up and if I keep doing this, it speeds up to unbearable speeds. I have no idea what is happening. How my code works is when the key d is pressed then in the keysPressed object D is set to true instead of false,

let keysPressed = {
'd': false,
'a': false,
'w': false,
's': false,   }

Then, it executes a function that moves the player.

function move() {
if (keysPressed['d'] == true) { // check if its right
    let player = document.querySelector('.player');
    var id = setInterval(frame, 20);
    function frame() {
        if (keysPressed['d'] == false) {
            clearInterval(id);
        } else {
            player.style.left = player.offsetLeft   2   'px';
        }
    }
}
if (keysPressed['a'] == true) { // check if its left
    let player = document.querySelector('.player');
    var id = setInterval(frame, 20);

    function frame() {
        if (keysPressed['a'] == false) {
            clearInterval(id);
        } else {
            console.log(player.offsetLeft)
            player.style.left = player.offsetLeft - 2   'px';
        }
    }
} 

}

I know that it isn't the cleanest code but I just wanna fix this bug first before tackling this.

Thanks

CodePudding user response:

You are calling setInterval many times over which is compounding and causing the symptom you're describing. I think you only need to call setInterval once, and then just change the left/right variables depending on the keypress.. something like

let intervalID, player = document.querySelector('.player'),
  dir, offset, isMoving = false;

function changeDirection(keysPressed) {
  if (!isMoving) move();
  if (keysPressed['d']) {
    dir = 'left';
    offset = 'offsetLeft';
  } else if (keysPressed['a']) {
    dir = 'right';
    offset = 'offsetRight';
  }
}

function move() { // called just once
  if (isMoving) return;
  isMoving = true;
  intervalID = setInterval(function() {
    player.style[dir] = ( player[offset]   2)   'px';
  }, 20);
}
  • Related