CuuDuongThanCong.com
CuuDuongThanCong.com
MasteringAndroidGameDevelopment
CuuDuongThanCong.com
TableofContents
MasteringAndroidGameDevelopment
Credits
AbouttheAuthor
AbouttheReviewers
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmore
Whysubscribe?
FreeaccessforPacktaccountholders
Preface
Whatthisbookcovers
Whatyouneedforthisbook
Whothisbookisfor
Conventions
Readerfeedback
Customersupport
Downloadingtheexamplecode
Downloadingthecolorimagesofthisbook
Errata
Piracy
Questions
1.SettingUptheProject
Therighttoolfortherightgame
Doyouwanttouse3D?
Doyouwanttousephysics?
DoyouwanttouseJava?
ProsofbuildinggameswiththeAndroidSDK
ConsofbuildinggameswiththeAndroidSDK
IwanttheAndroidSDK!
Theproject–YASS(YetAnotherSpaceShooter)
CuuDuongThanCong.com
ActivitiesandFragments
Projectsetup
Creatingthestubproject
Cleaningup
Choosinganorientation
Dealingwithaspectratios
Gamearchitecture
GameEngineandGameObjects
Startingagame
Stoppingagame
Managinggameobjects
UpdateThread
DrawThread
Userinput
Puttingeverythingtogether
Movingforwardwiththeexample
Handlingthebackkey
Honoringthelifecycle
Usingasmuchscreenaswecan
BeforeAndroid4.4–almostfullscreen
Android4.4andbeyond–immersivemode
Puttingfullscreentogether
Goodpracticesforgamedevelopers
Objectpools
Avoidingenhancedloopsyntaxinlists
Precreatingobjects
Accessingvariablesdirectly
Beingcarefulwithfloatingpoints
Performancemyths–avoidinterfaces
Summary
2.ManagingUserInput
CuuDuongThanCong.com
TheInputControllerbaseclass
ThePlayerobject
Displayingaspaceship
Firingbullets
TheBulletgameobject
Themostbasicvirtualkeypad
Limitationsandproblems
Creatingavirtualjoystick
Generalconsiderationsandimprovements
Physicalcontrollers
HandlingMotionEvents
HandlingKeyEvents
Detectinggamepads
SensorsandInputControllers
Selectingcontrolmodes
Summary
3.IntotheDrawThread
UsingGameView
TheGameViewinterface
StandardGameView
SurfaceGameView
UpdatingGameEngine
Updatingthegamelayout
ImprovingDrawThread
Sprites
Updatingthespaceshipandbullets
Addingaframes-per-second(fps)counter
Spawningenemies–theGameController
Procedural/random
Deterministic/static
Hybridapproach
CuuDuongThanCong.com
Ourapproach
Theasteroids
Moreonthetransformationmatrix
Occlusionculling
Parallaxbackgrounds
Multiplebackgrounds
Layers
Summary
4.CollisionDetection
Detectingcollisions
Whocancollide?
UpdatingGameEngine
Handlingcollisions
Rectangularbodies
Addingvisualfeedback
Prosandcons
Circularbodies
Addingvisualfeedback
Prosandcons
Mixedcollisiondetection
Addingvisualfeedback
Otheroptionsforshapes
Optimization
SpatialpartitioningandQuadTree
Duplicatedcollisions
Summary
5.ParticleSystems
Generalconcepts
Particles
ParticleSystem
Initializers
CuuDuongThanCong.com
Modifiers
CompositeGameObjectsandGameEngine
Makinggoodparticlesystems
Oneshot
Asteroidexplosions
Spaceshipexplosions
Emitters
Asteroidtrails
Thespaceship’sengine
Summary
6.SoundFXandMusic
SoundManager
SoundFX
HowtocreatesoundFXs
GameEvents
UsingSoundPool
Playingmusic
Obtainingmusic
MediaPlayer
MusicandActivitylifecycle
EnablinganddisablingmusicandsoundFX
UpdatingMainMenuFragment
UpdatingSoundManager
Disablingsystemsounds
Summary
7.MenusandDialogs
Customfonts
Workingwithbackgrounds
ThepowerofXMLdrawables
Statelistdrawables
Statelistscolors
CuuDuongThanCong.com
Shapedrawables
TheGameFragment
Addingascore
Addinglives
Customdialogs
BaseCustomDialog
Quitdialog
Pausedialog
GameOverdialog
Otherdialogs
Designingformultiplescreensizes
Summary
8.TheAnimationFramework
UpdatingBaseFragment
AnimationDrawable
Animatedsprites
Animatingviews
XMLversuscode
Interpolators
Viewanimation
Animatingdialogs
DelayingtheactioninthedialogstoonDismissed
Pulsatingbuttons
Propertyanimation
ViewPropertyAnimator
Movingaspaceshiparound
Animatingthemainmenu
Summary
9.IntegratingGooglePlayServices
Settingupthedeveloperconsole
Settingupthecode
CuuDuongThanCong.com
Achievements
Architecture
Unlockingachievements
Leaderboards
OpeningthePlayGamesUI
OtherfeaturesofGooglePlayservices
Events
Quests
Gifts
Savedgames
Multiplayergames
Summary
10.TotheBigScreen
Projectconfiguration
TestingforAndroidTV
DeclaringaTVActivity
Providingahomescreenbanner
Declaringitasagame
DeclaringLeanbacksupport
Declaringtouchscreencapabilityasnotrequired
Reviewingthemanifest
Showingcontrollerinstructions
Dealingwithoverscan
Controller-basednavigation
Dialogsandcontrollers
Beyondthisbook
Summary
A.APILevelsforAndroidVersions
Index
CuuDuongThanCong.com
CuuDuongThanCong.com
MasteringAndroidGameDevelopment
CuuDuongThanCong.com
CuuDuongThanCong.com
MasteringAndroidGameDevelopment
Copyright©2015PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,
ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthe
publisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyofthe
informationpresented.However,theinformationcontainedinthisbookissoldwithout
warranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,andits
dealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecaused
directlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthe
companiesandproductsmentionedinthisbookbytheappropriateuseofcapitals.
However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:June2015
Productionreference:1250615
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78355-177-4
www.packtpub.com
CuuDuongThanCong.com
CuuDuongThanCong.com
Credits
Author
RaulPortales
Reviewers
SergioViudesCarbonell
AntonioHernándezNiñirola
CommissioningEditor
NadeemN.Bagban
AcquisitionEditor
HarshaBharwani
ContentDevelopmentEditor
ArunNadar
TechnicalEditor
RuchiDesai
CopyEditors
StephenCopestake
AkshataLobo
ProjectCoordinator
NikhilNair
Proofreader
SafisEditing
Indexer
MonicaAjmeraMehta
Graphics
AbhinashSahu
ProductionCoordinator
ConidonMiranda
CoverWork
ConidonMiranda
CuuDuongThanCong.com
CuuDuongThanCong.com
AbouttheAuthor
RaulPortalesisasoftwareengineerwhoworksasacontractconsultantwithPlattySoft.
HecofoundedthegamestudioThePillTree,whichranforayearandproducedseveral
titlesthatwerefeaturedbyGooglePlay,includingChalkBallandSpaceCat.
HehasbeenaGoogleDeveloperExpertforAndroidsincethestartof2015,andheloves
publicspeaking.HehaspresentedatseveralDroidConsandGameDevelopers
conferences,talkingabouthowtosurviveasanindiegamedeveloper.
Atthemoment,RaullivesinDublinandyoucaneasilyfindhimcollaboratingwiththe
localcommunityondifferentmeetups,especiallytheonesorganizedbyGDGDublin.
CuuDuongThanCong.com
CuuDuongThanCong.com
AbouttheReviewers
SergioViudesCarbonellisa32-year-olddeveloperfromElche(Spain).Hehaslovedto
playvideogamessincehischildhooddays(sincetheZXSpectrumwasaround).Also,he
hasdrawnandcomposedelectronicmusicasahobby.Then,hestartedcodingandstudied
computerengineeringattheUniversityofAlicante.
Hestartedworkingasasoftwareandwebdeveloper.Buthealwayswantedtocreatevideo
games.So,hefoundedBaviuxandnowSergio,designinganddevelopingmobileappsand
games.HehasreviewedthefollowingbooksforPacktPublishinginthepast:
AndEngineforAndroidGameDevelopmentCookbook
LearningAndEngine
MobileGameDesignEssentials
MasteringAndEngineGameDevelopment
JavascriptSecurity
IwouldliketothankRaulPortalesforwritingthisbook.Specialthanksgotomywife,
Estefanía,whoencouragesandsupportsmeeveryday.
AntonioHernándezNiñirolaisaEuropeanPhDcandidateinsoftwareengineeringinthe
lastphaseofhisdoctorateprogram.HehasaBScincomputerscienceandamasters
degreebytheUniversityofMurciainSpain.
CurrentlylocatedinSanFranciscosinceMay2015,heisworkingaspartoftheAndroid
developmentteamatYelp.
Intheacademicyear2013-14,heworkedwiththeDepartmentofSoftwareEngineeringin
theUniversitéMohammedVinRabat.Thiswasagreatopportunitytofocusonhis
researchonmobileusabilityandresultedinseveralacademicpapersforbothJCRjournals
andCOREconferences.
HehasalsocollaboratedwithPacktPublishinginthepastasbothauthorandreviewer.If
youwanttolearnmoreadvancedtechniquesontestingandsecurityforAndroid,check
outhisbookTestingandSecuringAndroidStudioApplications,alsopublishedbyPackt
Publishing.IfyouarenewtoAndroiddevelopment,youcancheckthesebookshehas
reviewed:AndroidStudioApplicationDevelopmentandAndroidStudioEssentials.
Formoreinformationonhim,visithiswebsite()andfollowhimon
Twitterat@hdezninirola.
CuuDuongThanCong.com
CuuDuongThanCong.com
www.PacktPub.com
CuuDuongThanCong.com
Supportfiles,eBooks,discountoffers,and
more
Forsupportfilesanddownloadsrelatedtoyourbook,pleasevisitwww.PacktPub.com.
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFand
ePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandas
aprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwith
usat<>formoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signup
forarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooks
andeBooks.
/>DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigital
booklibrary.Here,youcansearch,access,andreadPackt’sentirelibraryofbooks.
CuuDuongThanCong.com
Whysubscribe?
FullysearchableacrosseverybookpublishedbyPackt
Copyandpaste,print,andbookmarkcontent
Ondemandandaccessibleviaawebbrowser
CuuDuongThanCong.com
FreeaccessforPacktaccountholders
IfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccess
PacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsfor
immediateaccess.
Allyourandroidarebelongtous.
CuuDuongThanCong.com