我是 JS 和画布的新手,我正在尝试练习一下。我正在尝试创建一个垂直射击游戏,我希望敌人不仅以线性方式移动,而且还能上下移动(之字形)。到目前为止,我只能对线性运动进行编码,但我无法对振荡运动进行编码。这是我到目前为止编写的代码(检查 drawDucks 函数):
<html>
<head>
<script>
var c = new Object();
var ctx = new Object();
bg = new Image();
bg.src = "bg.jpg";
tank = new Image();
tank.src = "tank1.png";
duck = new Image();
duck.src = "duck_1.png";
gameCanvas =
{
tankPos : 221.5,
duckLeft : 0,
duckTop : 30,
getCanvas : function(id)
{
c = document.getElementById('canvas1');
ctx = c.getContext('2d');
setInterval(gameCanvas.drawDucks,2);
gameCanvas.drawGame();
gameCanvas.moveTank();
},
drawGame : function()
{
ctx.drawImage(bg,0,0);
ctx.drawImage(tank,gameCanvas.tankPos,400);
ctx.drawImage(duck,gameCanvas.duckLeft,gameCanvas.duckTop);
},
moveTank : function()
{
document.onkeydown = function(dir)
{
switch (dir.keyCode)
{
case 39:
{
if (gameCanvas.tankPos < 440)
{
gameCanvas.tankPos += 20;
gameCanvas.drawGame();
}
else
{
gameCanvas.tankPos;
}
break;
}
case 37:
{
if (gameCanvas.tankPos > 10)
{
gameCanvas.tankPos -= 20;
gameCanvas.drawGame();
break;
}
}
case 17:
{
gameCanvas.fire();
}
}
}
},
drawDucks : function()
{
if (gameCanvas.duckLeft < 512)
{
gameCanvas.duckLeft += 1;
}
else
{
gameCanvas.duckLeft = -75
}
gameCanvas.drawGame();
}
}
</script>
</head>
<body onload = 'gameCanvas.getCanvas()'>
<canvas id = 'canvas1' width='512px' height='480px'>
</canvas>
</body>
</html>