我正在努力改进我正在制作的html5游戏,我正试图将玩家对象的动作放入游戏中:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
theplayer = function(width, height, color, x, y)
{
this.width = width;
this.height = height;
this.color = color;
this.speedx = 0;
this.speedy = 0;
this.x = x;
this.y = y;
this.update=function()
{
context.fillStyle = color;
context.fillRect(this.x,this.y,this.width,this.height);
}
this.newpos=function()
{
this.x += this.speedx;
this.y += this.speedy;
}
}
var theplayer = new theplayer(30, 30, "red", 10, 120);
function clearboard()
{
context.clearRect(0,0,canvas.width,canvas.height);
}
function movement()
{
document.addEventListener("keydown",keyPressed, false);
document.addEventListener("keyup",keyLifted, false);
}
function keyPressed(event)
{
var keyPressed = String.fromCharCode(event.keyCode);
if (keyPressed == "W")
{
theplayer.speedx += 1;
}
else if (keyPressed == "D")
{
theplayer.speedy += 1;
}
else if (keyPressed == "S")
{
theplayer.speedx -= 1;
}
else if (keyPressed == "A")
{
theplayer.speedy -= 1;
}
}
var rungame = setInterval(function()
{
clearboard();
theplayer.newpos();
theplayer.update();
}, 20);
该程序应该让玩家用WASD键控制玩家对象,但是我无法让X和Y坐标的更改适用于玩家'反对' newpos'功能。我怎样才能解决这个问题,无论如何都要对WASD键进行多次按键击打?