How to Spawn objects in corona sdk - android

hey i am new to the Corona sdk world i want to learn how to spawn some objects and make them move across the screen i try everything and it never work i read the forum on spawning the right way and try it but still end up with a error in my code help this is my code
local mRandom = math.random
local mAbs = math.abs
local objects = {"rocket02" ,"rocket01","coin01"}
local function spawnObject()
local objIdx = mRandom(#objects)
local objName = objects[objIdx]
local object = display.newImage("image/object_"..objName..".png")
object.x = mRandom (screenLeft +30,screenRight-30)
object.y = screenTop
if objIdx < 4 then
object.type = "food"
else
object.type = "other"
end
end
Also can some one tell me how to make it move across the screen
Please help Thanks
here's the media file for you to take a look at

I'll show you a method. For that, I have rewritten your code as follows:
local mRandom = math.random
local objects = {"rocket02" ,"rocket01","coin01"}
local objectTag = 0
local object = {}
local function spawnObject()
objectTag = objectTag + 1
local objIdx = mRandom(#objects)
local objName = objects[objIdx]
object[objectTag] = display.newImage(objName..".png") -- see the difference here
object[objectTag].x = 30+mRandom(320)
object[objectTag].y = 200
object[objectTag].name = objectTag
print(objectTag)
end
timer.performWithDelay(1,spawnObject,3)
Here I've used a timer for displaying the object. You can also use for loop for the same purpose.
Here you can call any object with tag as object[objectTag].
For your information:
display.newImage(objName..".png")
--[[ will display object named rocket02.png or rocket01.png or coin01.png
placed in the same folder where your main.lua resides --]]
And
display.newImage("image/object_"..objName..".png")
--[[ will display object named object_rocket02.png or object_rocket01.png
or object_coin01.png placed in a folder named 'image'. And the folder
'image' should reside in the same folder where your main.lua is. --]]
And for moving your object from top to bottom, you can use:
either
function moveDown()
object[objectTag].y = object[objectTag].y + 10
--replace 'objectTag' in above line with desired number (ir., 1 or 2 or 3)
end
timer.performWithDelay(100,moveDown,-1)
or
transition.to(object[objectTag],{time=1000,y=480})
--[[ replace 'objectTag' in above line with desired number (ir., 1 or 2 or 3)
eg: transition.to(object[1],{time=1000,y=480}) --]]
Keep coding.............. :)

Related

How to make a loading scene in between two scenes while downloading. Corona sdk

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

Using scores between scenes Corona SDK

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/

Saving the value of a stepper in Corona SDK to a json file

I want to be able to pass the value from a stepper widget in corona into a json file. So far I've got my stepper to display and increment and decrement and display the current value on screen. I've written a function to save the value to a file as json, but i'm having trouble calling that function. I want to be able to have other setting on screen which have their values save to json. Here the code I have to save the setting:
local function saveSettings (e)
-- body
print("testtesttest")
if (file) then
local content = file:read("*a")
else
settings = {}
settings.houses = StepperNo
file = io.open(path, "w")
local json_setting = json.encode(settings)
file:write(json_setting)
io.close(file)
end
end
and then the code to display the stepper:
local StepperNo = 1
local displayNoOfHouses = display.newText("Number of houses: "..StepperNo,180,135, native.systemFontBold,16)
local function onStepperPress( e )
if ("increment" == e.phase) then
StepperNo = StepperNo + 1
elseif ("decrement") == e.phase then
StepperNo = StepperNo - 1
end
displayNoOfHouses.text = "Number of houses: "..StepperNo
end
local HouseStepper = widget.newStepper {left = 100, top = 100, minimumValue = 0, maximumValue = 9, onPress = onStepperPress}
I dont know how to call the savesetting function after the stepper is pressed. I think I might have done this incorrectly or may be missing something obvious, I am very new to Lua...
There is a very simple to implement table saver and loader presented in this tutorial:
http://coronalabs.com/blog/2014/10/14/tutorial-saving-and-loading-lua-tables-with-json/
It uses JSON to encode a Lua table to save and when needed, read the JSON back in and decode it to a Lua table.

Publishing by Air Android Flash 5.5 , showing me an error

I'm creating an android app using AS3 Flash CS5.5
it'a about simple library contains images that are uploaded to a web page , and i'm using this code that someone help me `
//THIS DEFINES THE ARRAY WHERE YOUR LOADERS WILL GO
var pictureArray:Array = new Array;
//THIS CODE TARGETS THE BUTTONS -- WHEN YOU CLICK THEM THE FUNCTIONS 'nextpic' and 'lastpic' WILL FIRE
nextbtn.addEventListener(MouseEvent.CLICK, nextpic)
backbtn.addEventListener(MouseEvent.CLICK, lastpic)
//YOUR LOADERS. I'VE PUT 3 PICTURES IN THE LIBRARY
//THE LAST LINE FOR EACH LOADER 'PUSHES' THE LOADER INTO THE ARRAY
var loader1 = new Loader();
loader1.load(new URLRequest("banana.jpg"));
pictureArray.push(loader1);
var loader2 = new Loader();
loader2.load(new URLRequest("big apple.jpg"));
pictureArray.push(loader2);
var loader3 = new Loader();
loader3.load(new URLRequest("pineapple.jpg"));
pictureArray.push(loader3);
//WE ADD THE FIRST 'CHILD' HERE
//NOTE THAT ARRAYS HOLD OBJECTS IN CONSECTUTIVE POSITIONS: 0 - WHATEVER
//THE FIRST OBJECT IN THE ARRAY IS ADDRESSED AT: ARRAYNAME[0], THE SECOND OBJECT IS
//AT ARRAYNAME[1], ETC.
addChild(pictureArray[0]);
pictureArray[0].x = 110; pictureArray[0].y = 80;
//n IS JUST A COUNTER THAT WILL MAKE IT EASIER TO ADDRESS THE ITEMS IN THE ARRAY
var n:int = 0;
Function nextpic(e)
{
removeChild(pictureArray[n]);
n = n+1;
//HERE WE RESET THE POSITION IN THE ARRAY IF WE'VE GONE PAST THE NUMBER OF PICTURES THAT WE HAVE
if (n>pictureArray.length - 1)
n=0;
addChild(pictureArray[n]);
pictureArray[n].x = 110; pictureArray[n].y = 80;
}
function lastpic(e)
{
removeChild(pictureArray[n]);
n = n-1;
if (n<0)
n=pictureArray.length - 1;
addChild(pictureArray[n]);
pictureArray[n].x = 110; pictureArray[n].y = 80;
}`
it's working well , but when I publish it by Android Air , it shows me this error
Scene 1, Layer 'Layer 1', Frame 1, Line 39 1071: Syntax error: expected a definition keyword (such as function) after attribute Function, not nextpic.
re-write Function as function Easy!

Attempt to index field "?" (nil value)

hey guy i am new to corona and i am trying to spawn some objects that fall out of the sky on to the ground. i have posted this same code already the person who answered don't answer the question fully. i need help with this so i could get my game on track thanks guys. some one please tell me why i am getting "Attempt to index field "?" (nil value)" i know something doesn't exist. also the code that is giving me this problem is "object[objectTag].x = 30+mRandom(320)" i try to comment it out and try to work without it but the error goes to the next line. can someone help. thanks
local mRandom = math.random
local objects = {"rocket02" ,"rocket01","coin01"}
local objectTag = 0
local object = {}
local function spawnObject()
objectTag = objectTag + 1
local objIdx = mRandom(#objects)
local objName = objects[objIdx]
object[objectTag] = display.newImage("image/object_"..objName..".png")
*object[objectTag].x = 30+mRandom(320)
object[objectTag].y = 200
object[objectTag].name = objectTag*
print(objectTag)
end
timer.performWithDelay(1,spawnObject,3)
Can you use this code block to see if there is a problem with image loading
local mRandom = math.random
local objects = {"rocket02" ,"rocket01","coin01"}
local objectTag = 0
local object = {}
local function spawnObject()
objectTag = objectTag + 1
local objIdx = mRandom(#objects)
local objName = objects[objIdx]
object[objectTag] = display.newImage("image/object_"..objName..".png")
if object[objectTag] ~= nil then
print( "Image succesfully loaded." )
else
print( "Image couldn't be found." )
end
*object[objectTag].x = 30+mRandom(320)
object[objectTag].y = 200
object[objectTag].name = objectTag*
print(objectTag)
end
timer.performWithDelay(1,spawnObject,3)

Categories

Resources