我正在完成一项学校作业,使用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();
}
答案 0 :(得分:1)
您可以将所需的每个图像(向上,向右和向左)保存为播放器对象的属性,并在玩家改变方向时更改主图像(正在绘制的图像)。
INIT:
//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