Stopping drag objects going off screen

Hi,
I want to stop a drag object going off screen.
I’ve found a function to do this but its interfering with the next page and I’m wondering why or if there’s a better function I could use?
any help, greatly appreciated
Steve
[lua]local map = display.newImage (“images/map.png”)
map.x = 720
map.y = 980

function onTouch( event )
local t = event.target

local phase = event.phase
if “began” == phase then
display.getCurrentStage():setFocus( t )

t.isFocus = true

– Store initial position
t.x0 = event.x - t.x
t.y0 = event.y - t.y
elseif t.isFocus then
if “moved” == phase then

t.x = event.x - t.x0
t.y = event.y - t.y0
elseif “ended” == phase or “cancelled” == phase then
display.getCurrentStage():setFocus( nil )
t.isFocus = false
end
end

return true
end
map:addEventListener( “touch”, onTouch )
local function wrapit (event)
if map.x < 10 then
map.x = 10
elseif map.x > 738 then
map.x = 738
elseif map.y < 10 then
map.y = 10
elseif map.y > 994 then
map.y = 994
end
end[/lua] [import]uid: 97656 topic_id: 17343 reply_id: 317343[/import]

Please post your code in < lua > tags in the future so it’s easy to read.

I’ve found a function to do this but its interfering with the next page

Are you making sure to remove the runtime listener before changing scenes? It sounds like that’s probably the issue.

Peach :slight_smile: [import]uid: 52491 topic_id: 17343 reply_id: 65640[/import]

Will indeed Peach post in tags in future. Sorry, I’m a newbie.

So is it at the very end of my code where I place:
[lua] Runtime:removeEventListener(“enterFrame”, wrapit) [/lua]

or just after [lua] Runtime:addEventListener(“enterFrame”, wrapit) [/lua]
Thanks for your help.
p.s. Your tutorials are excellent! [import]uid: 97656 topic_id: 17343 reply_id: 65641[/import]

instead of adding another event listener you can put the function call inside your onTouch function:

  
.... elseif t.isFocus then  
 if "moved" == phase then  
  
 t.x = event.x - t.x0  
 t.y = event.y - t.y0  
 wrapit ()  
  
 elseif ....  

also you don’t need to send “event” as parameter to the wrapit function. you could use this for every display object you want.

local function wrapit (theObject)  
 local obj = theObject  
 if obj.x \< 10 then  
 obj.x = 10  
 elseif obj.x \> 738 then  
 obj.x = 738  
 elseif obj.y \< 10 then  
 obj.y = 10  
 elseif obj.y \> 994 then  
 obj.y = 994  
 end  
end  

the function call would look like:

wrapit ( t ) -- wrap the event target object  

cheers,
-finefin
[import]uid: 70635 topic_id: 17343 reply_id: 65646[/import]

Finefin,

Thank you so much. That worked like a dream and put a smile on my face!

Appreciate it,
Best,
Steve [import]uid: 97656 topic_id: 17343 reply_id: 65649[/import]