Quantcast
Channel: Envato Tuts+ Code - Mobile Development
Viewing all articles
Browse latest Browse all 1836

CoronaSDK: Create an Entertaining Bouncing Game

$
0
0

In this tutorial, I’ll show you how to create a bouncing game with the Corona SDK. You’ll learn more about the Drawing API, touch controls, and random numbers. The objective of this game is to use a paddle to prevent balls from touching the floor. To learn more, read on!

1. Application Overview

App Overview

We’ll use pre-made graphics to code an exciting game using Lua and Corona SDK API’s.

Upon completion, the player will use the touch screen on the device to control a paddle. The parameters in the code can be modified to customize the game.


2. Target Device

Target Device

The first thing we have to do is select the platform we want to run our app in. This way we’ll be able to choose the size for the images we will use.

The iOS platform has the following characteristics:

  • iPad 1/2/Mini: 1024x768px, 132 ppi
  • iPad Retina: 2048×1536, 264 ppi
  • iPhone/iPod Touch: 320x480px, 163 ppi
  • iPhone/iPod Retina: 960x640px, 326 ppi
  • iPhone 5/iPod Touch: 1136×640, 326 ppi

Because Android is an open platform, there are many different devices and resolutions. Some of the common screen characteristics are:

  • Asus Nexus 7 Tablet: 800x1280px, 216 ppi
  • Motorola Droid X: 854x480px, 228 ppi
  • Samsung Galaxy SIII: 720x1280px, 306 ppi

In this tutorial we’ll focus on the iOS platform with the graphic design, specifically to develop for distribution to an iPhone/iPod touch, but the code presented here applies to Android development with the Corona SDK as well.


3. Interface

Interface

A simple and friendly interface will be used. This involves multiple shapes, buttons, bitmaps, and more.

The interface graphic resources necessary for this tutorial can be found in the attached download.


4. Export Graphics

Export Graphics

Depending on the device you have selected, you may need to export the graphics in the recommended PPI. You can do that in with your favorite image editor.

I used the Adjust Size… function in the Preview app on Mac OS X.

Remember to give the images a descriptive name and save them in your project folder.


5. App Configuration

We’ll use an external file to make the application become full-screen across devices (the config.lua file). This file shows the original screen size and the method used to scale that content in case the app runs in a different screen resolution.

application=
{
 content=
{
 width=320,
 height=480,
 scale="letterbox"
},
}

2. Main.lua

Let’s write the application!

Open your preferred Lua editor (any Text Editor will work, but you won’t have syntax highlighting) and prepare to write your awesome app. Remember to save the file as main.lua in your project folder.


7. Code Structure

We’ll structure our code as if it were a Class. If you know ActionScript or Java, you’ll find the structure familiar.

Necessary Classes
Variables and Constants
Declare Functions
    contructor (Main function)
    class methods (other functions)
call Main function

8. Hide Status Bar

display.setStatusBar(display.HiddenStatusBar)

The above code hides the status bar. The status bar is the bar on top of the device screen that shows the time, signal, and other indicators.


9. Background

Background

A simple vector is used as the background for the application interface. The next line of code creates it.

-- Graphics
-- [Background]
local bg = display.newRect(0, 0, display.contentWidth, display.contentHeight)
bg:setFillColor(52, 46, 45)

10. Title View

Title View

This is the Title View, it will be the first interactive screen to appear in our game. These variables store its components:

-- [Title View]
local title
local playBtn
local creditsBtn
local titleView

11. Credits View

Credits View

This view will show the credits and copyright of the game. This variable will be used to store it:

-- [CreditsView]
local creditsView

12. Instruction Message

Instructions

An instruction message will appear at the start of the game and will be tweened out after 2 seconds. You can change the time later in the code.

-- Instructions
local ins

13. Color Circles

Buttons

Here are the circles or balls. The objective of the game is to prevent them from touching the bottom of the screen.

-- Color Circles
local circles = display.newGroup()

14. Alert

Alert

This is the alert that will be displayed when a ball touches the floor. It will display the score and end the game.

-- Alert
local alertView

15. Sounds

Sounds

We’ll use Sound Effects to enhance the feeling of the game. The sounds used in this game were created in as3sfxr.

-- Sounds
local bounceSnd = audio.loadSound('bounce.wav')
local loseSnd = audio.loadSound('lose.wav')

16. Variables

These are the variables we’ll use. You can read the comments in the code to learn more about them.

-- Variables
local circleTimer -- Adds a new circle every time is called
local colors = {{71, 241, 255},{255, 204, 0},{245, 94, 91},{0, 255, 204},{250, 140, 254},} -- Possible colors for the circles (R, G, B)

17. Declare Functions

Next, declare all functions as local at the start.

-- Functions
local Main = {}
local startButtonListeners = {}
local showCredits = {}
local hideCredits = {}
local showGameView = {}
local gameListeners = {}
local moveBar = {}
local addCircle ={}
local onCollision = {}
local alert = {}

18. Constructor

During this step we’ll create the function that initializes the game logic:

function Main()
	-- code...
end

19. Add Title View

Now we’ll place the TitleView in the stage and call a function that adds the tap listeners to the buttons.

function Main()
	title = display.newImage('title.png')
	playBtn = display.newImage('playBtn.png', 130, 248)
	creditsBtn = display.newImage('creditsBtn.png', 125, 316)
	titleView = display.newGroup(title, playBtn, creditsBtn)
	startButtonListeners('add')
end

20. Start Button Listeners

This function adds the necessary listeners to the TitleView buttons:

function startButtonListeners(action)
	if(action == 'add') then
		playBtn:addEventListener('tap', showGameView)
		creditsBtn:addEventListener('tap', showCredits)
	else
		playBtn:removeEventListener('tap', showGameView)
		creditsBtn:removeEventListener('tap', showCredits)
	end
end

21. Show Credits

The credits screen is shown when the user taps the about button, a tap listener is added to the credits view to remove it.

function showCredits:tap(e)
	playBtn.isVisible = false
	creditsBtn.isVisible = false
	creditsView = display.newImage('credits.png', 0, display.contentHeight)
	transition.to(creditsView, {time = 300, y = display.contentHeight - (creditsView.height - 40), onComplete = function() creditsView:addEventListener('tap', hideCredits) end})
end

22. Hide Credits

When the credits screen is tapped, it’ll be tweened out of the stage and removed.

function hideCredits:tap(e)
	transition.to(creditsView, {time = 300, y = display.contentHeight + 40, onComplete = function() creditsBtn.isVisible = true playBtn.isVisible = true creditsView:removeEventListener('tap', hideCredits) display.remove(creditsView) creditsView = nil end})
end

23. Show Game View

When the Play button is tapped, the TitleView is tweened and removed, revealing the GameView. There are many parts involved with this view, so we’ll split them into the next few steps.

function showGameView:tap(e)
	transition.to(titleView, {time = 300, x = -titleView.height, onComplete = function() startButtonListeners('rmv') display.remove(titleView) titleView = nil end})

24. Instructions Message

The following lines add the instructions message:

ocal ins = display.newImage('ins.png', 160, 355)
	transition.from(ins, {time = 200, alpha = 0.1, onComplete = function() timer.performWithDelay(2000, function() transition.to(ins, {time = 200, alpha = 0.1, onComplete = function() display.remove(ins) ins = nil end}) end) end})

25. Add Paddle

This step creates the paddle and places it on the stage. A name can be added later for easier access.

-- Add Bar
	bar = display.newRoundedRect(70, 340, 160, 10, 3)
	bar.name = 'bar'

26. Walls

Now we’ll create walls around the screen to prevent the balls from leaving the stage.

-- Walls
left = display.newLine(0, 240, 0, 720)
left.isVisible = false
right = display.newLine(320, 240, 320, 720)
right.isVisible = false
bottom = display.newLine(160, 480, 480, 480)
bottom.isVisible = false

27. Score

Here’s a score TextField to create at the top-right of the stage:

-- Score
	score = display.newText('0', 300, 0, 'Futura', 15)

28. Physics

Next we need to add physics to our objects. Here we’ll use the Filter property that prevents certain objects from colliding with each other. This prevents our circles from colliding while keeping collisions between the walls and paddle. You can find a simple explanation of its behavior at the Corona Site.

	-- Physics
	physics.addBody(bar, 'static', {filter = {categoryBits = 4, maskBits = 7}})
	physics.addBody(left, 'static', {filter = {categoryBits = 4, maskBits = 7}})
	physics.addBody(right, 'static', {filter = {categoryBits = 4, maskBits = 7}})
	physics.addBody(bottom, 'static', {filter = {categoryBits = 4, maskBits = 7}})
	gameListeners('add')
end

29. Game Listeners

The following function adds the necessary listeners to start the game logic:

function gameListeners(action)
	if(action == 'add') then
		bg:addEventListener('touch', moveBar)
		circleTimer = timer.performWithDelay(2000, addCircle, 5)
		bar:addEventListener('collision', onCollision)
		bottom:addEventListener('collision', alert)
	else
		bg:removeEventListener('touch', moveBar)
		timer.cancel(circleTimer)
		circleTimer = nil
		bar:removeEventListener('collision', onCollision)
		bottom:removeEventListener('collision', alert)
	end
end

30. Move the Paddle

Touching the background calls the next function that handles the paddle’s movement. It follows the finger and stays on top of it.

function moveBar(e)
	if(e.phase == 'moved') then
		bar.x = e.x
		bar.y = e.y - 40
	end
	-- Keep bar 1/3 from the top
	if(bar.y < 160) then
		bar.y = 160
	end
end

31. Add a Circle

The circleTimer calls this code. It creates a circle or ball at the top of the screen (which is then moved down by gravity) and gives it a random size and color picked from our colors Table. The color values are then stored to to change the paddle as well. A little push is added in a random direction calculated by the dir and r variables.

function addCircle()
	local r = math.floor(math.random() * 12) + 13
	local c = display.newCircle(0, 0, r)
	c.x = math.floor(math.random() * (display.contentWidth - (r * 2)))
	c.y =  - (r * 2)
	-- Circle color
	local color = math.floor(math.random() * 4) + 1
	c.c1 = colors[color][1]
	c.c2 = colors[color][2]
	c.c3 = colors[color][3]
	c:setFillColor(c.c1, c.c2, c.c3)
	physics.addBody(c, 'dynamic', {radius = r, bounce = 0.95, filter = {categoryBits = 2, maskBits = 4}})
	circles:insert(c)
	--Move Horizontally
	local dir
	if(r < 18) then dir = -1 else dir = 1 end
	c:setLinearVelocity((r*2) * dir, 0 )
end

32. Collisions

This function runs when the paddle collides with a ball. It plays a sound, increases the score, and changes the paddle color.

function onCollision(e)
	audio.play(bounceSnd)
	bar:setFillColor(e.other.c1, e.other.c2, e.other.c3)
	score.text = tostring(tonumber(score.text) + 50)
	score:setTextColor(e.other.c1, e.other.c2, e.other.c3)
	score.x = 300
end

33. Alert

The alert function creates an alert view, animates it, and ends the game.

function alert()
	audio.play(loseSnd)
	gameListeners('rmv')
	alertView = display.newImage('alert.png', 90, 200)
	transition.from(alertView, {time = 200, alpha = 0.1})
	local scoreTF = display.newText(score.text, 145, 253, 'Futura', 17)
	scoreTF:setTextColor(255, 255, 255)
	-- Wait 100 ms to stop physics
	timer.performWithDelay(100, function() physics.stop() end, 1)
end

34. Call Main Function

In order to start the game, the Main function needs to be called. With the above code in place, we’ll do that here:

Main()

35. Loading Screen

Loading Screen

The Default.png file is an image that’s displayed when the application starts while iOS loads the basic data to show in the Main Screen. Add this image to your project source folder, then it will be automatically added by the Corona compliler.


36. Icon

Icon

Using the graphics you created before, you can now create a good looking icon. The icon size for the non-retina iPhone icon is 57x57px, but the retina version is 114x114px. Keep in mind that the iTunes store requires a 512x512px version. I suggest creating the 512×512 version first and then scaling down for the other sizes.

It doesn’t need to have the rounded corners or the transparent glare, iTunes and the iPhone does that for you.


37. Testing in Simulator

Testing

It’s time for the final test. Open the Corona Simulator, browse to your project folder, and then click Open. If everything works as expected, you are ready for the last step!


38. Build

Build

In the Corona Simulator go to File > Build and select your target device. Fill the required data and click Build. Wait a few seconds and your app is ready for device testing and/or submission for distribution!


Conclusion

In this tutorial, we’ve learned about drawing API, timers, random numbers, and other skills that can be incredibly useful in a wide number of games.

Experiment with the final result and try to make your own custom version of the game!

I hope you enjoyed this tutorial series and found it helpful. Thank you for reading!


Viewing all articles
Browse latest Browse all 1836

Trending Articles