I am making a frogger replica and I want the frog to move only once when I press a key, basically to prevent it from moving multiple times if a key is held down.
This is the relevant part of my code that handles the keydown
event:
document.onkeydown = function(e) {
var key = e.which || e.keyCode;
if (key == 37){ frog.x = frog.x - 50; }
if (key == 38){ frog.y = frog.y - 50; }
if (key == 39){ frog.x = frog.x + 50; }
if (key == 40){ frog.y = frog.y + 50; }
};
Update:
I got it to not move when holding down keys, but now it won't let me move right after I moved right once, but will reset if I click another button, then does the same thing again:
const canvas = document.getElementById('canvas');
const c = canvas.getContext('2d');
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
let frog = {
x: 0,
y: 0,
fw: 50,
fh: 50,
fmx: 0,
fmy: 0,
};
let counter = 0;
function animate() {
requestAnimationFrame(animate);
// Clear previous scene:
c.clearRect(0, 0, window.innerWidth, window.innerHeight);
// Draw frog:
c.fillStyle = '#000'
c.fillRect(frog.x, frog.y, frog.fw, frog.fh);
// Movement of the frog with keys:
document.onkeydown = function(e) {
e = e || window.event;
var key = e.which || e.keyCode;
if (key == 65 && counter === 0) { frog.x = frog.x - 50, counter = 1 }
if (key == 87 && counter === 0) { frog.y = frog.y - 50, counter = 1 }
if (key == 68 && counter === 0) { frog.x = frog.x + 50, counter = 1 }
if (key == 83 && counter === 0) { frog.y = frog.y + 50, counter = 1 }
};
document.onkeyup = function(e) {
e = e || window.event;
var key = e.which || e.keyCode;
if (key == 65) { counter = 0 }
if (key == 87) { counter = 0 }
if (key == 68) { coutner = 0 }
if (key == 83) { counter = 0 }
};
}
animate();
body {
margin: 0;
}
#canvas {
width: 100%;
height: 100%;
}
<canvas id="canvas" />