2017-08-06 51 views
0

为什么按下箭头键时第二个正方形会消失? 而不是消失第二个广场应该是第一个广场。我检查了每行代码,没有发现任何错误,我使用的浏览器是Google Chrome。为什么第二个正方形消失

这里是我的代码:

<!doctype html> 
    <html> 
    <head> 
    <title></title> 
    </head> 
    <body> 
    <canvas id="canvas" style="border:1px solid #000;"></canvas> 
    <script> 
    var canvas = document.getElementById("canvas"); 
    var ctx = canvas.getContext("2d"); 
    var width = 500; 
    var height = 500; 
    var win = false; 
    var player = { 
     x:250, 
     y:250, 
     speed:5, 
     width:100, 
     height:100 
    }; 
    var ai = { 
     x:150, 
     y:150, 
     mox:0, 
     moy:0, 
     speed:1, 
     width:50, 
     height:50 
    }; 
    canvas.width = width; 
    canvas.height = height; 
    ctx.fillRect(player.x, player.y, player.width, player.height); 
    ctx.stroke(); 
    ctx.fillRect(ai.x, ai.y, ai.width, ai.height); 
    ctx.stroke(); 
    function a() { 
     if(player.x < ai.x && win==false) { 
      ai.mox-=ai.speed; 
     } 
     if(player.x > ai.x && win==false) { 
      ai.mox = ai.speed; 
     } 
     if(player.y < ai.y && win==false) { 
      ai.moy -= ai.speed; 
     } 
     if(player.y > ai.y && win==false) { 
      ai.moy = ai.speed; 
     } 
     canvas.width = canvas.width; 
     var ctx = canvas.getContext("2d"); 
     ctx.fillRect(ai.x, ai.y, ai.width, ai.height); 
     ctx.stroke(); 
    } 
function move(e) { 
    // alert(e.keyCode); 
    if(e.keyCode==37) { 
     player.x -= player.speed; 
    } 
    if(e.keyCode==39) { 
     player.x += player.speed; 
    } 
    if(e.keyCode==38) { 
     player.y -= player.speed; 
    } 
    if(e.keyCode==40) { 
     player.y+=player.speed; 
    } 
    ai.x += ai.mox; 
    ai.y += ai.moy; 
    a(); 
    canvas.width = canvas.width; 
    var ctx = canvas.getContext("2d"); 
    ctx.fillRect(player.x, player.y, player.width, player.height); 
    ctx.stroke(); 
} 
document.onkeydown = move; 
</script> 
</body> 
</html> 

请告诉我什么是错我的代码。另外一个语法检查器告诉我它在语法上是正确的。

+0

请格式化您的代码,因此它实际上是人类可读的。那么我们可能会帮助你。 – MarthyM

回答

0

这有一些问题,我会在稍后讨论。 要立即解决您的问题,您需要添加

ctx.fillRect(ai.x, ai.y, ai.width, ai.height);

后,立即

ctx.fillRect(player.x, player.y, player.width, player.height);


好了,回到问题。大多数HTML5画布游戏都有一个tick函数,这个函数被称为每个x MS,但您似乎完全没有。代码中还有其他一些小问题,但我认为当你了解更多信息时,你将能够弄清楚这些问题。祝你好运:)

相关问题