Javascript画布动画精灵行走
我试图让一个精灵用画布在背景图像上行走。理想情况下,我会在一个画布上完成这一切,但使用两个画布似乎更有效、更容易 到目前为止,我所拥有的: 及 来自fiddle 1的代码,处理最简单的动画形式:Javascript画布动画精灵行走,javascript,animation,canvas,sprite,Javascript,Animation,Canvas,Sprite,我试图让一个精灵用画布在背景图像上行走。理想情况下,我会在一个画布上完成这一切,但使用两个画布似乎更有效、更容易 到目前为止,我所拥有的: 及 来自fiddle 1的代码,处理最简单的动画形式: var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var spritePosition = 0; var spriteWidth = 50; var spriteHeight = 2
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var spritePosition = 0;
var spriteWidth = 50;
var spriteHeight = 225;
var spriteCount = 17;
var spritePlayCount = 0;
var maxSpritePlays = 3;
var sheet = new Image();
sheet.onload = function () {
animate();
}
sheet.src = "https://s33.postimg.cc/dapcxzmvj/sprite_walk.png";
var fps = 15;
function animate() {
setTimeout(function () {
if (spritePlayCount < maxSpritePlays) {
requestAnimationFrame(animate);
}
// Drawing code goes here
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(sheet,
spritePosition * spriteWidth, 0, spriteWidth, spriteHeight,
0, 0, spriteWidth, spriteHeight);
spritePosition++;
if (spritePosition > spriteCount - 1) {
spritePosition = 0;
spritePlayCount++;
}
}, 1000 / fps);
}
var canvas=document.getElementById(“canvas”);
var ctx=canvas.getContext(“2d”);
变量spritePosition=0;
变量spriteWidth=50;
变量spriteHeight=225;
var-spriteCount=17;
var spritePlayCount=0;
var maxSpritePlays=3;
var sheet=新图像();
sheet.onload=函数(){
制作动画();
}
sheet.src=”https://s33.postimg.cc/dapcxzmvj/sprite_walk.png";
var fps=15;
函数animate(){
setTimeout(函数(){
if(spritePlayCountspriteCount-1){
spritePosition=0;
spritePlayCount++;
}
},1000/帧);
}
我希望能够让它正确行走,并理解它是如何工作的。我看到它们都使用了一些类似于
sprite.width
和sprite.height
的东西,我想它们应该是width/columns
和height/rows
,但它们似乎工作不正常。你的坐标都错了。您的“精灵宽度”和“精灵高度”值与您的所有值都不匹配
此外,您的逻辑仅更新x轴,而您的精灵工作表设置在多行上。您需要更新此逻辑,以便同时更新x和y源位置 最后,不要像那样混合使用setTimeout和requestAnimationFrame。他们总是相处不好。 要实现15FPS,您可以非常轻松地运行requestAnimationFrame循环,该循环将以60FPS的速度启动,并且只需每四帧绘制一次(60FPS/4=>15FPS)
var canvas=document.getElementById(“canvas”);
var ctx=canvas.getContext(“2d”);
var xIndex=0;
var-yIndex=0;
var-cols=5;
var行=4;
变量spriteWidth=265;
变量spriteHeight=200;
var sheet=新图像();
sheet.onload=函数(){
制作动画();
}
sheet.src=”https://i.stack.imgur.com/eL5yV.png";
var帧=0;
函数animate(){
请求动画帧(动画);
//60FPS/4=>15FPS
如果(++帧)%4>0,则返回;
clearRect(0,0,canvas.width,canvas.height);
//更新当前列
xIndex=(xIndex+1)%cols;
//如果x为0,则更新当前行
yIndex=xIndex==0?(yIndex+1)%rows:yIndex;
//最后一行有三个单元格是空的。。。
if(yIndex==(行-1)和&xIndex==2)
xIndex=yIndex=0;
//同时更新sourceX和sourceY
ctx.图纸图像(第页,
xIndex*spriteWidth,yIndex*spriteHeight,spriteWidth,spriteHeight,
0,0,spriteWidth,spriteHeight);
}
我使用的是我找到的模板,真的不确定如何将其更改为与我的spritesheet一起使用。你的答案澄清了很多,我只是想检查一下我是否正确地假设精灵的高度和宽度应该直接基于列和行的数量?此外,我还投票了,但当我能够将其放入我的代码中并查看时,我将接受!