Question

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

Was it helpful?

Solution

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.............. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top