1

我正在做一个学校作业,使用 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();
 }
4

1 回答 1

1

您可以将所需的每个图像(上、右和左)保存为播放器对象的属性,并在播放器改变方向时更改主图像(正在绘制的图像)。

在里面:

//default to straight in init()
player.image = new Image();
player.image.src = "./kite.png";
player.imgUp = new Image();
player.imgUp.src = "./kite.png";
player.imgLeft = new Image();
player.imgLeft.src = "./kite-links.png";
player.imgRight = new Image();
player.imgRight.src = "./kite-right.png";

onKeyDown:

switch (event.keyCode) {
    case 37: player.vx = -1; player.image = player.imgLeft; break; // left key
    case 38: player.vy = -1; player.image = player.imgUp; break; // up key
    case 39: player.vx = 1; player.image = player.imgRight; break; // right key
}

您也不需要像现在一样在 draw() 中绘制所有图像。你只需要画player.image

于 2013-03-21T15:28:28.380 回答