2013-10-16 34 views
2

我正在关于精灵的教程: http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/ 我有一个精灵现在工作,但我喜欢精灵有更多的一个动画。那些动画应该取决于这个精灵应该具有的特定状态。Javascript和HTML5的画布精灵

我喜欢做的是在旧的苹果游戏空中创造伞兵。举例来说,请参阅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; 
} 

我怎样才能得到这个精灵有这些额外的动画选项?

感谢

回答

1

可以使用的偏移值指向针对每个区域:

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) ... 

可选您只需要使用不同的图像,每个动画,并使用相同的方法,但用指针来代替存储对象到要使用的图像。

+0

对于迟到的回复,我很抱歉。谢谢Ken,这非常有用。 – Smek