Thursday, 15 August 2013

How to create global objects in your corona SDK game

In this tutorial, we will teach you how to make global objects with it's own listeners and properties, and are accessible to any class in your game with corona SDK. Here the director class is used to change from scene to scene.

Here I have my .lua  files: main, status and menu. First, lets start with the main.lua. Do the followings in your main:

main.lua
                                                                                 


     local director=require("director")
     local maingroup=display.newGroup()
     maingroup:insert(director.directorView)
     director:changeScene("menu")
     return maingroup 
                                                                                   

Here, we can see that the director class is loaded, and a main displayGroup is created. Next we need to create a class which contains our global object. I am naming that class as 'status.lua'. Here we can create the object method with its certain object with listener and properties and while calling the method, you can return the object to any scene in your game/application. Just look at the status.lua class:

status.lua
                                                                                

    local function myObject(group,x,y,imagePath)

      local image = display.newImage( imagePath )
      image.x, image.y = x, y
      group:insert( image )

      -- We can even add properties as below--
      transition.to(image, {time=1000, x=160, y=300, transition=easing.inOutQuad}) 

      -- Adding Listener --
      image:addEventListener("touch", function() print("imageClicked") end )
    end

    local status = { myObject = myObject }

    return status
                                                                               

Now we can create our menu scene, which is the menu.lua. Here we have to require the object page ('status') and have to call the object method in the page to get the object in current scene, as follows:

menu.lua
                                                                                


module(...,package.seeall)

function new()

    -- require object page --
    local status = require "status"

    -- create a display group --
    local localGroup = display.newGroup()

    -- call object --
    status.myObject(localGroup, 160, 80, "muImage.png")

 return localGroup
end
                                                                               

Now save your files and run the app in the simulator/device to see what happens...

No comments:

Post a Comment