I created an example app with Corona and I tried to implement admob functions.
I ran the admob example and it worked. But when I combined it with this sample code below it stopped working.
At the emulator it runs normally. But when I upload the apk to my phone, I got a black screen.
Not an error, but a weird black screen.
Do you know what am I doing wrong?
-----------------------------------------------------------------------------------------
--
-- menu.lua
--
-----------------------------------------------------------------------------------------
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
-- include Corona s "widget" library
local widget = require "widget"
--------------------------------------------
-- forward declarations and other locals
local playBtn
local optsBtn
local helpBtn
-- ************* ADMOB *********************
-- Hide the status bar
display.setStatusBar( display.HiddenStatusBar )
-- The name of the ad provider.
local provider = "admob"
-- Your application ID
local appID = "a1522213c297e5a"
-- Load Corona 'ads' library
local ads = require "ads"
--------------------------------------------------------------------------------
-- Setup ad provider
--------------------------------------------------------------------------------
-- Create a text object to display ad status
local statusText = display.newText( "", 0, 0, native.systemFontBold, 22 )
statusText:setTextColor( 255 )
statusText:setReferencePoint( display.CenterReferencePoint )
statusText.x, statusText.y = display.contentWidth * 0.5, 160
local showAd
-- Set up ad listener.
local function adListener( event )
-- event table includes:
-- event.provider
-- event.isError (e.g. true/false )
local msg = event.response
-- just a quick debug message to check what response we got from the library
print("Message received from the ads library: ", msg)
if event.isError then
statusText:setTextColor( 255, 0, 0 )
statusText.text = "Error Loading Ad"
statusText.x = display.contentWidth * 0.5
showAd( "banner" )
else
statusText:setTextColor( 0, 255, 0 )
statusText.text = "Successfully Loaded Ad"
statusText.x = display.contentWidth * 0.5
end
end
-- Initialize the 'ads' library with the provider you wish to use.
if appID then
ads.init( provider, appID, adListener )
end
--------------------------------------------------------------------------------
-- UI
--------------------------------------------------------------------------------
-- initial variables
local sysModel = system.getInfo("model")
local sysEnv = system.getInfo("environment")
-- create a background for the app
--local backgroundImg = display.newImageRect( "background.jpg", display.contentWidth, display.contentHeight )
--backgroundImg:setReferencePoint( display.TopLeftReferencePoint )
--backgroundImg.x, backgroundImg.y = 0, 0
statusText:toFront()
-- Shows a specific type of ad
showAd = function( adType )
local adX, adY = display.screenOriginX, display.screenOriginY
statusText.text = ""
ads.show( adType, { x=adX, y=adY } )
end
-- if on simulator, let user know they must build for device
if sysEnv == "simulator" then
local font, size = native.systemFontBold, 22
local warningText = display.newRetinaText( "Please build for device or Xcode simulator to test this sample.", 0, 0, 290, 300, font, size )
warningText:setTextColor( 255 )
warningText:setReferencePoint( display.CenterReferencePoint )
warningText.x, warningText.y = display.contentWidth * 0.5, display.contentHeight * 0.5
else
-- start with banner ad
showAd( "interstitial" )
end
-- ************* FIM ADMOB *****************
-- 'onRelease' event listener for playBtn
local function onPlayBtnRelease()
-- go to level1.lua scene
storyboard.gotoScene( "level1", "fade", 500 )
return true -- indicates successful touch
end
-- Options
local function onOptionsBtnRelease()
-- go to level1.lua scene
storyboard.gotoScene( "options", "fade", 500 )
return true -- indicates successful touch
end
-- Options
local function onHelpBtnRelease()
-- go to level1.lua scene
storyboard.gotoScene( "help", "fade", 500 )
return true -- indicates successful touch
end
-----------------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
--
-- NOTE: Code outside of listener functions (below) will only be executed once,
-- unless storyboard.removeScene() is called.
--
-----------------------------------------------------------------------------------------
-- Called when the scene s view does not exist:
function scene:createScene( event )
local group = self.view
-- display a background image
local background = display.newImageRect( "background.jpg", display.contentWidth, display.contentHeight )
background:setReferencePoint( display.TopLeftReferencePoint )
background.x, background.y = 0, 0
-- create/position logo/title image on upper-half of the screen
local titleLogo = display.newImageRect( "title.png", 264, 42 )
titleLogo:setReferencePoint( display.CenterReferencePoint )
titleLogo.x = display.contentWidth * 0.5
titleLogo.y = display.contentHeight / 5
-- create a widget button (which will loads level1.lua on release)
playBtn = widget.newButton{
label="Play Now",
labelColor = { default={255}, over={128} },
defaultFile="button.png",
overFile="button-over.png",
width=154, height=40,
onRelease = onPlayBtnRelease -- event listener function
}
playBtn:setReferencePoint( display.CenterReferencePoint )
playBtn.x = display.contentWidth*0.5
playBtn.y = display.contentHeight * 2 / 5
-- button for options (options.lua)
optsBtn = widget.newButton{
label="Options",
labelColor = { default={255}, over={128} },
defaultFile="button.png",
overFile="button-over.png",
width=154, height=40,
onRelease = onOptionsBtnRelease -- event listener function
}
optsBtn:setReferencePoint( display.CenterReferencePoint )
optsBtn.x = display.contentWidth*0.5
optsBtn.y = display.contentHeight * 3 / 5
-- button for options (help.lua)
helpBtn = widget.newButton{
label="Help",
labelColor = { default={255}, over={128} },
defaultFile="button.png",
overFile="button-over.png",
width=154, height=40,
onRelease = onHelpBtnRelease -- event listener function
}
helpBtn:setReferencePoint( display.CenterReferencePoint )
helpBtn.x = display.contentWidth*0.5
helpBtn.y = display.contentHeight * 4 / 5
-- all display objects must be inserted into group
group:insert( background )
group:insert( titleLogo )
group:insert( playBtn )
group:insert( optsBtn )
group:insert( helpBtn )
end
-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
local group = self.view
-- INSERT code here (e.g. start timers, load audio, start listeners, etc.)
end
-- Called when scene is about to move offscreen:
function scene:exitScene( event )
local group = self.view
-- INSERT code here (e.g. stop timers, remove listenets, unload sounds, etc.)
end
-- If scene s view is removed, scene:destroyScene() will be called just prior to:
function scene:destroyScene( event )
local group = self.view
if playBtn then
playBtn:removeSelf() -- widgets must be manually removed
playBtn = nil
end
end
-----------------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
-----------------------------------------------------------------------------------------
-- "createScene" event is dispatched if scene s view does not exist
scene:addEventListener( "createScene", scene )
-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )
-- "exitScene" event is dispatched whenever before next scene s transition begins
scene:addEventListener( "exitScene", scene )
-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )
-----------------------------------------------------------------------------------------
return scene
In your build.settings check whether you've added the followings:
android =
{
usesPermissions =
{
"android.permission.INTERNET",
"android.permission.ACCESS_NETWORK_STATE",
"android.permission.READ_PHONE_STATE",
},
}
Keep coding.................. :)
Well, just adding this, it worked:
-- ************* ADMOB *********************
-- Hide the status bar
display.setStatusBar( display.HiddenStatusBar )
-- The name of the ad provider.
local adNetwork = "admob"
-- Your application ID
local appID = "a1522213c297e5a"
-- Load Corona 'ads' library
local ads = require "ads"
-- Initialize the 'ads' library with the provider you wish to use.
if appID then
ads.init( adNetwork, appID )
end
-- initial variables
local sysModel = system.getInfo("model")
local sysEnv = system.getInfo("environment")
local bgW, bgH = 320, 480
if appID then
local adX, adY = display.contentCenterX, 0
local halfW = display.contentWidth * 0.5
local font, size = "Helvetica-Bold", 16
if sysEnv == "simulator" then
local warningText2 = display.newText( "Please build for device ", adX, adY, font, size )
local warningText3 = display.newText( "to test this sample code.", adX, adY, font, size )
warningText2:setTextColor( 255, 255, 255)
warningText3:setTextColor( 255, 255, 255)
warningText2:setReferencePoint( display.CenterReferencePoint )
warningText3:setReferencePoint( display.CenterReferencePoint )
warningText2.x, warningText2.y = halfW, 0
warningText3.x, warningText3.y = halfW, 16
else
ads.show( "banner", { x=adX, y=adY} )
end
else
-- If no appId is set, show a message on the screen
local warningText1 = display.newText( "No appID has been set.", 0, 105, font, size )
warningText1:setTextColor( 255, 255, 255)
warningText1:setReferencePoint( display.CenterReferencePoint )
warningText1.x = halfW
end
And, at the build.settings file:
add this:
plugins =
{
-- key is the name passed to Lua's 'require()'
["CoronaProvider.ads.admob"] =
{
-- required
publisherId = "com.coronalabs",
},
},
Now I just need to adjust some variables to correctly arange the ad at the screen.
Related
I am working on a program that will create a bunch of clones, and it will delete a clone when the clone is taped on. I only want it to delete the clone that is taped on. I am having an issue with the touch event listener. It says that I am trying to index a nil variable, but I defined it earlier in the program.
I have tried changing the variable to be a global variable.
display.setDefault("background", 0, 0, 200)
math.randomseed(os.time())
local boat = display.newImage( "boatt.png" )
boat.x = 163
boat.y = 225
local score = 0
local spawnCnt = 0
local spawnTable = {}
local startTime = os.time()
local startTime2 = os.time()
local fish_tapped
local function spawn ()
local obj = display.newImageRect("fishpic.png",70,70)
obj.x = math.random(1, 300)
obj.y = (0 - math.random(30, 400))
obj.isDone = false
-- Note: Second argument is function name without brakets
obj:addEventListener("touch", touched()) --i added brackets to this
return obj
end
local function onSpawn ()
spawnCnt = spawnCnt + 1
spawnTable[spawnCnt] = spawn()
end
local function movement (event)
-- SPAWN OBJECT USING TIMER
if os.time() - startTime >= 1 then
onSpawn()
startTime = os.time()
end
-- MOVE OBJECT
if spawnCnt > 0 then
for i = 1, spawnCnt do
if spawnTable[i].isDone == false then
if spawnTable[i].y > 600 or spawnTable[i].fish_tapped == true then
spawnTable[i].y = 700
spawnTable[i].isDone = true
display.remove(self)
self = nil
else
spawnTable[i].y = spawnTable[i].y + 4
end
end
end
end
end
Runtime:addEventListener ("enterFrame",movement)
--when i tried to have touched() in the event listener for touch it said that i was calling a
--nill value, so I made the funciton global.
function touched( event )
local obj = event.target
obj.fish_tapped = true
end
Try (not tested)
local function movement (event)
...
-- Replace
-- if spawnTable[i].y > 600 or fish_tapped == true then
-- with
if spawnTable[i].y > 600 or spawnTable[i].fish_tapped == true then
...
end
local function touched( event )
local obj = event.target
obj.fish_tapped = true
end
local function spawn ()
local obj = display.newImageRect("fishpic.png",70,70)
obj.x = math.random(1, 300)
obj.y = (0 - math.random(30, 400))
obj.isDone = false
-- Note: Second argument is function name without brakets
obj:addEventListener("touch", touched)
return obj
end
Read more:
Scope for Beginners
Tap/Touch Anatomy
I'm working on a business app using corona. The interfcae is sort of like the gmail mobile app interface. You've got a screen with a table, when a row is clicked, it opens a new page.
Description of interface: The app gets text and imagelinks from indexed elements in a json object. For each element(jsonObject[i]) in the json object, a row is created and the images are downloaded from the link passed contained in the "imagelink" field in each json element, while texts are gotten from other fields in the same json element. I'm using sockets to get the image and store them in a temporary location that way the images download before everything shows up. And when a row is clicked, it passes the current json element (jsonObject[i]) as well as the tempimage downloaded, and on this new page, the tempImage and some other fields that weren't used in the table are displayed.
Issue: When moving back and front from the scene with the table and the page displayed when a row is clicked, it takes sometime to load up. Understandable since it has to download images, to help with this I created a scene called "loading" to call in between the two other scenes, For now it just has a plane white box (Screen size) that I want it to display while the next scene takes it's time to load, that way it doesn't look like the app is frozen.
My problem: The "loading" scene doesn't work, I know the app loads it cause I removed the part in the code that goes to the next screen, and the loading scene shows up, but when it's added back, everything transitions the way it did before, the current screen appears to be frozen and then goes to the next screen like the "loading" scene isn't there. Could I please get some help with this? I tried using "loadScene" before "goto" but I got a lot of errors. Thank you!
My code:
ItemListPage.lua
local composer = require ( "composer" )
local widget = require( "widget" )
local json = require( "json" )
-- Load the relevant LuaSocket modules
local http = require( "socket.http" )
local ltn12 = require( "ltn12" )
local scene = composer.newScene()
--To help with navigation, these two variables are set on all scenes except loading
--nextScene is the scene I want loaded after the "loading scene"
--prevScene is the current scene which will soon become the previous.
composer.setVariable( "nextScene", "itemDisplayPage")
composer.setVariable( "prevScene", composer.getSceneName("current"))
--NavigationBar elements initiated
--Removed for readability
--Load Json from local file
local filename = system.pathForFile( "items.json", system.ResourceDirectory )
local decoded, pos, msg = json.decodeFile( filename )
if not decoded then
print( "Decode failed at "..tostring(pos)..": "..tostring(msg) )
else
print( "File successfully decoded!" )
end
local items=decoded.items
--items being JsonObject explained in queston
--image handler
local function networkListener( event )
if ( event.isError ) then
print ( "Network error - download failed" )
end
print ( "event.response.fullPath: ", event.response.fullPath )
print ( "event.response.filename: ", event.response.filename )
print ( "event.response.baseDirectory: ", event.response.baseDirectory )
end
--Table stuff
local scrollBarOptions = {
sheet = scrollBarSheet, -- Reference to the image sheet
topFrame = 1, -- Number of the "top" frame
middleFrame = 2, -- Number of the "middle" frame
bottomFrame = 3 -- Number of the "bottom" frame
}
local function onRowRender( event )
-- Get reference to the row group
local row = event.row
local params=event.row.params
local itemRow=3;
-- Cache the row "contentWidth" and "contentHeight" because the row bounds can change as children objects are added
local rowHeight = row.contentHeight
local rowWidth = row.contentWidth
row.rowTitle = display.newText( row, params.topic, 0, 0, nil, 14 )
row.rowTitle:setFillColor( 0 )
row.rowTitle.anchorX = 0
row.rowTitle.x = 0
row.rowTitle.y = (rowHeight/2) * 0.5
--Other elements removed for readabilty (it's all just text objects)
--Download Image
--params referring to items[i]
local imagelink =params.imagelink
-- Create local file for saving data
local path = system.pathForFile( params.imagename, system.TemporaryDirectory )
myFile = io.open( path, "w+b" )
-- Request remote file and save data to local file
http.request{
url = imagelink,
sink = ltn12.sink.file( myFile )
}
row.Image = display.newImageRect(row, params.imagename, system.TemporaryDirectory, 25, 25)
row.Image.x = 20
row.Image.y = (rowHeight/2) * 1.5
row:insert( row.rowTitle )
row:insert( row.Image )
end
local function onRowTouch( event )
local row = event.target
local params=event.target.params
composer.removeScene(composer.getSceneName("current"))
composer.gotoScene( "loading" , {params=params})
end
-- Table
local tableView = widget.newTableView(
{
left = 0,
top = navBar.height,
height = display.contentHeight-navBar.height,
width = display.contentWidth,
onRowRender = onRowRender,
onRowTouch = onRowTouch,
listener = scrollListener
}
)
function scene:create( event )
local sceneGroup = self.view
-- create a white background to fill screen
local background = display.newRect( display.contentCenterX, display.contentCenterY, display.contentWidth, display.contentHeight )
background:setFillColor( 1 ) -- white
-- Insert rows
for i = 1, #sermons do
-- Insert a row into the tableView
tableView:insertRow{
rowHeight = 100,
rowColor = { default={ 0.8, 0.8, 0.8, 0.8 } },
lineColor = { 1, 0, 0 },
params=items[i]
}
end
-- all objects must be added to group (e.g. self.view)
sceneGroup:insert( background )
sceneGroup:insert( tableView )
end
-- other functions and elements unused and removed for readability
loading.lua
local composer = require ( "composer" )
local widget = require( "widget" )
local json = require( "json" )
local scene = composer.newScene()
local nextParams
function scene:create( event )
local sceneGroup = self.view
nextParams= event.params
-- create a white background to fill screen
local background = display.newRect( display.contentCenterX,
display.contentCenterY, display.contentWidth, display.contentHeight )
background:setFillColor( 1 ) -- white
-- all objects must be added to group (e.g. self.view)
sceneGroup:insert( background )
end
local function showNext(event)
--go to next scene
composer.removeScene(composer.getSceneName("current"))
--Goes to next scene with parameters passed from previous scene
composer.gotoScene(composer.getVariable( "nextScene" ), {params=nextParams})
return true
end
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if phase == "will" then
-- Called when the scene is still off screen and is about to move on screen
elseif phase == "did" then
showNext()
end
end
-- other functions and elements unused and removed for readability
ItemDisplayPage.lua
local composer = require ( "composer" )
local widget = require( "widget" )
local json = require( "json" )
local scene = composer.newScene()
--To help with navigation, these two variables are set on all scenes except loading
--nextScene is the scene I want loaded after the "loading scene"
--prevScene is the current scene which will soon become the previous.
composer.setVariable( "nextScene", composer.getVariable( "prevScene" ))
composer.setVariable( "prevScene", composer.getSceneName("current"))
--NavigationBar elements initiated
--This creates the "back button", when clicked it returns to the previous scene, in this case "itemListPage"
--it takes, no parameters
local function handleLeftButton( event )
if ( event.phase == "ended" ) then
composer.removeScene(composer.getSceneName("current"))
composer.gotoScene( "loading" , {params=nil})
end
return true
end
--Remaning navbar elements removed for readability
function scene:create( event )
local sceneGroup = self.view
local params=event.params
-- create a white background to fill screen
local background = display.newRect( display.contentCenterX, display.contentCenterY, display.contentWidth, display.contentHeight )
background:setFillColor( 1 ) -- white
--creating header bar
local bar = display.newRect( navBar.height + (headerBarHeight*0.5), display.contentCenterY, display.contentWidth, headerBarHeight )
bar:setFillColor( 1 )
-- create stuff
local title = display.newText(params.topic, 0, 0, nil, 14 )
title:setFillColor( 0 )
title.anchorX = 0
title.x = margin
title.y = ((2*headerBarHeight/2) * 0.5)+navBar.height
local Image = display.newImageRect(params.imagename, system.TemporaryDirectory, 25, 25)
Image.x = 50
Image.y = display.contentCenterY
-- all objects must be added to group (e.g. self.view)
sceneGroup:insert( background )
sceneGroup:insert( title )
sceneGroup:insert( Image)
end
-- other functions and elements unused and removed for readability
If I understand correctly your scenes are shown in following order:
ItemListPage -> loading -> ItemDisplayPage
But loading scene doesn't have any heavy work to do - so it is redundant.
On ItemListPage.lua you load images in onRowRender callback. This callback is called when you call tableView:insertRow(...) in scene:create. So there is the root of freese
I suggest you to create loading overlay on ItemListPage scene create event. Part of code with table creation should run after you show loading overlay to user - in ItemListPage scene:show event
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if phase == "will" then
elseif phase == "did" then
composer.showOverlay( "loading", { isModal = true })
-- Insert rows
for i = 1, #sermons do
--put your code here
end
composer.hideOverlay( "fade", 100 )
end
end
I have two scenes: the game.lua file and a restart.lua file. Once the game.lua file ends it transfers to the restart screen. On the restart screen I have 'your current score:' and 'your highscore:' along with the values. However, the values don't update themselves after each subsequent restart. The highscore won't update until I restart the app and the current score won't reset to zero until I restart the app.
So for example: i)Say my current highscore is 21. I play the game once and achieve a new highscore: 23. My current score goes to 23 but my highscore is still 21 (until I restart the app).
ii)I play again(without restarting the app) and get a score of 5. The restart screen still shows 23 as my current score.
So basically once I play the game once, all scores are stuck.
In the app I am using the ego module to save highscore(as that would have to be permanent) and have my current score set as global.
Here is the code in my game scene:
highscore = loadFile("score.txt")--the ego module loads this file for me
score = 0--kept global to use in restart screen
local scoreText = display.newText(score,W,0)--create text
sceneGroup:insert(scoreText)
local function checkForFile()
if highscore == "empty" then
highscore = 0--gives highscore number if file is empty
saveFile("score.txt", highscore)--saves new highscore
end
end
checkForFile()
local function onObjectTouch(event)
if(event.phase == "began") then
score = score+1--increment score on touch
scoreText.text = score
if score>tonumber(highscore) then
saveFile("score.txt",score)--if new highscore, save score as highscore
end
vertical = -150--set ball's velocity
ball:setLinearVelocity(0,vertical)
print(ball.x .. " " .. event.x)
end
end
Runtime:addEventListener("touch", onObjectTouch)
And here is the code in my restart scene
------------highScore Text----------------
myscore = loadFile("score.txt")--load highscore file
local highscoretext = display.newText( "Your high score:"..myscore, 0, 0, native.systemFontBold, 20 )
highscoretext:setFillColor(1.00, .502, .165)
--center the title
highscoretext.x, highscoretext.y = display.contentWidth/2, 200
--insert into scenegroup
sceneGroup:insert( highscoretext )
--------------yourscore----------------
local yourscoretext = display.newText( "Your score:"..score, 0, 0, native.systemFontBold, 20 )
yourscoretext:setFillColor(1.00, .502, .165)
--center the title
yourscoretext.x, yourscoretext.y = display.contentWidth/2, 230
--insert into scenegroup
sceneGroup:insert( yourscoretext )
Your code seems a little bit confusing because you are using score, highscore and myscore but lets try and fix this. I will explain the three methods briefly but we will only try out two of them:
Global Score and High Score variables
Game.lua file
Pass paremeters between the scenes
1. Global Score and High Score variables
This is the method that you are using now and I would not recommend to use global variables if you don't need to so let's skip this method and check out the other two.
2. Game.lua file
In this method we will use a designated game.lua file that will store all the data. Please read this blog post from Corona on how Modular Classes works in Lua:
https://coronalabs.com/blog/2011/09/29/tutorial-modular-classes-in-corona/
We will not use meta tables in this example but we'll create a game.lua file that we can call from any other lua or scene file in our Corona project. This will enable us to save the Score and High Score in only one place and also be able to save and load the High Score very easily. So let's create the game.lua file:
local game = {}
-- File path to the score file
local score_file_path = system.pathForFile( "score.txt", system.DocumentsDirectory )
local current_score = 0
local high_score = 0
-----------------------------
-- PRIVATE FUNCTIONS
-----------------------------
local function setHighScore()
if current_score > high_score then
high_score = current_score
end
end
local function saveHighScore()
-- Open the file handle
local file, errorString = io.open( score_file_path, "w" )
if not file then
-- Error occurred; output the cause
print( "File error: " .. errorString )
else
-- Write data to file
file:write( high_score )
-- Close the file handle
io.close( file )
print("High score saved!")
end
file = nil
end
local function loadHighScore()
-- Open the file handle
local file, errorString = io.open( score_file_path, "r" )
if not file then
-- Error occurred; output the cause
print( "File error: " .. errorString )
else
-- Read data from file
local contents = file:read( "*a" )
-- Set game.high_score as the content of the file
high_score = tonumber( contents )
print( "Loaded High Score: ", high_score )
-- Close the file handle
io.close( file )
end
file = nil
end
-----------------------------
-- PUBLIC FUNCTIONS
-----------------------------
function game.new()
end
-- *** NOTE ***
-- save() and load() doesn't check if the file exists!
function game.save()
saveHighScore()
end
function game.load()
loadHighScore()
end
function game.setScore( val )
current_score = val
setHighScore()
end
function game.addToScore( val )
current_score = current_score + val
print("Current score", current_score)
setHighScore()
end
function game.returnScore()
return current_score
end
function game.returnHighScore()
return high_score
end
return game
In your scene file call game.lua like this (at the top of the scene):
local game = require( "game" )
and you'll be able to call the different game methods when needed like this:
game.load()
print("Current Score: ", game.returnScore())
print("High Score: ", game.returnHighScore())
game.setScore( game.returnHighScore() + 5 )
game.save()
The code snippet above:
Loads the High Score from the file
Print out the Current Score
Print out the High Score
Sets the Current Score to the current High Score + 5
Saves the High Score back to the file
Because we set the Current Score to High Score + 5 we will see that change when we restart the Corona Simulator.
3. Pass paremeters between the scenes
When you are switching scene using composer.gotoScene you can also add parameters like this:
local options =
{
effect = "fade",
time = 400,
params =
{
score = 125
}
}
composer.gotoScene( "my_scene", options )
and access them like this in the called scene:
function scene:create( event )
local sceneGroup = self.view
print("scene:create(): Score: ", event.params.score )
end
-- "scene:show()"
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
print("scene:show(): Score: ", event.params.score )
end
Documentation about this method: https://coronalabs.com/blog/2012/04/27/scene-overlays-and-parameter-passing/
I'm having trouble getting the marker added. (only tried on Android devices) I want to add the marker inmediately after the map is loaded. Got it working adding a delay but couldn't make it work by just adding the marker or scaling the map again (by using setRegion).
I tried the following:
1.
local mapa
mapa=native.newMapView( 20, 20, 280, 360 )
mapa.x = display.contentCenterX
mapa.y = display.contentCenterY
mapa.mapType = "standard"
mapa:setCenter( 41.641208, -0.896030 )
mapa:addMarker(tonumber(41.641208), tonumber(-0.896030),{
title = "El Rincon de la Encina",
subtitle = "Ofertas diarias!"})
mapa:setRegion(41.641208, -0.896030, 0.01, 0.01, false)
mapa.isLocationVisible=true
2. This one works correctly
local mapa
mapa=native.newMapView( 20, 20, 280, 360 )
mapa.x = display.contentCenterX
mapa.y = display.contentCenterY
mapa.mapType = "standard"
mapa:setCenter( 41.641208, -0.896030 )
mapa.isLocationVisible=true
local function listener:timer( event )
mapa:addMarker(tonumber(41.641208), tonumber(-0.896030),{
title = "El Rincon de la Encina",
subtitle = "Ofertas diarias!"})
end
timer.performWithDelay( 30000, listener )
Only if the timer calls the function after the map is loaded I get the wanted result.
The reason for adding tonumber was to make sure Corona got the number correctly.
Applying the solution handed over by #AniV
local attempts = 0
mapa=native.newMapView( 20, 20, 280, 360 )
mapa.x = display.contentCenterX
mapa.y = display.contentCenterY
mapa.mapType = "standard"
mapa:setCenter( 41.641208, -0.896030 )
mapa:setRegion(41.641208, -0.896030, 0.01, 0.01, false)
mapa.isLocationVisible=true
local function locationHandler( event )
local currentLocation = myMap:getUserLocation()
local rinconEncinaLat = 41.641208
local rinconEncinaLon=-0.896030
if ( currentLocation.errorCode or ( currentLocation.latitude == 0 and currentLocation.longitude == 0 ) ) then
attempts = attempts + 1
if ( attempts > 10 ) then
native.showAlert( "No GPS Signal", "Can't sync with GPS.", { "Okay" } )
else
timer.performWithDelay( 2000, locationHandler )
end
else
mapa:setCenter( rinconEncinaLat, rinconEncinaLon )
mapa:addMarker( rinconEncinaLat, rinconEncinaLon,{
title = "El Rincon de la Encina",
subtitle = "Ofertas diarias!"})
end
end
locationHandler()
Thanks for helping.
One solution is to repeatedly queue the location hardware until it receives a proper response, then call this function. See the example in object:getUserLocation() for details.
I'm new to Coronoa and Lua, and I'm trying to figure out how to close a map and textbox. The map and text box appear over the home screen, and I was able to create a button (just a genreic black x) and make it close but I can not get the map or text box to close. Below is the code snippet I am using, but I am stuck. I have searched Google, and read through their documentation, and I am just missing something.
local obj = display.newImageRect( "closeButton.jpg" ,25,25 )
obj.x = 60
obj.y = 410 -- replaced with newImageRect for dynamic scaling (adjust X & Y as required)
obj.touch = function (event)
local btn = event.target
if event.phase == "ended" then
btn.alpha = 0 -- example to show the function doing something
myMap.alpha = 0
textBox.alpha = 0
end
end
-- begin detecting touches
obj:addEventListener( "touch", obj.touch)
myMap = native.newMapView( 25, 0, 275, 180 )
myMap.mapType = "hybrid" -- other mapType options are "satellite" or "hybrid"
myMap.isScrollEnabled = true
myMap.isZoomEnabled = true
myMap.isLocationUpdating = true
isVisible = myMap.isLocationVisible
myMap:setCenter( 38.354614, -81.726351 )
myMap:addMarker( 38.354614, -81.726351)
-- Adding the Text Box that contains the Directions
textBox = native.newTextBox( 22, 183, 280, 225 )
textBox.text = "blah blah blah boring directions."
local group = display.newGroup()
group:insert( obj )
I keep getting "attempt to index local 'myMap' (a nil value)", and the same error for textBox. So if anyone can help, its appreciated.
Locally declare your 'MapView' and 'textBox' above the 'obj.touch' function, as below:
local myMap;
local textBox;
Note: Corona mapView does not supported in the simulator.
Keep coding................. 😃