Reputation: 1058
I am creating a game, and in level 1 I want to load a few images that represent letters, and I want to add functionalities to them. One of them is the ability to move them.
So inside my enterScene is
function scene:enterScene(event)
...
letA = display.newImage("media/letters/A.png", display.contentWidth/4 - 20, display.contentHeight/5 - 18)
letC = display.newImage("media/letters/C.png", display.contentWidth/4 + 35, display.contentHeight/5 - 18)
letR= display.newImage("media/letters/R.png", display.contentWidth/4 + 90, display.contentHeight/5 - 18)
letE=display.newImage("media/letters/E.png", display.contentWidth/4 + 145, display.contentHeight/5 - 18)
screenGroup:insert(letA)
screenGroup:insert(letC)
screenGroup:insert(letR)
screenGroup:insert(letE)
letA:addEventListener("touch", letA)
letC:addEventListener("touch", letC)
letR:addEventListener("touch", letR)
letE:addEventListener("touch", letE)
now I added the moving function for letA, which is
function letA:touch(event)
if event.phase=="began" then
display.getCurrentStage():setFocus(self, event.id)
self.isFocus = true
self.markX = self.x
self.markY = self.y
elseif self.isFocus then
if event.phase=="moved" then
self.x = event.x - event.xStart + self.markX
self.y = event.y - event.yStart + self.markY
elseif event.phase=="ended" or event.phase == "cancelled" then
display.getCurrentStage():setFocus(self,nil)
self.isFocus = false
end
end
return true
end
Then when I try to get into the scene it gives me an error to the line of function letA:touch(event), it says "attempt to index global 'letA'.
What do I do then? I designed it like that because I want it when the user clicks Play, it would load the letters, and if he presses back, it will unload them from screen.
Upvotes: 0
Views: 194
Reputation: 4007
You can do this instead, you declare the touch function via ":" (colon) which letA or the other objects are not tables.
local letA = display.newImage("media/letters/A.png", display.contentWidth/4 - 20, display.contentHeight/5 - 18)
letA.touch = function(self,event)
if event.phase=="began" then
display.getCurrentStage():setFocus(self, event.id)
self.isFocus = true
self.markX = self.x
self.markY = self.y
elseif self.isFocus then
if event.phase=="moved" then
self.x = event.x - event.xStart + self.markX
self.y = event.y - event.yStart + self.markY
elseif event.phase=="ended" or event.phase == "cancelled" then
display.getCurrentStage():setFocus(self,nil)
self.isFocus = false
end
end
return true
end
letA:addEventListener("touch")
Upvotes: 1