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

Create an Unblock Game – Adding Interaction

$
0
0

This is the second installment in our Corona SDK Unblock Puzzle game tutorial. In today’s tutorial, we’ll add to our interface by creating the interactive elements of the unblock game. Read on!


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 + 40)})
	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: Game Background

This code places the game background image on the stage:

-- Game BG
gameBg = display.newImage('gameBg.png', 10, 10)

Step 6: Movements TextField

Next we add the movements textfield to the stage. This will count the number of moves done by the player.

-- Movements Textfield
movements = display.newText('0', 211, 66, display.systemFont, 16)
movements:setTextColor(224, 180, 120)

Step 7: Create Level

This part creates the blocks defined in the Level variable using a double for statement.

	-- Create Level
	hblocks = display.newGroup()
	vblocks = display.newGroup()
	for i = 1, #l1 do
		for j = 1, #l1[1] do
			if(l1[i][j] == 1) then
				local v = display.newImage('vrect.png', 10 + (j * 50)-50, 120 + (i * 50)-50)
				v:addEventListener('touch', dragV)
				vblocks:insert(v)
			elseif(l1[i][j] == 2) then
				local h = display.newImage('hrect.png', 10 + (j * 50)-50, 120 + (i * 50)-50)
				h:addEventListener('touch', dragH)
				hblocks:insert(h)
			elseif(l1[i][j] == 3) then
				s = display.newImage('square.png', 10 + (j * 50)-50, 120 + (i * 50)-49)
				s:addEventListener('touch', dragH)
			end
		end
	end
	 gameListeners('add')
end

Step 8: Game Listeners

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

function gameListeners(action)
	if(action == 'add') then
		Runtime:addEventListener('enterFrame', update)
	else
		Runtime:removeEventListener('enterFrame', update)
	end
end

Step 9: Horizontal Drag

The next function handles the horizontal drag of the blocks.

function dragH(e)
	e.target.lastX = 0
	local currentX = 0
	local initX = 0
	if(e.phase == 'began') then
		e.target.lastX = e.x - e.target.x
		initX = e.target.x
		movements.text = tostring(tonumber(movements.text) + 1)
	elseif(e.phase == 'moved') then
		e.target.x = e.x - e.target.lastX
		currentX = e.target.x
		-- Calculate direction
		if(initX < currentX) then
			dir = 'hl' --horizontal-left
		elseif(initX > currentX) then
			dir = 'hr' --horizontal-right
		end
	end
end

Step 10: Vertical Drag

Now we create the vertical drag function.

function dragV(e)
	e.target.lastY = 0
	local currentY = 0
	local initY = 0
	if(e.phase == 'began') then
		e.target.lastY = e.y - e.target.y
		initY = e.target.y
		movements.text = tostring(tonumber(movements.text) + 1)
	elseif(e.phase == 'moved') then
		e.target.y = e.y - e.target.lastY
		currentY = e.target.y
		-- Calculate direction
		if(initY < currentY) then
			dir = 'vu' --Vertical-upwards
		elseif(initY > currentY) then
			dir = 'vd' --Vertical-downwards
		end
	end
end

Step 11: Hit Test Function

We’ll use an excellent and useful function for collision detection without physics. You can find the original example and source at the CoronaLabs Code Exchange web site.

function hitTestObjects(obj1, obj2)
        local left = obj1.contentBounds.xMin <= obj2.contentBounds.xMin and obj1.contentBounds.xMax >= obj2.contentBounds.xMin
        local right = obj1.contentBounds.xMin >= obj2.contentBounds.xMin and obj1.contentBounds.xMin <= obj2.contentBounds.xMax
        local up = obj1.contentBounds.yMin <= obj2.contentBounds.yMin and obj1.contentBounds.yMax >= obj2.contentBounds.yMin
        local down = obj1.contentBounds.yMin >= obj2.contentBounds.yMin and obj1.contentBounds.yMin <= obj2.contentBounds.yMax
        return (left or right) and (up or down)
end

Step 12: Vertical Borders

This code limits the movement by creating virtual borders.

function update(e)
	-- Vertical Borders
	for i = 1, vblocks.numChildren do
		if(vblocks[i].y >= 370) then
			vblocks[i].y = 370
		elseif(vblocks[i].y <= 170) then
			vblocks[i].y = 170
		end

Step 13: Collisions

Here we handle the collisions between the vertical and horizontal blocks.

		-- Hit Test
		if(hitTestObjects(vblocks[i], hblocks[i]) and dir == 'vu') then
			vblocks[i].y = hblocks[i].y + 75
		elseif(hitTestObjects(vblocks[i], hblocks[i]) and dir == 'vd') then
			vblocks[i].y = hblocks[i].y - 75
		end
		if(hitTestObjects(vblocks[i], hblocks[i]) and dir == 'hr') then
			hblocks[i].x = vblocks[i].x + 75
		elseif(hitTestObjects(vblocks[i], hblocks[i]) and dir == 'hl') then
			hblocks[i].x = vblocks[i].x - 75
		end
		if(hitTestObjects(s, vblocks[i])) then
			s.x = vblocks[i].x - 50
		end
	end

Step 14: Horizontal Borders

This code limits the movement horizontally by creating virtual borders.

	-- Horizontal Borders
	for j = 1, hblocks.numChildren do
		if(hblocks[j].x >= 260) then
			hblocks[j].x = 260
		elseif(hblocks[j].x <= 60) then
			hblocks[j].x = 60
		end
	end
	-- Square
	if(s.x >= 320) then
		display.remove(s)
		display.remove(vblocks)
		display.remove(hblocks)
		alert()
	elseif(s.x <= 35) then
		s.x = 35
	end
end

Step 15: Alert

The alert function stops the game, displays a message and removes the active listeners.

function alert()
	gameListeners('rmv')
	local alertView = display.newImage('alert.png', 80, display.contentHeight * 0.5 - 41)
	transition.from(alertView, {time = 300, y = -82})
endend
end

Step 16: 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 17: 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 18: 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 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 will do that for you.


Step 19: Testing in the 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 20: 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

In this tutorial you learned how to make our interface come to life by allowing the user to interact with the game’s pieces. Experiment with the final result and try to make your own custom version of the game! I hope you liked this tutorial series and found it helpful. Thank you for reading!


Viewing all articles
Browse latest Browse all 1836

Trending Articles