在javascript空间入侵者游戏中按箭头键时船只没有移动 [英] Ships not moving when pressing arrow keys in javascript space invaders game

查看:67
本文介绍了在javascript空间入侵者游戏中按箭头键时船只没有移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿大家,我目前正在创建一个javacript太空入侵者游戏,而且他偶然发现了一个问题。每当我按下右箭头键和左箭头键时,船只不会向右或向左移动。



这是我的代码

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

<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.

推荐答案

您已在Javascript论坛中发布此内容。请不要交叉。
You already posted this in the Javascript forum. Please do not crosspost.


这篇关于在javascript空间入侵者游戏中按箭头键时船只没有移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆