I’d like to trigger a sprite animation when it is touched, and only have it loop once.
I have a sprite animation that currently triggers on screen touch, but I don’t know how to make it so it only animates when the sprite itself is touched.
require "sprite"
local sheet1 = sprite.newSpriteSheet( "greenman.png", 75, 105 )
local spriteSet1 = sprite.newSpriteSet(sheet1, 1, 16)
sprite.add( spriteSet1, "green", 1, 12, 700, 1 ) -- play 12 frames every 700 ms
local instance1 = sprite.newSprite( spriteSet1 )
instance1.x = display.contentWidth/2
instance1.y = display.contentHeight/2.8
function kick( event )
if(event.phase == "ended") then
instance1:prepare("green")
instance1:play()
end
end
Runtime:addEventListener("touch", kick)
use an anonymous function for one-time code
where you would code once and forget later:
do this when you want the function to be tied to the object,
and it may morph for different instances,
save the
kickfunction underinstance1as one of its properties,then add/remove it:
If the event handler is shared across different objects and used widely: