Touch function not working - lua

local Gin2
local function Gin ( event )
if ( event.phase == "began" ) then
Gin2 = display.newImage("PNGs/Sprite/Gin")
Gin2.x = _H
Gin2.y = _W
end
return true
end
Runtime:addEventListener("touch", Gin )
Hello, so I've been trying to figure out this for some time, but with with no success. So as may guess the idea is to spawn an image by touching.Should I define the object that will be touch?

I have made a code for you to use. When you want to spawn an object via touch listener (Either Runtime event or a single event) you can use event.x and event.y to determine the touch point of the user. Below is the code.
NOTE: I made gin as a array for future use of your spawned object
local val = 1
local gin = {}
local spawnObject = function(event)
if(event.phase == "ended") then
gin[val] = display.newImage("PNGs/Sprite/Gin")
gin[val].x = event.x
gin[val].y = event.y
val = val + 1
end
end
Runtime:addEventListener( "touch", spawnObject )

You are using the 'functional listener' form and for 'touch' event you should not be using Runtime.
In your case, you need to change Runtime to the object that 'is to be touched'. I guess what you want to do is to move the image once it is touched.
so, firstly move
Gin2 = display.newImage("PNGs/Sprite/Gin")
up and out the function. then change Runtime to Gin2.

Related

Coronasdk Issue with addeventListeners

recently I was coding a new game when I ran across a problem of which I cannot seem to be able to fix.
This is the code :
function newPower()
rand = math.random( 100 )
if (rand < 80) then
powerup = display.newImage("power.png");
powerup.class = "powerup"
powerup.x = 60 + math.random( 160 )
powerup.y = -100
physics.addBody( powerup, { density=0.9, friction=0.3, bounce=0.3} )
powerup:addEventListener( "touch", handlePowerTouch )
end
end
local function handlePowerTouch( event )
if event.phase == "began" then
currentScore = currentScore * 2
currentScoreDisplay.text = string.format( "%06d", currentScore )
event.target:removeSelf()
return true
end
end
local function spawnpowers()
-- Spawn a new powerup every second until canceled.
spawnPower = timer.performWithDelay( 1000, newPower, -1 )
end
Any help fixing this issue would be greatly appreciated!
The issue I'm having is when I click "run" or "play" the game starts working then crashes and displays this message:
addEventListener: listener cannot be nil: nil stack traceback:
?: in function 'addeventListener'
game.lua63: in function'_listener' <-- i have given you game.lua:63 above.
Thanks
powerup:addEventListener( "touch", handlePowerTouch )
Here handlePowerTouch is nil as the function definition follows after this line.
Move your function definition in front of that line, then it should work.
Btw, is there any reason why you have so many global variables? You should use local variables wherever possible.

Corona Sdk - Is there a way to call and group:insert() an object from another lua file?

As stated in the title I would like to not only call an object from an external Lua file, but I would also like to group:insert() this object into my Menu page with the properties given to it in the external lua file. Is this possible and/or efficient? I would just really like to make sure data isn't repeated through out my project.
EDIT
Here's my code so far:
The group:insert() function is throwing me an error stating it was expecting a table and that I might have been trying to call a function in which case i should use ":" instead of "."
This is menu.lua:
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local widget = require "widget"
local m = require ("myData")
local menuFunction = require("menuFunction")
local menuSwipe
-- =======================
-- menuSwipe()
-- =======================
menuSwipe = function(self, event)
local phase = event.phase
local touchID = event.id
if(phase == "began") then
elseif(phase == "moved") then
elseif(phase == "ended" or phase == "cancelled") then
if(m.menuActivator > 0) then
menuDown(m.invisiBar, event)
else
--m.layerInfo = layers
transition.to( menuFunction.menuBar, { x = menuFunction.menuBar.x, y = 0, time = 200 } )
--transition.to( layers, { x = menuFunction.menuBar.x, y = h, time = 100 } )
m.invisiBar = display.newRect( 0,0,w,25,6)
m.invisiBar.alpha = 0
m.menuActivator = 1
end
end
end
-- ++++++++++++++++++++++
-- menuDown()
-- ++++++++++++++++++++++
function menuDown(self, event)
local phase = event.phase
local touchID = event.id
if(phase == "began") then
elseif(phase == "moved") then
elseif(phase == "ended" or phase == "cancelled") then
if(m.menuActivator == 1) then
transition.to( menuFunction.menuBar, { x = m.menuInfo.x, y = h*.964, time = 200 } )
--transition.to( group, { x = 0, y = 0, time = 10 } )
m.menuActivator = 0
end
end
end
function scene:createScene( event )
local group = self.view
group:insert( menuFunction.menuBar ) -- *** ERROR occurs here
end
function scene:enterScene( event )
local group = self.view
end
function scene:exitScene( event )
local group = self.view
end
function scene:destroyScene( event )
local group = self.view
end
scene:addEventListener( "createScene", scene )
scene:addEventListener( "enterScene", scene )
scene:addEventListener( "exitScene", scene )
scene:addEventListener( "destroyScene", scene )
return scene
This is menuFunction.lua:
local m = require("myData")
local menu = require ("menu")
local w = display.contentWidth
local h = display.contentHeight
local menuFunction = {}
--menuBar
menuFunction.menuBar = display.newImage( "images/menuBar1.png")
menuFunction.menuBar.x = w*(1/2)
menuFunction.menuBar.y = h*1.465
menuFunction.menuBar.height = h
menuFunction.menuBar:setReferencePoint(display.TopLeftReferencePoint)
menuFunction.menuBar.touch = menu.menuSwipe
menuFunction.menuBar:addEventListener("touch", menuFunction.menuBar)
return menuFunction
This is the exact error message:
ERROR: table expected. If this is a function call, you might have used '.' instead of ':'
message**
Does this happen every time this code is called, or does it by any chance work the first time and then crashes? In your case, code could work the first time you enter the scene, but the second time you do, it may crash [if you remove scenes in between].
When you do a 'require' of a file, its contents are executed and returned value is saved in the global packages table. When you require the same file again, the returned value is taken from the global packages table instead, the code is not executed again.
So if you by any chance require this file in one spot of your app, and then call :removeSelf() and nil the reference of the menuBar, the display object will be removed and its reference will cease to exist, and calling the require again, will not recreate the object. Fully removing a scene will also remove the display objects.
So what you wanted to achieve is very sensible [contrary to what #Schollii says], but your "module" should allow creation of multiple objects if you want to get rid of them during runtime.
I'm not going to correct your code, just a simple example of how you can achieve this:
-- menu.lua
local menuCreator = {}
menuCreator.newMenu = function(params)
local menu = display.newGroup()
-- create your menu here
return menu
end
return menuCreator
Now anytime you do:
local menuCreator = require("menu.lua")
you will be able to call:
local menu = menuCreator.newMenu(someParams)
and get yourself a nice new menu wherever you need.
If it's not shown all the time on screen, it may be better to create a new one whenever you need it, and then remove it from the memory.
There are several issues with this, and none of them seem related to your error but fixing them will either also fix the error or make the cause of the error more obvious. Please fix following and update:
Although Lua allows it, don't use circular includes, where A includes B which includes A. Instead have menu require menuFunction and then call a creation function in menuFuntion:
-- menuFunction.lua
local m = require("myData")
-- require("menu") -- BAD! :)
local w = display.contentWidth
local h = display.contentHeight
local menuBar = display.newImage( "images/menuBar1.png")
menuBar.x = w*(1/2)
menuBar.y = h*1.465
menuBar.height = h
menuBar:setReferencePoint(display.TopLeftReferencePoint)
local menuFunction = { menuBar = menuBar }
function createMenuBar(menuSwipe)
menuFunction.menuBar.touch = menuSwipe
menuFunction.menuBar:addEventListener("touch", menuFunction.menuBar)
return menuFunction
end
-- menu.lua
function createScene(event)
local mf = require('menuFunction')
mfFunction = mf.createMenuBar(menuSwipe)
group:insert(menuFunction.menuBar)
end
Secondly out of the four calls to group:insert() the first 3 refer to objects that are not shown in the code and don't see relevant to problem, they should be removed or if you think relevant, comment why their code now shown, or show their code.

Add ID to listener after loading remote image

I have a listener for loading remote images, but I need to be able to pass an ID number to that listener, and I'm not really sure how to do it. My code to retrieve the remote image is:
display.loadRemoteImage("http://www.newyorker.com/online/blogs/photobooth/NASAEarth-01.jpg", "GET", networkListener, "banner.png",system.TemporaryDirectory, (globalData.contentX * rows2) + globalData.contentX/2, 20 + (i - 1) % 6 * 140
And the listener I have is:
local function networkListener( event )
if ( event.isError ) then
print ( "Network error - download failed" )
else
local target = event.target
target.alpha = 0
transition.to( target, { alpha = 1.0 } )
target.width = 590
target.height = 110
target:addEventListener( "touch", target )
scrollView:insert(target)
function target:touch(event)
if event.phase == "began" then
display.getCurrentStage():setFocus( self )
self.isFocus = true
elseif self.isFocus then
if event.phase == "moved" then
numMoved = numMoved + 1
if(numMoved > 10) then
display.getCurrentStage():setFocus( nil )
self.isFocus = false
scrollView:takeFocus( event )
end
elseif event.phase == "ended" or event.phase == "cancelled" then
globalData.selectedLocationID = target.id --This needs to be the ID that I pass to this listener
if(globalData.approvedToggle == 1) then
storyboard.gotoScene("businessScene")
else
storyboard.gotoScene("locationScene")
end
display.getCurrentStage():setFocus( nil )
self.isFocus = false
end
end
return true
end
end
Any help in this matter would be greatly appreciated, thanks!
I did this a while back on an Ecommerence app I was making. I'm not to familer with storyboard, but I do remember using this API. If I remember correctly, you need to use event.target as the event listener and pass everything through there. I also remember that you can embed a function inside of the display.loadRemoteImage API like this:
itemImage = display.loadRemoteImage(itemData.imageURL, "GET",
function(event)
event.target.xScale = 0.4
event.target.yScale = 0.4
function openSite(event)
if event.phase == "ended" then
system.openURL( itemData.itemURL )
end
end
event.target:addEventListener( "tap", openSite )
end)
My advice is remove all the story board stuff, and try making the API work in a different document. I think that you need to simplify it so you aren't confused.
Hopefully this helps.

Images doesn´t appear in storyboard Corona SDK

I am doing a game in corona SDK, but I have this little problem.
I have a menu with a button. If I press it, it sends me to the first level of my game.
When I pass the final level, the game return me to the menu. Bur, if I start playing the first again, my images doesn´t appear.
The images are balls, and to pass the level, you have to eliminate all the balls. To do this, I use:
ball:removeSlef()
ball = nil
But, I don´t think that this is the problem, because I eliminate this lines, and it doesn´t work.
The images are create in scene:createScene function, and insert in the Group.
I short the code of the first level to be understood.
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local physics = require "physics"
physics.start(); physics.pause()
physics.setGravity( 0, 0 )
local cont = 0
local bur = {}
function eliminar1( event )
if (cont == 0) and (event.phase == "began") then
event.target:removeSelf()
bur[1] = nil
cont = cont + 1
end
end
function eliminar2( event )
if (cont == 1) and (event.phase == "began") then
bur[2]:removeSelf()
bur[2] = nil
cont = cont + 1
end
end
function eliminar3( event )
if (cont == 2) and (event.phase == "began") then
bur[3]:removeSelf()
bur[3] = nil
storyboard.gotoScene( "levels.1.level2" )
end
end
function scene:createScene ( event )
local screenGroup = self.view
for i = 1,3 do
bur[i] = display.newImage("irudiak/"..i..".png")
bur[i]:translate(math.random(0,280), math.random(0,400) )
physics.addBody( bur[i], {bounce = 0.3 } )
bur[i]:setLinearVelocity(math.random(-50,50), math.random(-50,50) )
screenGroup:insert(bur[i])
end
bur[1]:addEventListener("touch", eliminar1)
bur[2]:addEventListener("touch", eliminar2)
bur[3]:addEventListener("touch", eliminar3)
end
function scene:enterScene( event )
local screenGroup = self.view
physics.start()
end
function scene:exitScene( event )
local screenGroup = self.view
physics.stop()
end
function scene:destroyScene( event )
local screenGroup = self.view
package.loaded[physics] = nil
physics = nil
end
return scene
createScene is ran only first time when you gotoScene. Every next time only willEnterScene and enterScene are played. To play createScene again you have to remove it (storyboard.removeScene() I guess). Or you can move some stuff you need to willEnterScene. For more detailed info you can watch this: http://www.coronalabs.com/blog/2013/08/20/tutorial-reloading-storyboard-scenes/

Touch Event detection issue

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?
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.................. 😃
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

Resources