Handling keyboard interaction in a game loop - javascript

Viewed 301

I am playing with javascript and writing a simple game. I have a game loop set up and want to use the arrow keys to interact with the game. I have defined an event handler to handle keyboard interaction and placed this before and outside the main game loop, along with the definition for the game interval (tick) timer:

document.addEventListener("keydown", function(event) {
    var_to_modify = processKeys(event);
});

let gameTimer = window.setInterval(function() {
    gameLoop();
}, gameSpeed);

function gameLoop() {
    ...
}

The game loop ticks over nicely but the problem is this: how can I take the result of the processKeys() function and use it to modify a variable that is used inside the gameLoop() function? I know this can be achieved using a global, e.g. a game state variable, but is there a more elegant solution without using a global variable? Ta!

1 Answers

have a closure around game loop :

function generateGameLoop() {
let param = 0; //or any default value
let setParam = function (newParam) { 
param = newParam;
//here add any logic to respond to event
};
let gameLoop = function() {
    ...
}
return {setParam, gameLoop};
}

let setParam, gameLoop = generateGameLoop();

document.addEventListener("keydown", function(event) {
    setParam(processKeys(event));
});

let gameTimer = window.setInterval(function() {
    gameLoop();
}, gameSpeed);

I would also rename gameLoop as gameStep or gameIncrement or whatever.

(code might be wrong but the goal is to give you an idea)

Related