使用带有多个sprite的sprite sheet [英] Using a sprite sheet with multiple sprites
问题描述
嘿,所以我有一个sprite表与多个sprites,我想使用动画网站
使用画布。
但我的问题
例如:
pre> 1 1 1 2
2 2 2 2
3 3 4 4
4 4 4 4
这里我有4个不同的sprites,我想动画。
我如何检索和动画正确的帧?
我使用的是javascript。
在spritesheet上检索和播放多个sprite
检索:创建一个定义每个精灵的x,y,width,height和保存数组中的对象的对象
sprite1.push({x:0,y:0,width:20,height:30});
sprite1.push({x:20,y:0,width:20,height:30});
sprite1.push({x:40,y:0,width:20,height:30});
//对sprite执行相同操作#2-4
播放框架:使用剪辑功能验证context.drawImage以播放一个精灵帧:
function playSpriteFrame(sprite,frameIndex,canvasX,canvasY){
//从sprite数组获取当前sprite
var s = sprite [frameIndex];
//在canvasX / canvas上绘制sprite在canvasX上
context.drawImage(
spritesheet,// spritesheet图片
sx,s ,y,s.width,s.height,// clip from spritesheet
canvasX,canvasY,s.width,s.height // draw to canvas
);
}
用法示例: #2 of sprite1 at canvas 100,100
//记住数组从元素0开始,所以框架#2在数组元素1
playSpriteFrame(sprite1,1,100,100);
你没有问如何创建一个动画循环, / p>
- 旧的方式将循环使用setInterval或setTimer
- requestAnimationFrame
Hey guys so I have a sprite sheet with multiple sprites that I want to use to animate a website using canvas.
However the problem I am having is I don't know how to go about reading in only the frames that I need.
Example:
1 1 1 2
2 2 2 2
3 3 4 4
4 4 4 4
Here I have 4 different sprites that I want to animate. How would I go about retrieving and animating the correct frames?
P.S I'm using javascript.
Retrieving and Playing multiple sprites on a spritesheet
Retrieving: Create an object defining each sprite's x,y,width,height and save the objects in an array
sprite1.push({x:0,y:0,width:20,height:30});
sprite1.push({x:20,y:0,width:20,height:30});
sprite1.push({x:40,y:0,width:20,height:30});
// do the same for sprites #2-4
Depending on your actual spritesheet, this code can be optimized--especially if the sprites are equally sized and spaced.
Playing a frame: Use the clipping verision of context.drawImage to "play" a sprite frame:
function playSpriteFrame(sprite,frameIndex,canvasX,canvasY){
// get the current sprite from the sprite array
var s=sprite[frameIndex];
// draw that sprite on the canvas at canvasX/canvasY
context.drawImage(
spritesheet, // the spritesheet image
s.x,s,y,s.width,s.height, // clip from spritesheet
canvasX,canvasY,s.width,s.height // draw to canvas
);
}
Example usage: Draw frame #2 of sprite1 at canvas 100,100
// Remember arrays start at element 0 so frame#2 is at array element 1
playSpriteFrame(sprite1,1,100,100);
You didn't ask about how to create an animation loop, but here is starter info anyway:
- the old way would be looping with setInterval or setTimer
- the new (better) way is with requestAnimationFrame
这篇关于使用带有多个sprite的sprite sheet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!