大家好,
我目前在按 [space] 键时无法使箭头键正常工作。按住 [space] 键和其中一个箭头键时一切正常。但是,如果我尝试同时按 [space] 并按住 [up] 和 [left],它会直接到屏幕顶部,就好像 [left] 键甚至没有被按下一样(它应该沿对角线移动到左上角)。这只会在按下 [space] 时发生。以后我想用这个键射击子弹。
我的代码有问题吗?或者它是某种错误?
为我糟糕的英语道歉:/ ..
<!DOCTYPE html>
<body>
<canvas id="myCanvas" width="568" height="262">
</canvas>
<script type="text/javascript">
var canvas;
var ctx;
var dx = 0.5;
var dy = 0.5;
var x = 284;
var y = 130;
var WIDTH = 568;
var HEIGHT = 262;
var keys = new Array();
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.fill();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
window.addEventListener('keydown',doKeyDown,true);
window.addEventListener('keyup',doKeyUp,true);
return setInterval(draw, 1);
}
function draw() {
move();
clear();
ctx.fillStyle = "white";
ctx.strokeStyle = "black";
rect(0,0,WIDTH,HEIGHT);
// player ///
ctx.fillStyle = "purple";
circle(x, y, 20);
}
function doKeyDown(evt)
{
keys[evt.keyCode] = true;
evt.preventDefault(); // Prevents the page to scroll up/down while pressing arrow keys
}
function doKeyUp(evt){
keys[evt.keyCode] = false;
}
function move() {
if (32 in keys && keys[32]){
; // fire bullets
}
if (38 in keys && keys[38]){ //up
y -= dy;
}
if (40 in keys && keys[40]){ //down
y += dy;
}
if (37 in keys && keys[37]){ //left
x -= dx;
}
if (39 in keys && keys[39]){ //right
x += dx;
}
}
init();
</script>
</body>
</html>