Factory Objects

The number of requests that I have seen on the forums are phenomenon on creating objects. Now if one had been involved in developing games using C++, (there is a lovely book on this topic that talks about the same) you would realise that the way to manage this would be to have a factory routine

So what is and why is it called the factory routine? It is called so because a factory creates a widget, so this routine will create an object. The object is a generic object that the factory creates. So let us have a look at the code in Lua to understand this a bit better.

function createWidget(widgetType)
 -- Returns a widget of widgetType

  local returnObject

 local widgetType = widgetType
 if "circle" == widgetType then
   returnObject = display.newCircle(10,10,10)
 elseif "rectangle" == widgetType then
   returnObject = display.newRect(10,10,10,10)
 elseif "roundedrect" == widgetType then
   returnObject = display.newRoundedRect(10,10,10,10,5)
 elseif "image" == widgetType then
   returnObject = display.newImage("blank.png")
 end
 
 if returnObject ~= nil then
  returnObject.objectType = widgetType
 end

 return returnObject
end

Now when we spawn these objects, they are created with some default settings, these can be passed to the factory for creating, but in IDE's an object with default settings are created which are then moved around and sized to the desired proportions.

So if one would want to create a rectangle, the way to do would be
  local obj1 = createWidget("rectangle")

This can be used in a sample paint type app, where the toolbar would have buttons to create one of the type of objects. Then obviously one would have to move them around and also manage them to work with them.

I hope that beginners that have started development with CoronaSDK or other frameworks, it is suggested that you spend some time in understanding the basics of games and development. Hope this is a good start towards your journey.

Comments

Popular Posts