Corona: 当触摸时触发精灵

我想在触摸精灵时触发精灵动画,并且它只循环一次。

我有一个精灵动画,目前在屏幕触摸时触发,但我不知道如何使它只在触摸精灵本身时播放。

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 ) -- 在700ms内播放12帧
local instance1 = sprite.newSprite( spriteSet1 )
instance1.x = display.contentWidth/2
instance1.y = display.contentHeight/2.8

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

instance1:addEventListener("touch", kick)

原文链接 https://stackoverflow.com/questions/9011818

点赞
stackoverflow用户7602
stackoverflow用户7602

请尝试使用以下格式将其翻译成中文:

instance1:addEventListener( "touch" , kick )

或者

instance1:addEventListener( "tap" , kick )
2012-01-26 00:49:30
stackoverflow用户909233
stackoverflow用户909233

使用匿名函数来进行一次性代码,你只需要编写一次然后就可以忘记它了:

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

如果您想让函数与对象绑定,并且可能会变形为不同的实例,则将 kick 函数保存在 instance1 的属性之一下面,然后添加 / 删除它:

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

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

如果事件处理程序在不同的对象和场合下被广泛使用:

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

instance1:addEventListener("touch", kick)
2012-01-30 09:46:24
stackoverflow用户1645893
stackoverflow用户1645893
使用如下代码:

instance1:addEventListener ("touch", kick)


而不是:

Runtime:addEventListener ("touch", kick)


2012-09-04 10:25:59