为什么当我按箭头键时,第二个方块消失了?第二个正方形应该跟随第一个正方形,而不是消失。我检查了每一行代码,没有一行代码出错,我使用的浏览器是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>请告诉我我的代码出了什么问题。还有一个语法检查器告诉我它在语法上是正确的。
发布于 2017-08-06 15:53:34
这有一些问题,我稍后再讨论这些问题。要立即修复问题,您需要添加
ctx.fillRect(ai.x, ai.y, ai.width, ai.height);
紧随其后
ctx.fillRect(player.x, player.y, player.width, player.height);
好了,回到问题上来。大多数HTML5 canvas游戏都有一个被称为每x MS的tick函数,你看起来根本就没有这个功能。代码中还有其他一些小问题,但我认为随着学习的深入,您将能够解决这些问题。祝你好运:)
https://stackoverflow.com/questions/45529587
复制相似问题