79510716 Creating Games With Corona SDK

14
Interesting feature PLUS >>> INTERVIEW WITH AKIRA MOBILE >>> Starting Mobile Game Development Issue 01/2012 (1) MOBILE GAME DEVELOPMENT Creating Games In Corona SDK Creating Games In Corona SDK Creating Games In Corona SDK AntiAliasing & Motion Blur Effect SnakeStyle Game in C# SnakeStyle Game in C#

Transcript of 79510716 Creating Games With Corona SDK

Page 1: 79510716 Creating Games With Corona SDK

Interesting featurePLUS >>> INTERVIEW WITH AKIRA MOBILE >>> Starting Mobile Game Development

Issue 01/2012 (1)

MOBILE GAME DEVELOPMENT

Creating Games In Corona SDKCreating Games In Corona SDKCreating Games In Corona SDK

Anti-­Aliasing & Motion Blur Effect

Snake-­Style Game in C#Snake-­Style Game in C#

Page 2: 79510716 Creating Games With Corona SDK

4 01/2012 gamecodermag.com

The world of game develop-ment has become increas-ingly popular in the past

couple years among many mobile platforms such as iOS and Android. A popular game engine used for mobile game development is Corona SDK by Anscamobile http://www.anscamobile.com. It is very user friendly and great for begin-ning and experienced program-mers. You will !nd yourself diving into Corona quickly using Lua as the programming language; close-ly compared to AS3. Corona SDK is available to develop on Mac or PC, so everyone can join in on the fun.

In this article, we’ll be learning how to make a simple 2D shooter type based game in Corona SDK from start to !nish in less than an hour. There are a couple necessary tools and !les that will be needed be-fore we start coding. You will need to create a user account on Ansca’s site to download Corona here: http://www.anscamobile.com/corona. It is free to test out for as long as you like, but if you want full access to what Corona has to o"er and submit your games to either the App Store or Android Market, you will have to be a subscriber. There are a variety of subscriptions to suit your developer needs if you choose to subscribe later on: http://www.anscamobile.com/pricing.

Once you have created a user ac-count, please refer to the Quick Start Guide link to get you set up

in Corona SDK before we begin: https://developer.anscamobile.com/resources/corona-­quick-­start-­guide. Are you set up now? Great! Let’s start coding our game!

Make sure that you have down-loaded the project folder that is attached to this article called Bears Gone Wild New. The main premise of the game is that you are a panda bear being attacked by a swarm of evil bears and will have to fend them o" for as long as you can. You will learn how to transition be-tween scenes using the Storyboard API: http://developer.anscamobile.com/content/storyboard. The proj-ect !le will contain some .lua !les and assets that are already set up for you to create the mini game. So let’s get started!

In your text editor, create a new !le called main.lua and save it to your project folder. The main.lua !le is the !rst scene Corona SDK reads from when a project is launched in the simulator. We’ll need to im-port storyboard and call the load-ing scene. See Listing 1 and add the following lines. Save your !le (Listing 1).

Next, we’ll start adding in our loading scene. Create a new !le in your text editor and save it as loading.lua to your project folder (Bears Gone Wild New). We’ll start implementing the Storyboard API in our scene. Refer to Listing 2 and add the following code to

your loading.lua !le. Every time you want to load a new scene into view, require (“storyboard”) needs to be added. local scene = storyboard.newScene() will allow us to call the scene events: createS-cene(), enterScene(), exitScene(), and destroyScene().

The main visual focus of the scene is the image display object in createScene(). It is included in the screenGroup so when we change scenes, we’ll be able to remove the object to prevent memory leaks. Notice that storyboard.gotoScene( “scene1”, “fade”, 800 ) will transi-tion to scene 1 once the chang-eScene() function is completed through myTimer. In the createS-cene() function, storyboard.remo-veScene( “scene1” ) is added and will be applied after the !rst initial gameplay is over and the game is restarted. When you have added all the code for loading.lua, save your !le (Listing 2).

How to Create a Mini-­Game in Corona SDK

by Michelle Fernandez

Listing 1: Setting up main.luadisplay.setStatusBar( display.HiddenStatusBar )

-­-­ require controller module

local storyboard = require “storyboard*

storyboard gotoScene( “loading”)

Page 3: 79510716 Creating Games With Corona SDK

501/2012 gamecodermag.com

How to Create a Mini-­Game in Corona SDK

Figure 1: Loading screen

The main game algorithms will be stored in a new scene. The last !le you’ll need to create is scene1.lua from your text editor. In this !le, we’ll introduce and declare some modules and variables that will be called during gameplay, see (Listing 3). There are also sound e"ects we have pre-loaded that will be applied to some of the game assets. The great thing about Storyboard API is that it uses the same set up throughout every scene change. You’ll notice how the code is similar to load-ing.lua. In createScene(), we used storyboard.removeScene( “load-ing” ) to remove the loading scene since it is not needed anymore. In enterScene(), we applied all the game functions in this block. The gameActivate() function will start

-­ “exitScene” event is dispatched before next scene’s transition begins scene:addEventListener( “exitScene”, scene )

-­ “destroyScene” event is dispatched before view is unloaded, which can be scene:addEventListener( “destroyScene”, scene )return scene

Listing 2: Setting the loading scene

local storyboard = require( “storyboard”) local scene = storyboard.newScene()-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­ BEGINNING OF YOUR IMPLEMENTATION-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­

local image local myTimer

-­-­ Called when the scene’s view does not exist: function scene:createScene( event) local screenGroup = self view

-­-­ completely remove scenel storyboard removeScene( “scenel”)

print( “\nloading: createScene event”)end

-­-­ Called immediately after scene has moved onscreen: function scene:enterScene( event) local screenGroup = self view

print( “loading: enterScene event”)

image = display newlmageRect( “loading png”, 300,400) image x = 160;; imagey = 240 scree nGroup inse rtf image)

local changeScene = function () storyboard gotoScene( “scenel”, “fade”, 800 ) end myTimer = timer performWithDelayf 1500, changeScene, 1 )

end

-­-­ Called when scene is about to move offscreen:function scene exitScenef)

if myTimer then timer.cancel( myTimer);; end

print( “loading: exitScene event”)

end

-­-­ Called prior to the removal of scene’s “view (display group) function scene:destroyScene( event)

print( “((destroying loadings’s view))”)

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

scene)

Page 4: 79510716 Creating Games With Corona SDK

6 01/2012 gamecodermag.com

out by setting gameIsActive = true since it initially is set to false at the beginning of the game. We’ll ap-ply our main character movement with moveChar() based on touch events along the X direction. The setScore() function will continually update the game score when the enemy collides with the player’s weapon.

The game is over when the main character has zero lives remaining. We will call the callGameOver() function. What this function does is activates the gameOverSound sound e"ect, dims the background image with a darker overlay, and displays and image that says “Game Over.” Appearing alongside the game over screen is the !nal score of the player and a restart button that will allow the player to play the game again. Most impor-tantly during this function is that all transitions, timers, animations, and touch events that were run-ning during gameplay are no lon-ger active. The heads up display is organized into one function called hud(). It displays the count for number of enemies that are killed, lives that are left, and current game score. There is a function called livesCount() which will decrement lives after the player’s character gets hit by an enemy 3 times. When player has less than one life, callGameOver() is activated in the scene. The background image in the game is placed in it’s own func-tion called background().

The following block of code demon-strates the collision detection with all the objects that have a physical body. This includes the user’s char-acter (panda bear), the enemies (evil bears), and the character’s weapon (!re bullets). Add the remaining code in your scene1.lua !le, see (Listing 4).

The main character of the game is animated through a movieclip class that is already included in the project !le. This can be found in the createChar() function. You will see 2 images that will alternate back and

Listing 3: Declaring variables, movement, and HUD

local storyboard = require( “storyboard”) local movieclip = requirefmovieclip”) local physics = require (“physics”) local scene = storyboard.newScene()-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­ BEGINNING OF YOUR IMPLEMENTATION-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­local backgroundlocal characterlocal smokelocal lastX = 0local restartBtn

local scoreTextlocal killTextlocal livesTextlocal shadelocal gameOverScreenlocal gamelsActive = false

local stopTimerlocal shotTimerlocal playTweenlocal shootTweenlocal gameLives = 3local gameScore = 0local killCount = 0local mRand = math, random

-­-­ LOAD SOUNDS

local gameOverSound = audio.loadSound( “gameover.wav”) local btnSound = audio.loadSound( “btnSound.wav”) local explo = audio.loadSound(“explo.mp3”) local shot = audio.loadSound(“shot.mp3”)

—-­ Called when the scene’s view does not exist: function scene:createScene( event) local screenGroup = self.view

—-­ completely remove scene’s view storyboard. removeScene( “loading”)

print( “\n1: createScene event’)

end—-­ Called immediately after scene has moved onscreen function scene:enterScene( event) local screenGroup = self.view

—-­ Game start local gameActivate = function()

gamelsActive = true

end

—-­ Events for character movement along the X direction local moveChar = function(event) if( event, phase == “began”) then lastX = event.x -­ character.x elseif(event.phase == “moved”) then character.x = eventx-­ lastX end

—-­ Keeps character from going outside the edge of the

Page 5: 79510716 Creating Games With Corona SDK

701/2012 gamecodermag.com

How to Create a Mini-­Game in Corona SDK

stage if((character.x -­ character.width * 0.5) < 0) then character.x = character.width * 0.5 elseif((character.x + character.width * 0.5) > display.contentWidth) then character.x = display.contentWidth -­ character.width *0.5 end end

—-­ Tracks the game score

local setScore = function( scoreNum ) local newScore = scoreNum gameScore = newScore if gameScore < 0 then gameScore = 0;; end

scoreText.text = “Score:”.. tostring( gameScore ) scoreText.xScale = 0.5;; scoreTextyScale = 0.5 scoreText.x = (scoreText.contentWidth * 0.5) + 15 scoreText.y = 15 end

—-­ Calls the game over screen local callGameOver = function()

audio.play( gameOverSound )

gamelsActive = false physics. pause()

shade = display.newRect( 0, 0, 380, 570 ) shade:setFillColor( 0, 0, 0, 255 ) shade.x = 160;; shade.y = 240 shade.alpha = 0

gameOverScreen = display. newlmageRect( “gameOver.png”, 300, 400 )

local newScore = gameScore setScore( newScore )

gameOverScreen.x = 160;; gameOverScreen.y = 240 gameOverScreen.alpha = 0

screenGroup:insert( shade ) screenGroup:insert( gameOverScreen )

—-­ Transition game over assets

transition.to( shade, time=200, alpha=0.65 ) transition.to( gameOverScreen, time=500, alpha=1 )

scoreText.isVisible = false scoreText.text = “Score:”.. tostring( gameScore ) scoreText.xScale = 0.5;; scoreTextyScale = 0.5 —> for clear retina display text scoreText.x = 160 scoreText.y = 240 scoreText:toFront() timer.performWithDelay( 0, function() scoreText.isVisible = true;; end, 1 )

local onRestartTouch = function( self, event) if event.phase == “began” then audio.play(btnSound ) —-­ Once restart button is touched, the loading screen displays and the game is restarted storyboard.gotoScene( “loading”, “fade”, 400 ) return true end end

Page 6: 79510716 Creating Games With Corona SDK

8 01/2012 gamecodermag.com

restartBtn = display.newlmageRect(“restartbtn.png”, 60, 60 ) restartBtn.x = 260;; restartBtn.y = 385 screenGroup:insert( restartBtn )

restartBtn .touch = onRestartTouch restartBtn:addEventListener( “touch”, restartBtn )

-­-­ Stops character movieclip character:stop()

—-­ Stops all timers and transitions when game over screen displays if playTween then transition.cancel( playTween );; end if shootTween then transition.cancel( shootTween );; end if stopTimer then timer.cancel( stopTimer);; end if shotTimer then timer.cancel( shotTimer);; end

—-­ Touch events on character are no longer active Runtime: re moveEventL istene r(“touc h”, moveCha r)end

—-­Displays heads up display local hud = function()

killText = display.newTextf “Killed: ”.. tostringf killCount), 0, 0, “Arial”, 45 ) killText: setTextColor( 150,25,180, 255 ) killTextxScale = 0.5;; killText.yScale = 0.5 killTextx = (320 -­ (killTextcontentWidth * 0.5)) -­15 killText. y = 465

screenGroup:insert( killText)

livesText= display.newText( “Lives:”.. tostring( gameLives ), 0, 0, “Arial”, 45 ) livesText:setTextColor( 150,25,180, 255 ) livesTextxScale = 0.5;; livesText.yScale = 0.5 livesTextx = (320 -­ (livesText.contentWidth * 0.5)) -­ 15 livesText.y= 15

screenGroup:insert( livesText) scoreText = display.newText( “Score:”.. tostring( gameScore ), 0, 0, “Arial”, 45 ) scoreText:setTextColor( 150,25,180, 255 ) scoreText.xScale = 0.5;; scoreText.yScale = 0.5 scoreText.x = (scoreText.contentWidth * 0.5) + 15 scoreText.y = 15

screenGroup:insert( scoreText)

end

-­-­ Track character lives local livesCount = function()

gameLives = gameLives -­ 1

livesText.text = “Lives:”.. tostring( gameLives ) livesText.xScale = 0.5;; livesText.yScale = 0.5 livesText.x = (320 -­ (livesTextcontentWidth * 0.5)) -­15 livesText.y = 15

print(gameLives ..” lives left”)

if gameLives < 1 then callGameOver() end end

-­-­ Displays background image

Page 7: 79510716 Creating Games With Corona SDK

901/2012 gamecodermag.com

How to Create a Mini-­Game in Corona SDK

forth while the character display object is moving. For the collision of character to work properly, it has been assigned a name that is respectively called “character” and given a “static” physical body since the player will control it through touch events. Also, notice character.isHit = false. This will also help us de-tect when a collision has occurred between character and enemy. For all collision events, a display object called smoke will appear and disappear to demonstrate a poof e"ect. It’s just another subtle detail that will add more aesthetics to the gameplay.

In the shoot() function, bullet is introduced and is positioned equal to character. The most important part of this function is the move-ment of bullet. It transitions in the Y direction opposite from character and removed from the scene from either a collision with the enemy or if it reaches near the top of screen

if no collision occurs. In order for bullet to continue shooting, timer.performWithDelay( 800, shoot, 0) is used. The 0 at the end of the func-tion means that the designated function will run repeatedly until the timerID is canceled.

When it comes to the enemy col-lision portion of the game, there are a couple things that need to be assigned. There are 2 parameters assigned for onEnemyCollision(), self and event. Upon any collision that comes back true, the enemy object is removed from the stage and a poof of smoke appears tem-porarily. Since bullet is assigned the name “bullet”, the count for every enemy on the screen killed is tracked and the score will incre-ment 500 points every time with the setScore() function. When char-acter is hit, livesCount() is called which decrements the lives of the character. When gameLives < 1, all timers will be cancelled.

The enemy display object will also be animated through the movieclip class. It is set up similarly to char-acter. When it enters the screen, a random function was added on the x value of enemy to make the evil bears appear in di"erent loca-tions in the X direction. The physical body type of enemy is “dynamic” and will activate collision detections between the bullet and character. The enemy transitions from the top of the screen at a smaller scale to make it appear as if they’re coming from a distance from the player’s character. It will appear at full size as it reaches the bottom of the screen during gameplay. What’s important about enemy, is that it is assigned a “collision” event listener which is connected to onEnemyCollision(). Another timer.performWithDelay() function is used to continually tran-sition enemy while the game is active.

Lastly, a function called initVars() will initialize all the functions we have created and added to this chunk, including the touch event for the main character. This is also where we initialize the physics properties in the game as well. When gameplay is over and the player presses the restart button, all that was active needs to be made sure that they are inactive. If there are any other tim-ers and transitions that were used, be sure to cancel them and remove all event listeners. We also have to make sure we add physics.stop(). Try to clean out the scene as much as possible to prevent any potential issues when changing scenes. You will see all the variable removals added in exitScene().

Remember to save your scene1.lua !le and any other .lua !les that you have not saved. Launch Corona SDK and run the project !le in the simulator. To play the game, drag the panda bear side to side to shoot at the evil bears and to dodge them if they get too close. This game is al-ready con!gured to run on any iOS or Android device. You’ll be able to play the game that you have coded in such a short amount of time.

local background = function()

background = display.newlmageRect( “bg.png”, 320, 480) background.x = 160;; background.y = 240

screenGroup:insert( background )

end

Figure 2: Game screen 1 Figure 3: Game screen 2

Page 8: 79510716 Creating Games With Corona SDK

10 01/2012 gamecodermag.com

Listing 4:

—-­ Function for character and smoke local createChar = function()

character = movieclip.newAnim(“charA.png”, “charA.png”,”charA.png”,”charA.png”,”charA.png”,”charA.png”,”ch arB.png”,”charB.png”,”charB.png”1”charB.png”,,’charB.png”1”char B.png”) character.x = display.contentWidth * 0.5 character.y = display.contentHeight-­ character.height character.myName = “character” character: play() physics.addBody(character, “static”, density=1.0, friction=0.15) character.isHit = false

smoke = display.newlmageRect( “poof.png”, 50, 50 ) smoke.alpha = 1.0 smoke.isVisible = false

screenGroup:insert( character) screenGroup:insert( smoke ) end

local shoot = function(event) local bullet = display.newlmageRectfbullet.png”, 8, 20 ) bulletx = character.x bullety = character.y -­ character.height bullet. myName = “bullet” bullet. isH it = false physics.addBody(bullet, “static”, density=1, friction=0)

audio.play(shot) shootTween = transition.to(bullet, y=30, time=700, onComplete=function(self) print(“erase”);; self.parentremove(self);; self = nil;; end)

screenGroup:insert(bullet) end

local shotEntrance = function() shotTimer = timer.performWithDelay( 800, shoot, 0 ) end

local onEnemyCollision = function( self, event)

if event.phase == “began” and self.isHit == false then audio.play( explo )

self. isHit = true print( “Enemy destroyed!”) self. isVisible = false self.isBodyActive = false

smoke.x = self.x;; smoke.y = self.y smoke.alpha = 0 smoke. isVisible = true

local fadeSmoke = function() transition.to( smoke, time=500, alpha=0 ) end

transition.to( smoke, time=50, alpha=1.0, onComplete=fadeSmoke)

self.parent:remove( self) self = nil

if event.other.myName == “bullet” then

Page 9: 79510716 Creating Games With Corona SDK

1101/2012 gamecodermag.com

How to Create a Mini-­Game in Corona SDK

killCount = killCount + 1 killText.text = “Killed: “.. tostring( killCount) killText.xScale = 0.5;; killText.yScale = 0.5 -­-­> for clear retina display text killText.x = (320 -­ (killText.contentWidth * 0.5))-­15 killText. y = 465 print(“enemy hit”)

local newScore = gameScore + 500 setScore( newScore )

elseif event.other.myName == “character” then

ivesCount() print(“character hit”)

end

if gameLives < 1 then timer.caneel( stopTimer) timer.cancel( shotTimer) print(“timer cancelled”) end endend

-­-­ Function for enemy entrance local enemyEntrance = function() local enemy = movieclip.newAnim(“enemyA.png”, “enemyA.png”,”enemyA.png”,”enemyA.png”,”enemyA.png”,”ene myA.png’,,”enemyB.png”,”enemyB.png”1”enemyB.png”,”enemyB.p ng”,”enemy B. png”, “enemy B. png”)

(display.contentWidth -­ enemy.width)) enemy.y = 50 enemy. myName = “enemy” physics.addBody(enemy, “dynamic”, bounce=0, friction=0.5) enemy:play() enemy.isHit = false enemy.xScale = 0.4;; enemy.yScale = 0.4

-­-­ Scale starts small and becomes full size as it nears the bottom of the screen playTween = transition.to(enemy, y=530, time=4500, xScale = 1.0, yScale = 1.0, onComplete = function(self) display.remove( self);; self = nil;; end) screenGroup:insert(enemy) enemy.collision = onEnemyCollision enemy:addEventListener( “collision”, enemy) end local enemyTimer = function() stopTimer = timer.performWithDelay( 600, enemyEntrance, 0) end

-­-­Initializes all functions created local initVars = function() physics.start( true ) physics.setGravity( 0, 0 ) -­physics.setDrawMode( “hybrid”)

background() createChar() enemyTimer() shotEntranceQ hud() gameActivate()

Runtime:addEventListener(“touch”, moveChar)

end initVars() print( “1: enterScene event’ )

Page 10: 79510716 Creating Games With Corona SDK

12 01/2012 gamecodermag.com

Conclusion

We have covered a ton of informa-tion in this article that will give you a taste of what game development using physics properties in Corona SDK is like. Be sure to go over the comments in the code if there is any confusion on how something was created. You can also take a look at the full project with all the code in-cluded under the folder called Bears Gone Wild Final. For more informa-tion relating to Corona SDK, visit Anscamobile’s website at: http://www.anscamobile.com where you can learn more on how Lua is applied to Corona’s easy to understand API’s. If you are really intrigued with Corona SDK and would like to learn more about game development and

how to develop mobile apps with it, please check out my book, Corona Game Development Beginner’s Guide, due out February 2012.

All listings and additional !les are available for download on our web-site: www.gamecodermag.com in the Downloads section

end

-­-­ Called when scene is about to move offscreen: function scene:exitScene( event)

print( “1: exitScene event”)

physics. stop()

if playTween then transition.cancel( playTween );; end if shootTween then transition.cancel( shootTween );; end if stopTimer then timer.cancel( stopTimer);; end if shotTimer then timer.cancel( shotTimer);; end

Runtime:removeEventListenerftouch”, moveChar) restartBtn:removeEventListener( “touch”, restartBtn )end

—-­ Called prior to the removal of scene’s “view” (display group) function scene:destroyScene( event) print( “((destroying scene 1’s view))”)end

-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­ END OF YOUR IMPLEMENTATION-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­

-­-­ “createScene” event is dispatched if scene’s view does not existscene:addEventListener( “createScene”, scene )

scene:addEventListener( “enterScene”, scene)

-­-­ “exitScene” event is dispatched before next scene’s transition beginsscene:addEventListener( “exitScene”, scene )

—“destroyScene” event is dispatched before view is unloaded, which can bescene:addEventListener( “destroyScene”, scene )-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­-­

return scene

Figure 4: Game Over screen

Michelle Fernandez

co-­founder of MobiDojo LLC

and author of Corona Game Development Beginner’s Guide. Developer for Willy Wiener and the Tunnel of Doom for iOS and Android.

Page 11: 79510716 Creating Games With Corona SDK

14 01/2012 gamecodermag.com

IntroductionThe word ‘mobile’ became very

popular in the computer world in the last 10 years. In the last 2 years it is ‘mobile games’.

All of us know games about birds vs pigs, ropes cut and fruits de-stroyed and those games are associ-ated with the word ‘millions’. Millions of downloads and millions of dollars. All of us (game develop-ers) feel really tempted to go mobile and become millionaires with our super duper game. It is possible. Check these numbers.

According to Apple, the App Store reached the mark of 15 billion apps downloaded (data from July 2011). Google, on the other hand, claimed 10 billion apps downloaded from their Android Market (data from December 2011). According to 148apps.biz, currently 17% of down-loads form Apple App Store are games. For the Android counterpart, 25.6% are games. Consider also an average price for games of $1.0 for the Apple App Store and around $1.7 for the Android Market. And for the freemium lovers, according to Flurry, consumers spend average of $14 per transaction on freemium games in iOS or Android.

When you see these numbers it is impossible not to feel tempted to go to the mobile world. And I’m not going to tell you that you don’t have to go that way, in fact you should go that way. The point of this article is

to show you some of the important aspects (at least in my opinion) of the di"erent platforms before you jump in and start coding.

We are going to talk about two major players here, and for smart phones those are Android and iOS. The new Windows Mobile OS could be a big hit but it is still too early to tell. At least at the beginning, you will get more attention if you go for Android and/or iOS.

Device FragmentationNo, you don’t need to defrag

your iPhone but you will face the is-sue of fragmentation if you enter the mobile world.

Basically, fragmentation means that your game should run on di"er-ent devices with di"erent hardware and OS (we’ll check that later). Fragmentation is usually associated with Android which has many ver-sions which makes it hard to develop an app that would run without problems on all of them. iOS is start-ing to show some symptoms of this issue too. Android has a bigger problem, as we are going to see in this section.

Android is an open platform and almost anyone can use the OS for any hardware. This causes problems with fragmentation. There is a lot of different devices on which your game should run properly. Of course, you can always limit the number of devices your game will

run on, but this could seriously im-pact your sales on the Android Market. If you don’t believe me, go and check out www.androidfrag-mentation.com (yes, there is a web-site about this), you can !nd a list of all the different brands that use Android, and you may get a big surprise.

The Android SDK takes a good approach to !x this issue. Basically, you have di"erent places where you should put your assets that apply to a device speci!c DPI and your lay-outs’ de!nitions based on the size of the screen. For example, if you want to build an application that support Android phones for the most com-mon devices (in a proper way) you must provide at least 3 (ldpi, mdpi and hdpi) sets of assets and make 3 sets of layout (small, normal and large). If you want to support tab-lets, well, then you have to add one more to each category. Of course, you can just stick with one option and let Android do the scaling if it ’s possible. This is highly not recommended in most cases. Simply speaking, games should look really good and leaving the image scaling to the SDK could result in some really bad graphics. If you are making games, you probably are not going to use the layout stu", but it is still an option for some not so ‘complicated’ games.

One thing that, obviously, the SDK can’t !x is the di"erent hard-ware on each device. Your game

Starting Mobile Game Developmentby Sebastián Castro

Page 12: 79510716 Creating Games With Corona SDK

1501/2012 gamecodermag.com

Starting Mobile Game Development

could run REALLY good on some devices, and at the same time pretty pretty BAD on others. This is the real pain in the hardware fragmentation for Android.

So, do you think Android is not a good option and that iOS is more simple? Well, you are wrong. Right now, you need at least 2 sets of as-sets for your iOS application. And just like in Android, if you want to support tablets (iPad) you need to add one set of assets and probably new UI design or at least lots of “if IPAD” for some stu" (like UI design, positional constants, etc.), or you can make the HD version of your app that supports only tablets. Yes, it is less work than creating an app in Android, but it is not much better option.

The good point about fragmen-tation of the Apple devices is that the company makes previous mod-els obsolete when a new one arrives and also that there is no more that 4-5 di"erent hardwares to support. This is a really big advantage over Android.

OS FragmentationIn the case of iOS this is practi-

cally not a problem, there are two main versions out there, 4.x and 5.x. Apart from the new features that you have on 5.x, you can stick to developing apps for 4.x devices and reach almost whole (if not whole) market.I think that supporting 3.x devices is a waste of time, as almost no one uses this version anymore and if that is the case the device is an old one.

The OS fragmentation is one of the biggest issues for Android. Although right now it is not as big as a year ago (the older versions are obsolete) still it causes some prob-lems as we are going to see).

As you can see in the figure above, most of the Android devices are using 2.3.3 and 2.2, but be sure that you will get many complains about 2.1 users. Still, in my opinion, you should stick at least to 2.2.

The problem with any new Android version is that it takes too much time for any to get accepted be-cause, in most cases, the manufac-turer of the device is in charge of new versions’ distribution, so it de-pends on the manufacturer to re-lease an update and that could take a while. So in a year or less, you will have devices with 3.X and/or 4.X Android versions plus the old ones. And wait, there is a new problem: custom versions.

Yes, some companies don’t only make hardware that supports Android, they also take an Android version and change it so they can put “their own stu"” in there (pro-prietary applications or they change some behaviors to adapt to the purpose of the device). This is a real pain for developers. I’m working on a game right now that should run on Kindle Fire, the Amazon’s own version of Android. So what you get is that you don’t only need to worry about your bugs, you also have to worry about their bugs that could make your life a nightmare (at least for a couple of days and lots of “if KINDLE” lines).

This is the biggest problem with Android. It requires the app to sup-port too many Android versions, each one has some new features that you can’t use (or you need

compatibility packages that could make your work a nightmare), some-times you also have to stick to some “old” version’s behaviors or bugs, and prey that it wasn’t changed in “newer” versions and that it doesn’t make your layouts looks totally broken.

FrameworksDo not reinvent the wheel...that

is my favorite phrase about software development. If you really, really need to get in touch with low level API, do it, but always try to use frameworks or game engines that make your life easier. It’s highly probable that someone has already done what you are trying to accom-plish and probably shared the code or, even better, made a tutorial about that. So, for me, the best development tool is Google.

There is a lot of mobile frame-works/engines for games. I will only discuss some of them. A lot of books, articles, tutorials, etc. is available for each of those frameworks and en-gines and I’m sure that you can !nd better info out there than from me, but at least you’ll have some refer-ences to look at.

One really good thing about some of these frameworks is that they can work on both platforms (or more in some cases)

Figure 1: Usage of different Android versions

Source: http://developer.android.com/intl/fr/resources/dashboard/platform-versions.html

Page 13: 79510716 Creating Games With Corona SDK

16 01/2012 gamecodermag.com

One note about cocos, you will !nd almost a speci!c version of cocos for each platform you may want to make a game for. In fact there is año android versión under development, I didn’t add it to the list because it is not ready for production but keep an eye for it. Also there is a C version of cocos that should work in Android and iOS.

Development environmentSome of the engines or frame-

works named in the previous section have their own scripting language and you’ll need to know the basic stu" to work with these platforms.

For iOS you have to go for Xcode and for Android for Eclipse. In Android you can use NetBeans too but the

usual development tool is Eclipse. As you may know iOS uses Objective-C as a programming language while Android uses Java.

Both SDKs have simulators. For iOS you have simulators for each device (iPhone and iPad) and each iOS ver-sion (4.x and 5.x). In Android you can customize your simulator to run whenever you may need it. This is a really good feature because you can have lots of different hardware out there so you can experiment with vari-ous simulators. Also there are compa-nies that are releasing their own Android emulators to make your life easier, one example is Samsung for their Galaxy Tab.

The problem with Android emula-tor is that it is not good for games, it can’t run your games and debug your games, so you probably need to !nd a device and test directly on it, you will save lot of time. For iOS you can test & debug all your work in the simulator without problem, but still need to test in real hardware, because there can be some differences between real devices and the simulator (one exam-ple, iOS devices are key sensitive but not the simulator, so you could end up getting an image showing on the simulator but not on the device).

MarketsBoth markets are di"erent, Android

is growing and it seems that it will overtake iOS and that it will be bigger. Almost every new smartphone has Android or iOS, but iOS is restricted to Apple products while Android is used by multiple devices. The catch here is that Apple users spend more money than Android ones, so right now Apple sounds like a better option. But Android will be huge and you’d want to go !rst for iOS and then for Android. This is not only my opinion, big game companies are going that way.

One thing that they have in com-mon is that you have to pay to get a game in there. For Apple you need $100 a year to publish anything. In the case of Android you have to pay $25. In both cases you receive 70% of your sales.

Table 1:

Figure 2: Top 10 mature markets, by iOS and Android device penetration

Page 14: 79510716 Creating Games With Corona SDK

1701/2012 gamecodermag.com

Starting Mobile Game Development

Also pay attention to the new Windows mobile, Microsoft is trying to enter the !ght here and is trying to mix all in one huge package: Windows, Xbox and windows mobile, so it could be a real option in the near future or (why not) present because you can start your development for Windows mobile right now.

TabletsDo not forget about tablets.

Tablets are the jack pot in mobile gaming. The iPad is a really good and pro!table game platform so you must release your games for iPad, you could loose some really good players ($$) out there.

Android tablets are not good, we are all expecting the new versions to see if they make some good numbers but the truth is that Android tablets are pretty bad at this moment.

ConclusionThis article is just a basic introduc-

tion to mobile game development, there is a lot more, trust me. Still, mak-ing games for mobile phones is really fun, and with some luck and hard work you can live from that. So take this reading as a small guide for mo-bile game development and make lots of game about birds killing pigs.

ABOUT ME

I’m a mobile developer, most of the time I’m making games for other

“company”. My background, 5 years as C++ developer and architect for the telecommunications industry (mobile part) building some real time applications for mobile telephone operators. If you like, don’t like or hate my English feel free to contact me at [email protected].

may deduced that after reading the article :)

Figure 4: U.S. Mobile app consumption, time spent per category

Figure 3:

NumbersSource www.digitalbuzzblog.com

The mobile gaming industry is predicted to reach $54 Billion by 2015 ($8 billion this year).

84% of tablet owners play games.

70 – 80% of all mobile downloads are games.

Android is soon to overtake Apple in number of total available apps.

In-game purchases should overtake pay-per-downloads by 2013.

Developers made $87 million in ad revenue in 2010 and will grow 10 fold by 2015.

50% of revenue from the top grossing iPhone apps comes from in-app purchases.

58% of the most popular developers are creating multiple platforms apps.