Cole McNeil
Cole McNeil

Reputation: 1

keycode event not working with no error for canvas

I am trying to make the square move with the S key and the SPACE key... the only one that works is the S key... I have tried a great deal of things such as looking for errors (and i did not see any errors) so im really not sure what to try next. If you have any help of any kind please let me know.

I made sure the code is right thanks for helping!

document.addEventListener("keydown", keyDown)
document.addEventListener("keyup", keyUp)

var canvas = document.getElementById("myCanvas")
var ctx = canvas.getContext("2d")
ctx.fillStyle = "red"
var NX = 35
var Yspeed = 0
var Xspeed = 0
var Xpos = 10
var Ypos = 10
setInterval(draw, 50)
console.log(Xpos)

function keyUp(evt) {
  if (evt.keyCode == 32) Xspeed = 0
}

function keyDown(evt) {
  if (evt.keyCode == 32) Xspeed = 2
}

function keyUp(evt) {
  if (evt.keyCode == 83) Yspeed = 0
}

function keyDown(evt) {
  if (evt.keyCode == 83) Yspeed = 2
}

function draw() {
  ctx.clearRect(0, 0, 999, 999)
  Xpos = Xpos + Xspeed
  Ypos += Yspeed
  ctx.fillRect(Xpos, Ypos, 20, 20)
  ctx.fillStyle = "blue";
  ctx.fillRect(NX, 0, 50, 50)
}
<canvas id="myCanvas" width="800" height="600"></canvas>

Upvotes: 0

Views: 178

Answers (1)

Justin
Justin

Reputation: 2958

Your listeners are looking for a function called keyUp() and keyDown(). In JS the code is read top to bottom. Since you have declared the same function twice (two keyUp and two keyDown functions) the second one is overwriting the first. This means only keyCode 83 will be called.

You only need to declare the function once and put all keyCodes into the one function

function keyUp(evt) {
  if (evt.keyCode == 32) Xspeed = 0
  if (evt.keyCode == 83) Yspeed = 0

}

function keyDown(evt) {
  if (evt.keyCode == 32) Xspeed = 2
  if (evt.keyCode == 83) Yspeed = 2
}

Upvotes: 1

Related Questions