问题
when you add event listener to an object and moved outside that object event.phase == "ended"
will not be trigger because it detected outside the object.
my question: is there a way we can detect event.phase == "ended"
even if the user releases the touch outside the object or is there any other way we can detect if the user has lifted their finger without using Runtime event listener?
回答1:
You can try the following method:
local bg = display.newRect(0,0,display.contentWidth,display.contentHeight)
local rect = display.newRect(100,200,100,100)
rect:setFillColor(0)
local isRectTouched = false;
local function bgTouch_function(e)
if(isRectTouched == true and e.phase == "ended")then
isRectTouched = false;
print("Started on Rect and ended outside")
end
end
bg:addEventListener("touch",bgTouch_function)
local function rectTouch_function(e)
if(e.phase == "began" or e.phase == "moved")then
isRectTouched = true;
print("began/moved .... rect")
else
isRectTouched = false;
print("ended .... rect")
end
end
rect:addEventListener("touch",rectTouch_function)
Keep coding.................. 😃
回答2:
I would recommend using the built in setfocus method which will allow you to bind a touch event to a specific display object. Which allows you to get events even if you move off the object. You can read up on this method here Happy coding.
local function bind(event)
if event.phase=='began' then
display.getCurrentStage():setFocus(event.target)
end
if event.phase=='moved' or event.phase=='began' then
elseif event.phase=='ended' then
display.getCurrentStage():setFocus(nil)
-- Whatever you want to do on release here
end
end
来源:https://stackoverflow.com/questions/17231748/touch-event-detection-issue