cleaned up / modernized some syntax

game-container-alex
alex swanson 1 year ago
parent 5d334756b6
commit c8f0fbcc5b
  1. 44
      game.js

@ -39,45 +39,43 @@ gamewindow.addEventListener('tick', (e) => {
// https://stackoverflow.com/questions/3691461/remove-key-press-delay-in-javascript
// Set 0 or null for no repeat at repeat arg
function KeyControl(keys, repeat) {
var KeyControl = (keys, repeat) => {
// this object holds the timers for each key on keydown - ex. timers[key] is an interval
var timers = {};
var timers = {}
// When key is pressed and we don't already think it's pressed, call the
// key action callback and set a timer to generate another one after a delay
//
document.onkeydown = function(event) {
var key = (event || window.event).keyCode;
document.onkeydown = (event) => {
var key = (event || window.event).keyCode
if (!(key in keys))
return true;
return true
if (!(key in timers)) {
timers[key] = null;
keys[key]();
timers[key] = null
keys[key]()
if (repeat != 0)
timers[key] = setInterval(keys[key], repeat);
timers[key] = setInterval(keys[key], repeat)
}
return false;
return false
};
// Cancel timeout and mark key as released on keyup
//
document.onkeyup = function(event) {
var key = (event || window.event).keyCode;
console.log(timers)
document.onkeyup = (event) => {
var key = (event || window.event).keyCode
if (key in timers) {
if (timers[key] != null)
clearInterval(timers[key]);
delete timers[key];
clearInterval(timers[key])
delete timers[key]
}
};
// Case for unfocused windows, prevent keys from getting "stuck down" if user leaves windows
//
window.onblur = function() {
window.onblur = () => {
for (key in timers)
if (timers[key] != null)
clearInterval(timers[key]);
timers = {};
clearInterval(timers[key])
timers = {}
};
};
@ -85,25 +83,25 @@ function KeyControl(keys, repeat) {
// https://zeamedia.info/helper/javascript-key-codes-char-codes.php
KeyControl({
// W
87: function() {
87: () => {
player.y += 10
updatePlayer()
},
// A
65: function() {
65: () => {
player.x -= 10
updatePlayer()
},
// S
83: function() {
83: () => {
player.y -= 10
updatePlayer()
},
// D
68: function() {
68: () => {
player.x += 10
updatePlayer()
},
// Spacebar
32: function() { console.log("pressed key SPACE") }
32: () => { console.log("pressed key SPACE") }
}, 1)

Loading…
Cancel
Save