"英雄"需要在左/右键下水平翻转(坐标或新的精灵,无关紧要)。包括draw和keyDown部分。左/右键输入时,确切地将坐标偏移或新精灵去哪里?提前致谢。
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
heroReady = true;
};
heroImage.src = "hero.png";
var owlReady = false;
var owlImage = new Image();
owlImage.onload = function () {
owlReady = true;
};
owlImage.src = "owl.png";
var hero = {
speed: 256,
x: 0,
y: 0
};
var owl = {
x: 0,
y: 0
};
var keysDown = {};
addEventListener("keydown", function (e) {
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function (e) {
delete keysDown[e.keyCode];
}, false);
var reset = function () {
hero.x = canvas.width / 2;
hero.y = canvas.height / 2;
var update = function (modifier) {
if (38 in keysDown) {
hero.y -= hero.speed * modifier;
}
if (40 in keysDown) {
hero.y += hero.speed * modifier;
}
if (37 in keysDown) {
hero.x -=hero.speed * modifier;
}
if (39 in keysDown) {
hero.x +=hero.speed * modifier;
}
//collision
if (
hero.x <= (owl.x + 35)
&& owl.x <= (hero.x + 35)
&& hero.y <= (owl.y + 35)
&& owl.y <= (hero.y + 35)
) {
++owlsCaught;
reset();
}
};
//DRAW
var render = function () {
if (bgReady) {
context.drawImage(bgImage, 0, 0);
}
if (heroReady) {
context.drawImage(heroImage, hero.x, hero.y);
}
if (owlReady) {
context.drawImage(owlImage, owl.x, owl.y);
}
//game loop
var main = function () {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
render();
then = now;
requestAnimationFrame(main);
};
//play
var then = Date.now();
reset();
main();
</script>
答案 0 :(得分:0)
只需使用带负片的scale()
方法来翻转坐标系。在这样做的意义上,你还需要考虑“负面”,即你在负面方向上移动角色,并且在执行此操作后实际向正方向移动。
示例:
ctx.scale(-1, 1); // flip hor.
ctx.drawImage(img, -x - img.width, 0); // use neg. position -image width
ctx.scale(-1, 1); // flip back to normal
<强> FIDDLE 强>
你当然可以通过创建一个大小与图像大小不同的离屏画布,翻转轴,绘制图像翻转并使用离屏画布作为图像源来制作角色。
更新(对于显示的新代码)
您可以使用标志来了解英雄目前面向的方向:
var flipped = false;
if (37 in keysDown) {
hero.x -=hero.speed * modifier;
flipped = true;
}
if (39 in keysDown) {
hero.x +=hero.speed * modifier;
flipped = false;
}
然后在渲染功能中:
if (heroReady) {
if (flipped) {
context.scale(-1, 1);
context.drawImage(heroImage, -hero.x - heroImage.width, hero.y);
context.scale(-1, 1);
}
else {
context.drawImage(heroImage, hero.x, hero.y);
}
}