سؤال

--up in the level1.lua
local target
--in the enter frame function of scene
function target:touch(event)
  if event.phase=="began" then
    local target=display.newImage("target.png",event.x,event.y)
    return true
  end
end
هل كانت مفيدة؟

المحلول

function target:touch(event)

You have not created target yet. You cannot assign a touch handler to an object that doesn't exist yet.

It sounds like what you need to do is add a touch handler to the stage. I would pre-create the image and just hide it using .isVisible = true. Then in your touch handler, show and hide the object. But regardless you have to put the touch handler on the whole screen and not an individual small image.

نصائح أخرى

Remove the "local" in target:touch: it hides the module local, using a variable local to target:touch(). Also, if you want image to disappear after touch done, use the "ended" and "cancelled" phases of touch event. Finally, I'm assuming that you initialized target to something but if not, you must add that too, otherwise how can you define touch:event (thanks to Rob for noticing this btw):

-- first create the target, but don't show it:
local target = display.newImage("target.png", 0, 0)
target.isVisible = false

--in the enter frame function of scene
function target:touch(event)
  if event.phase=="began" then
    target.x = event.x
    target.y = event.y
    return true
  else if event.phase == "ended" or event.phase == "cancelled" then
    if target ~= nil then 
        target:removeSelf()
        target = nil
    end
    return true
  end
end
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top