【发布时间】:2018-10-10 21:03:35
【问题描述】:
我正在尝试在画布中制作简单的游戏。我使用 setTimeout() 函数为英雄制作了动画。我用函数 moove(e) 检查按下的键:
当我第一次按左箭头或右箭头时,一切正常,但随后英雄不动。对代码的任何建议表示赞赏。
var cns = document.getElementById("can");
cns.height = 600;
cns.width = 300;
var ctx = cns.getContext("2d");
var hero = new Image();
hero.src = "images/hero.png";
hero.onload = function() {
ctx.drawImage(hero, 120, 570);
hero.xx = 120;
hero.yy = 570;
};
var intervalL, intervalR, intervalLL, intervalRR;
var keys = [];
function moove(e) {
keys[e.keyCode] = (e.type == "keydown");
if (keys[37]) {
clearTimeout(intervalR);
clearTimeout(intervalRR);
goLeft(hero);
} else {
clearTimeout(intervalL);
clearTimeout(intervalLL);
}
if (keys[39]) {
clearTimeout(intervalL);
clearTimeout(intervalLL);
goRight(hero);
} else {
clearTimeout(intervalR);
clearTimeout(intervalRR);
}
}
function goLeft(img) {
var x = img.xx,
y = img.yy;
function f() {
ctx.clearRect(img.xx, img.yy, img.width, img.height);
ctx.drawImage(img, x, y);
img.xx = x;
img.yy = y;
x -= 1.2;
if (x < -35) {
x = cns.width;
}
}
if (!intervalL) {
intervalL = setTimeout(function run() {
f();
intervalLL = setTimeout(run, 5);
}, 5);
}
}
函数 goRight 与 goLeft 类似。
函数 moove 在标记体中调用 onkeydown='moove(event)' onkeyup='moove(event)'。
您可以在这里查看项目:https://github.com/Fabulotus/Fabu/tree/master/Canvas%20game%20-%20dodge%20and%20jump
【问题讨论】:
-
什么叫
moove函数?在您的代码示例中看到这一点会很有帮助。什么时候向keys数组添加值? -
在正文中调用。已编辑。
标签: javascript canvas