我试着在画布上做一个简单的游戏。我使用setTimeout()函数为英雄制作了动画。我用moove(E)功能检查按下的键:
当我第一次按下leftarrow或rightarrow时,一切都很正常,但是英雄没有移动。任何对代码的建议都是值得感谢的。
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。
在标记体onkeydown=' moove (event)‘onkeyup='moove(event)’中调用moove函数。
您可以在此处查看该项目:https://github.com/Fabulotus/Fabu/tree/master/Canvas%20game%20-%20dodge%20and%20jump
发布于 2018-10-09 05:16:42
第一次不起作用的原因是,第一次将位置设置为之前的位置(x = image.xx
),然后在绘制后更新x。应该在调用drawImage
之前更新x值x -= 1.2
发布于 2018-10-10 20:53:12
下面是你的代码的“工作”版本:
var cns = document.getElementById("can");
cns.height = 170;
cns.width = 600;
var ctx = cns.getContext("2d");
var hero = new Image();
hero.src = "http://swagger-net-test.azurewebsites.net/api/Image";
hero.onload = function() {
ctx.drawImage(hero, cns.width-10, cns.height/2);
hero.xx = cns.width-10;
hero.yy = cns.height/2;
};
var intervalL, intervalR, intervalLL, intervalRR;
var keys = [];
function goLeft(img) {
function f() {
ctx.beginPath()
ctx.clearRect(0, 0, cns.width, cns.height);
ctx.drawImage(img, img.xx, img.yy);
img.xx--;
if (img.xx < -img.width) {
img.xx = cns.width;
}
}
if (!intervalL) {
intervalL = setTimeout(function run() {
f();
intervalLL = setTimeout(run, 5);
}, 5);
}
}
goLeft(hero)
<canvas id="can">
正如您所看到的,function goLeft
已经大大简化了。
一个建议:避免太多的setTimeout
和clearTimeout
,而是使用一个setInterval来调用一个绘制函数,该函数负责绘制游戏上的所有内容,所有其他函数应该只更新gameObjects的位置。
https://stackoverflow.com/questions/52709927
复制相似问题