kylex
kylex

Reputation: 14406

Corona: trigger sprite on touch

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)

Upvotes: 0

Views: 1559

Answers (3)

Ali
Ali

Reputation: 1

just write:

instance1:addEventListener ("touch", kick)

instead of:

Runtime:addEventListener ("touch", kick)

Upvotes: 0

cctan
cctan

Reputation: 2023

use an anonymous function for one-time code
where you would code once and forget later:

instance1:addEventListener("touch", function(event)
  if(event.phase == "ended") then
    instance1:prepare("green")
    instance1:play()
  end
end)

do this when you want the function to be tied to the object,
and it may morph for different instances,
save the kick function under instance1 as one of its properties,
then add/remove it:

instance1.kick=function(event)
  if(event.phase == "ended") then
    instance1:prepare("green")
    instance1:play()
  end
end

instance1:addEventListener("touch",instance1.kick)

If the event handler is shared across different objects and used widely:

function kick( event )
  if(event.phase == "ended") then
    instance1:prepare("green")
    instance1:play()
  end
end

instance1:addEventListener("touch", kick)

Upvotes: 1

tomdemuyt
tomdemuyt

Reputation: 4592

please try

instance1:addEventListener( "touch" , kick )

or even

instance1:addEventListener( "tap" , kick )

Upvotes: 1

Related Questions