*tip* How to sync an event with a frame of animation

Here’s something I have been learning today. Say you have an animation, like a monster biting something, and you want to sync an event or sound to each bite. This is a common thing in gaming. It could be shooting, getting hit or whatever… Here’s the code I figured out that worked:

[lua]-- Hide status bar
display.setStatusBar(display.HiddenStatusBar);

– Set up the monster sprite animations

require “sprite”

local monster1 = sprite.newSpriteSheetFromData( “monster1.png”, require(“monster1”).getSpriteSheetData() )

local spriteSet1 = sprite.newSpriteSet(monster1,1,55)

sprite.add(spriteSet1,“attack”,1,30,1000,0)
sprite.add(spriteSet1,“walk”,31,25,1000,0)

– create a bite function that will trigger each frame

local function bite(event)
currentFrame = event.sprite.currentFrame;

if(currentFrame==10) then

– do something - play sound, reduce health etc

end
end
– spawn a monster

function spawnmonster(x,y)

local monster = sprite.newSprite( spriteSet1 )

monster:prepare(“attack”);
monster:play();

monster.x = x;
monster.y = y;

monster:addEventListener( “sprite”, bite);

end

spawnmonster(100,150);[/lua]

Obviously the cool part with this is the sprite event listener which can then be used to show the current frame:

event.sprite.currentFrame;

Hope this helps someone. :wink: Please let me know if I got anything wrong.

Tom [import]uid: 55068 topic_id: 11081 reply_id: 311081[/import]