Michael Herbert Michael Herbert - 6 months ago 14
Javascript Question

Why my key commands are not working

My issue is that my javascript is not seeing when i push my key down to move the object on the screen.
So here is my java script code:

var canvas = document.getElementById("maincanvas");
var context = canvas.getContext("2d");

var keys = [];

var width = 500, height = 400, speed = 3;

var player = {
x: 10,
y: 10,
width: 20,
height: 20
};

window.addEventListener("keydown", function(e){
keys[e.keycode] = true;
}, false);
window.addEventListener("keyup", function(e){
delete keys[e.keycode];
}, false);
/*
up - 38
down - 40
left - 37
right - 39
*/

function game(){
update();
render();
}

function update(){
if(keys[38]) player.y-=speed;
if(keys[40]) player.y+=speed;
if(keys[37]) player.x-=speed;
if(keys[39]) player.x+=speed;
}

function render(){
context.clearRect(0, 0, 100, 100)

context.fillRect(player.x, player.y, player.width, player.height);
}

setInterval(function(){
game();
}, 1000/30);


if you can not tell i am very new to this and just learning the basics.

Answer

The value you want out of the event object is called keyCode, not keycode:

var canvas = document.getElementById("maincanvas");
var context = canvas.getContext("2d");

var keys = [];

var width = 500,
  height = 400,
  speed = 3;

var player = {
  x: 10,
  y: 10,
  width: 20,
  height: 20
};

window.addEventListener("keydown", function(e) {
  keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e) {
  delete keys[e.keyCode];
}, false);
/*
up - 38
down - 40
left - 37
right - 39
*/

function game() {
  update();
  render();
}

function update() {
  if (keys[38]) player.y -= speed;
  if (keys[40]) player.y += speed;
  if (keys[37]) player.x -= speed;
  if (keys[39]) player.x += speed;
}

function render() {
  context.clearRect(0, 0, 100, 100)

  context.fillRect(player.x, player.y, player.width, player.height);
}

setInterval(function() {
  game();
}, 1000 / 30);
<canvas id="maincanvas"></canvas>

Comments