我正在以下网站上查看有关精灵的教程:http : //www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/我现在有一个精灵正在工作,但我喜欢该精灵有不止一个动画。这些动画应取决于此精灵应具有的特定状态。
我想做的是在旧的苹果机载游戏中创造伞兵。有关示例,请访问http://www.youtube.com/watch?v=pYujWCNUuNw您会看到这些士兵从砍刀中掉出来。当他们在地上时,他们站了一段时间,然后不时地开始行走。
这是我的精灵方法:
function sprite(options) {
var that = {},
frameIndex = 0,
tickCount = 0, ticksPerFrame = options.ticksPerFrame || 0, numberOfFrames = options.numberOfFrames || 1;
that.x = options.x, that.y = options.y,
that.context = options.context;
that.width = options.width;
that.height = options.height;
that.image = options.image;
that.update = function() {
tickCount += 1;
if (tickCount > ticksPerFrame) {
tickCount = 0;
// If the current frame index is in range
if (frameIndex < numberOfFrames - 1) {
// Go to the next frame
frameIndex += 1;
} else {
frameIndex = 0;
}
}
};
that.render = function() {
// Draw the animation
that.context.drawImage(that.image,
frameIndex * that.width / numberOfFrames,
0,
that.width / numberOfFrames,
that.height, that.x,
that.y,
that.width / numberOfFrames,
that.height);
};
return that;
}
我怎样才能让这个精灵有那些额外的动画选项?
谢谢
您可以使用指向每个区域的偏移值:
var offsets = [0, animation2x, animation3x, ...];
然后,当您使用代表偏移数组索引的整数值更改动画类型时,您可以执行以下操作:
var animation = 1;
hat.context.drawImage(that.image,
offsets[animation] + frameIndex * that.width / numberOfFrames,
....
您可能需要或想要向偏移添加其他信息,该信息也可能是包含帧数,大小等的对象。
一个伪示例可能如下所示:
var offsets = [{offset:0, frames:12, w:100, h:100},
{offset:1200, frames:7, w: 90, h:100},
...];
...
var offset = offsets[animation];
hat.context.drawImage(that.image,
offset.offset + frameIndex * offset.w / offset.frames,
....
if (frameIndex > offset.frames) ...
(可选)您为每个动画使用不同的图像,并使用相同的方法,而是存储带有指向要使用的图像的指针的对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句