Advertisement

Build an Air Hockey Game - Adding Interaction

by

This Cyber Monday Tuts+ courses will be reduced to just $3 (usually $15). Don't miss out.

This is the second installment in our Corona SDK Air Hockey Game tutorial. In today’s tutorial, we will add to our interface and code the game interaction. Read on!


Also available in this series:

  1. Build an Air Hockey Game - Interface Creation
  2. Build an Air Hockey Game - Adding Interaction

Where We Left Off. . .

Please be sure to check part 1 of the series to fully understand and prepare for this tutorial.


Step 1: Start Button Listeners

This function adds the necesary 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

Step 2: 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)
	
	lastY = titleBg.y
	transition.to(titleBg, {time = 300, y = (display.contentHeight * 0.5) - (titleBg.height + 50)})
	transition.to(creditsView, {time = 300, y = (display.contentHeight * 0.5) + 35, onComplete = function() creditsView:addEventListener('tap', hideCredits) end})
end

Step 3: 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 + 25, onComplete = function() creditsBtn.isVisible = true playBtn.isVisible = true creditsView:removeEventListener('tap', hideCredits) display.remove(creditsView) creditsView = nil end})
	transition.to(titleBg, {time = 300, y = lastY});
end

Step 4: Show Game View

When the Start button is tapped, the title view is tweened and removed, revealing the game view. There are many parts involved in this view, so we'll split them in the next steps.

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

Step 5: Add Walls

Here we create 6 lines that will be used as the table walls.

-- Walls

left = display.newLine(-1, display.contentHeight * 0.5, -1, display.contentHeight * 2)
right = display.newLine(display.contentWidth+1, display.contentHeight * 0.5, display.contentWidth+1, display.contentHeight * 2)
topLeft = display.newLine(0, -1, display.contentWidth - 120, -1)
topRight = display.newLine(display.contentWidth, -1, display.contentWidth * 1.6, -1)
bottomLeft = display.newLine(0, display.contentHeight, display.contentWidth - 120, display.contentHeight)
bottomRight = display.newLine(display.contentWidth, display.contentHeight, display.contentWidth * 1.6, display.contentHeight)

Step 6: Add the Game Background

This code places the game background in the stage.

-- Game Bg

gameBg = display.newImage('gameBg.png')

Step 7: Player

Add the Player paddle with the next code:

-- Player

player = display.newImage('paddle1.png', display.contentCenterX-25, display.contentHeight-100)

Step 8: Enemy

The Enemy paddle is created by this line:

-- Enemy

enemy = display.newImage('paddle2.png', display.contentCenterX-25, 10)

Step 9: Scores

Next we add the scores TextFields to use them later.

-- Scores

enemyScore = display.newText('0', 289, 206, 'Courier-Bold', 20)
enemyScore:setTextColor(227, 2, 2)

playerScore = display.newText('0', 289, 240, 'Courier-Bold', 20)
playerScore:setTextColor(227, 2, 2)

Step 10: Puck

This is the puck, it will appear in the center of the stage.

-- Puck

puck = display.newImage('puck.png', display.contentCenterX-20, display.contentCenterY-20)

Step 11: Add Physics

Lastly, we add the physics to the graphic elements. We also set a Puck property to false to prevent its rotation.

-- Set Physics

physics.addBody(left, 'static')
physics.addBody(right, 'static')
physics.addBody(topLeft, 'static')
physics.addBody(bottomLeft, 'static')
physics.addBody(topRight, 'static')
physics.addBody(bottomRight, 'static')

physics.addBody(puck, 'dynamic', {radius = 20, bounce = 0.4})
puck.isFixedRotation = true
physics.addBody(player, 'dynamic', {radius = 25})
physics.addBody(enemy, 'static', {radius = 25})

gameListeners('add')
end

Step 12: Drag Physics Body

The next function handles the Player drag.

It uses a different method than previous tutorials as we want to drag the object without losing its physics interactions. You can read more about it in the Corona website.

function dragBody(event)
	gameUI.dragBody( event, { maxForce=20000, frequency=10, dampingRatio=0.2, center=true } )
end

Step 13: Game Listeners

This function adds the necessary listeners to start the game logic.

function gameListeners(action)
	if(action == 'add') then
		player:addEventListener('touch', dragBody)
		Runtime:addEventListener('enterFrame', update)
		timerSrc = timer.performWithDelay(100, moveEnemy, 0)
	else
		player:removeEventListener('touch', dragBody)
		Runtime:removeEventListener('enterFrame', update)
		timer.cancel(timerSrc)
		timerSrc = nil
	end
end

Step 14: Move Enemy

A Timer is used to move the enemy, this will create a delay allowing the enemy to miss hitting the puck.

function moveEnemy(e)
	-- Move Enemy
	
	if(puck.y < display.contentHeight * 0.5) then
		transition.to(enemy, {time = 300, x = puck.x})
	end
end

Step 15: Update Score

The Update function runs every frame.

This part of the code checks if the puck has left the stage through the space where no walls are added. If true, it increases the appropiate score textfield.

function update()
	-- Score
	
	if(puck.y > display.contentHeight) then
		enemyScore.text = tostring(tonumber(enemyScore.text) + 1)
	elseif(puck.y < -5) then
		playerScore.text = tostring(tonumber(playerScore.text) + 1)
	end

Step 16: Rest Puck Position

These lines reset the puck position when it leaves the stage and play a goal sound.

-- Reset Puck position
	
if(puck.y > display.contentHeight or puck.y < -5) then
	puck.x = display.contentCenterX
	puck.y = display.contentCenterY
	puck.isAwake = false
	audio.play(bell)
end

Step 17: Player Stage Border

Here we prevent the player paddle from going into the enemy part of the stage.

	-- Keep paddle on player side
	
	if(player.y < display.contentWidth - 60) then
		player.y = display.contentWidth - 60
	end
end

Step 18: 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()

Step 19: Loading Screen

The Default.png file is an image that will be displayed right when you start the application while the iOS loads the basic data to show the Main Screen. Add this image to your project source folder, it will be automatically added by the Corona compiler.


Step 20: Icon

Using the graphics you created before you can now create a nice and good looking icon. The icon size for the non-retina iPhone icon is 57x57px, but the retina version is 114x114px and the iTunes store requires a 512x512px version. I suggest creating the 512x512 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 will do that for you.


Step 21: Testing in Simulator

It's time to do 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 final step!


Step 22: 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 will be ready for device testing and/or submission for distribution!


Conclusion

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

I hope you liked this tutorial series and find it helpful. Thank you for reading!

Advertisement