2013-10-16 35 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