Nicholas Korte
Nicholas Korte

Reputation: 9

How to make a function get called faster

I am making a game of pong and want I have a working function that moves the paddles up and down. I want to call this function more often than it is called. The paddles move much too slowly and I don't want to increase the amount they move each time the function is called because that makes it "choppy"

I have tried to use a set interval but to no luck I just got an error.

document.body.addEventListener("keypress", function(e) {
    getWasdKey(e);
});

function getWasdKey(e){
  var key = e.keyCode;
  if(key == 119){//w key
    leftUp();//up
  }
  if(key == 115){//s key
    leftDown();//down
  }
  if(key == 107){//k key
    rightUp();//up
  }
  if(key == 109){//m key
    rightDown();//down
  }
}

var x = 1;
function leftUp(){
  setStyle('paddlewasd', 'top', (parseInt(getStyle('paddlewasd', 'top'))) - x + "px");
}
function leftDown(){
  setStyle('paddlewasd', 'top', (parseInt(getStyle('paddlewasd', 'top'))) + x + "px");
}
function rightUp(){
  setStyle('paddlearrow', 'top', (parseInt(getStyle('paddlearrow', 'top'))) - x + "px");
}
function rightDown(){
  setStyle('paddlearrow', 'top', (parseInt(getStyle('paddlearrow', 'top'))) + x + "px");
}

As a side note, I created a setStyle function to help make my code work better. It works properly and has before. It takes 3 parameters, id, css property, and what you want to set it to. Get style is just the first 2 parameters.Code Game

Upvotes: 0

Views: 80

Answers (1)

korona
korona

Reputation: 2229

You are currently relying on the keyboards repeat frequency, which can differ on different systems.

I would recommend that instead of listening for keypress events, you create a game loop using request​Animation​Frame, and in that loop you inspect the keyboards current state and react accordingly.

EDIT: Here's a minimalistic example demonstrating how you could do this

const keyState = {};

window.addEventListener('keydown', function (e) {
  keyState[e.keyCode] = true;
});

window.addEventListener('keyup', function (e) {
  keyState[e.keyCode] = false;
});

function frameLoop () {
  requestAnimationFrame(frameLoop);

  if (keyState[KEYCODE]) {
    // Do something
  }
}

requestAnimationFrame(frameLoop);

Upvotes: 1

Related Questions