我正在做一个学校作业,使用 HTML5 画布和 Javascript 制作一个小游戏。这个想法是基于太空入侵者,但有风筝(我知道真的很糟糕)。所以我让风筝通过按键移动,现在我希望它在按下左右键时显示不同的图像(风筝向左和向右弯曲)。
我在屏幕上看到了左边的风筝图像,但它也显示了正常的风筝。左右按键也没有区别。
我需要添加另一个函数来单独绘制左侧风筝吗?或者当 key 为 true 时添加 if 语句绘制图像?这可能都是错误的,但我有点卡在这里。
这是我的代码
const FPS = 30;
var canvas = null;
var context = null;
window.onload = init ;
function init() {
canvas = document.getElementById('gameCanvas');
context = canvas.getContext('2d');
setInterval(loop, 1000 / FPS);
// register keyboard events
window.addEventListener("keydown", onKeyDown);
window.addEventListener("keyup", onKeyUp);
// Initialize the player object
player.vx = 0;
player.vy = 0;
player.image = new Image();
player.image.src = "./kite.png";
player.imgLeft = new Image();
player.imgLeft.src = "./kite-links.png";
player.x = canvas.width/2 - player.image.width/2;
player.y = canvas.height/1.3 - player.image.height/2;
player.speed = 10;
}
var player = Object(); // Initialize a player object
// Things to do when keys are down
function onKeyDown(event)
{
if (event.keyCode >= 37 && event.keyCode<=39)
event.preventDefault(); // prevent arrow keys from scrolling the page
switch (event.keyCode) {
case 37: player.vx = -1; break; // left key pressed
case 38: player.vy = -1; break; // up key pressed
case 39: player.vx = 1; break; // right key pressed
}
}
// Things to do when keys are up
function onKeyUp(event)
{
switch (event.keyCode) {
case 37: case 39: player.vx = 0; break; // left or right key released
case 38: player.vy = 0; break; // up or down key released
}
}
function update(){
// update all your objects here
player.x += player.vx * player.speed; // update player position
player.y += player.vy * player.speed;
}
function draw(){
// clear the screen
context.clearRect(0, 0, canvas.width, canvas.height);
// draw all your objects here
context.drawImage(player.image, player.x, player.y, player.image.width, player.image.height);
context.drawImage(player.imgLeft, player.x, player.y, player.image.width, player.image.height);
}
function loop() {
update();
draw();
}