Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
Player Speeding Up In JavaScript Game

Every single time I move with the right or left arrows keys or A or D, the player speeds up. I don't want this to happen. I want the player to move at the same speed whenever you press the move key. I have no idea why this is happening. Here is my code:

class Player {
    constructor(x, y, color, width, height, health, strength, type, speed) {
        this.x = x;
        this.y = y;
        this.color = color;
        this.width = width;
        this.height = height;
        this.health = health;
        this.strength = strength;
        this.type = type;
        this.speed = speed;
    }
    draw() {
        c.beginPath();
        c.rect(this.x, this.y, this.width, this.height);
        c.fillStyle = this.color;
        c.fill();
        c.stroke();
    }
    moveLeft(){
        this.x -= this.speed;
    }
    moveRight(){
        this.x += this.speed;
    }
    moveUp(){
        this.y += this.speed;
    }
}

var x = canvas.width / 2;
var y = canvas.height / 2;
var left = false;
var up = false;
var right = false;
var left2 = false;
var up2 = false;
var right2 = false;
var pressing;

var player = new Player(x, y, 'red', 30, 30, 100, 30, 'basic', 2);
player.draw();


document.addEventListener('keydown', function(e) {
    switch (e.keyCode) {
        case 37:
            left = true;
            setInterval(function pressing(){ 
            if(left2===false && left === true){   
                player.moveLeft();
            }
            },10) 
            break;

        case 65:
            left2 = true;
            setInterval(function pressing(){ 
            if(left===false && left2 === true){   
                player.moveLeft();
            }
            },10) 
            break;

        case 39:
            right = true;
            setInterval(function pressing(){ 
            if(right2===false && right === true){   
                player.moveRight();
            }
            },10) 
            break;
    
        case 68:
            right2 = true;
            setInterval(function pressing(){ 
            if(right===false && right2 === true){   
                player.moveRight();
            }
            },10) 
            break;   
            

            
    }
});

document.addEventListener("keyup", event => {
    clearInterval(pressing);
    if (event.keyCode === 37) { 
        left = false; 
    }
    if (event.keyCode === 65) {
        left2 = false;    
    }
    if (event.keyCode === 39) {
        right = false;    
    }
    if (event.keyCode === 68) {
        right2 = false;    
    }

});

I followed many tutorials but couldn't find a different easy way to move my player. Does anyone have another strategy for moving or know why this isn't working?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

On every keypress you are currently creating a new interval that is never stopped. So what you are actually doing is to create duplicate intervals each time the key is pressed. As a first, rough fix you could try to store the return value of setInterval in a variable outside of the scope of the key event handler and check whether you have earlier intervals running. If so, clear them up before going ahead.

As clearInterval does not throw any error when fed un-intervalish values, you don't even have to check before clearing:

enter image description here

let myInterval = null

document.addEventListener('keydown', (e) => {
  // Clean up any earlier mess.
  clearInterval(myInterval)

  // Create new mess.
  myInterval = setInterval(() => { /* do something */ }, 10)
}) 

about 4 years ago · Juan Pablo Isaza Report

0

I think that you already have the answer...
You are creating multiple intervals that are never stopped.

But I would not use the interval in the key events, instead use just one outside to draw at certain frequency, then use a more mathematical approach to move and set the speed of the player on those events, we don't need different functions to move left or right, all we need is the correct speed value, positive increases (moves right), negative decreases (moves left) ... here is the code:

class Player {
    constructor(pos, speed) {
        this.pos = pos
        this.speed = speed
    }
    draw() {
        this.pos.x += this.speed.x
        this.pos.y += this.speed.y
        c.clearRect(0, 0, canvas.width, canvas.height)
        c.beginPath()
        c.rect(this.pos.x, this.pos.y, 20, 20)
        c.fill()
    }
}

let canvas = document.getElementById("game")
let c = canvas.getContext("2d")

var player = new Player({ x: 60, y: 50 }, { x: 0, y: 0 })
setInterval(() => player.draw(), 50)

document.addEventListener("keydown", function (e) {
    switch (e.keyCode) {
        case 37:
        case 65:
            player.speed.x = -1
            break

        case 39:
        case 68:
            player.speed.x = 1
            break
    }
})

document.addEventListener("keyup", function (e) {
    switch (e.keyCode) {
        case 37:
        case 65:
        case 39:
        case 68:
            player.speed.x = 0
            break
    }
})
<canvas id="game"></canvas>

I did simplify a lot of your code to keep this example small...
If you are really serious about building a JS game you should look at some of the game engines:
https://github.com/collections/javascript-game-engines
Those are some of the most popular open source ones

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!