Click here to Skip to main content
15,891,708 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hey everyone, I am currently creating a javacript space invaders game and hav stumbled upon a problem. Whenever I press the right and left arrow keys the ship does not move right or left.

Here is my code
JavaScript
<pre>
function startGame(){
    gamearea.start();
  }
  function movePlayer(event){
    if(!player.moving){
      moveInterval = setInterval(function(){player.move(event);}, 50);
      player.moving = true;
    }
  }
  function stopPlayer(event){
    clearInterval(moveInterval);
    player.moving = false;
  }
  var gamearea = {
    canvas: document.createElement("canvas"),
    start: function(){
      this.canvas.width = 1100;
      this.canvas.height = 600;
      this.canvas.style.border = "3px solid gray";
      this.canvas.style.display = "block";
      this.canvas.style.margin = "auto";
      document.body.insertBefore(this.canvas, document.body.childNodes[0]);
      this.context=this.canvas.getContext("2d");
      player.draw();
      window.addEventListener("keydown", movePlayer, event);
      window.addEventListener("keydown", stopPlayer, event);
    }
  }
  var player={
    x:40, y:580, moving:false,
    draw:function(){
      gamearea.context.fillStyle="ivory";
      gamearea.context.fillRect(this.x+60, this.y, 80, 20);
      gamearea.context.fillRect(this.x+95, this.y-20, 10, 20);
    },
    update: function(d){
      this.x+=d;
    },
    move: function(ev){
      gamearea.context.clearRect(this.x, this.y, 80, 20);
      gamearea.context.clearRect(this.x+35, this.y-20, 10, 20);
      if(ev.keycode== 37 && this.x>0) this.update(-15);
      else if(ev.keycode == 39 && this+80<1100) this.update(15);
      this.draw();
    }
  }


What I have tried:

I have not tried much but from what I did try is checking for errors in the inspection tab/console and re-writing my code in case of a spelling error.
Posted
Updated 31-Aug-18 22:36pm

1 solution

You already posted this in the Javascript forum. Please do not crosspost.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900