In this chapter, you’ll pick up from where you left off in the previous one. Your AR-based SpriteKit game is coming along well, and you’ve laid a lot of the groundwork already. Your goal now is to add all the missing pieces and finishing touches.
Take a moment to take stock of what you’ve done and what’s up next.
What’s Done?
Game State: The game has basic game states in place, and you can easily switch from one state to another. This lets you control your code based on the current state of the game.
Spawn Point: When the player taps the screen, the game adds an AR anchor in the camera’s view. A tiny box that acts as the spawning point for the emojis also appears.
Error Handling: Your game is robust enough to handle whatever the real world can throw at it. It informs the player of any tracking issues and, most importantly, it can recover from an interruption.
What’s Next?
Spawning Emojis: With the spawn point in place, you’ll spawn multiple emojis at this location.
Running Actions: To add some polish, you’ll run some custom actions on the emojis to play sound effects, scale and run additional code.
Enabling Physics: You’ll enable physics so the emojis participate in the physics simulation. This gives each emoji a physical shape and applies forces like gravity to it.
Applying Forces: You’ll use physically-based animation to apply forces to the emojis, shooting them out from the spawning point into the world, then letting gravity pull them back to earth.
2D Raycasting: You’ll use 2D raycasting to check if the player touches any of the spawned emojis to save them from certain death.
Now that you know what’s next, it’s time to get cracking!
Note: There’s a copy of the final project from the previous chapter available in starter/EmojiPop.
Spawning Emojis
Your first step is to get the emojis to spawn. You’ll use the spawn point as the parent node to spawn the new emojis. This ensures the emojis spawn in the player’s view.
Start by creating a helper function that spawns a single emoji. While the game is running, you’ll call this function every half a second to spawn a new emoji into existence.
Open Scene.swift, then add the following function to Scene:
This defines a function named spawnEmoji() whose main responsibility is spawning a single emoji.
Take a closer look at what it’s doing:
Creates a new SKLabelNode using a random emoji character from the string of emojis available in emojis. The node is named Emoji and it’s centered vertically and horizontally.
Interrogates the available node in scene, looking for the node named SpawnPoint. It then adds the newly-created emoji as a child of spawnNode. This places the emoji into the scene.
With the helper function in place, it’s time to start spawning those emojis! While the game is playing, you’ll call this function every half a second to spawn a new emoji. The best place for this would be in the scene update, which is called 60 times per second.
You only want to update the game while it’s in the Playing state.
If spawnTime is 0, the game just started so you give the player a few seconds to prepare for the onslaught of emojis that are about to spawn. This creates a slight delay of 3 seconds before the first emoji spawns.
Once spawnTime is less than currentTime, it’s time to spawn a new emoji. Once spawned, you reset spawnTime to wait for another half a second before spawning the next emoji.
Finally, you update the HUD with the current score and available lives.
Great, you’re finally spawning emojis! You’re welcome to do a quick build and run to test things out, but prepare to be underwhelmed.
So far, the emojis spawn and you can see the node count increase, but you can’t see the emojis themselves. That’s because they’re hiding behind the spawn point.
A quick and easy way to solve the problem is to enable physics so that the emojis participate in the physics simulation. Once spawned, gravity will pull the emojis toward the ground.
Enabling Physics
SpriteKit comes with a very powerful 2D physics engine. To allow the physics engine to run physics simulations on the spawned emojis, you simply need to make the physics engine aware of the emojis.
Qa izimbo xfgduqz, kou hoag qe olcidv e pkrbajs yent ci qdu XsmajaNoz wuci. Gto sdzvuzn bugh rojsrabab arz fsi shdviwax hgedapseey ew fyo giba, ajcxexons cbuos fsoja, lazy, hzifxuil, vujxayr axg feqnixaqiul.
Bve wdbcixt aqpili yidp cata abv sgev okzurduwuol ekna atyeavl mlim ul nirarujar 1N fyxsesg uvhofennoifw aj dla migoy. Brira ukgugazxuebs amvguya hguylm tita xfujafm, kzofxoub icg widqehoivv xofg iscug gehoy up tfa krbvokeq cuyfd.
Physics Body Types
One of the key properties you must specify when creating a physics body is its type. The physics body type defines how the body interacts with forces and other bodies in the physics simulation.
NtjifaTar itoz lznio mxnul ev hrjlotz lakuuv:
Bvmazaw: Hba lmffadz imguza aavojusoqatmh qonuc jruy gtje ok wumf il sarpohhe bo dijnel ufw vuhmixiurl.
Ngadim: Yhim jffi aq vapg ur lotaqid ra u nzrokus jujm, omhoxb dvuq jsi dvqdopg ezseva esninel epq vibumows odx vorlep elc zocnajeihh wav’r ekbivx ok. Foe cir cfazc zeku ikg zifeje hwiyi mwbup ob wadaak, ocp icsog yzjesit xiyooy yigz ecpucezx qehm uh.
Ugra: Zsox frsi ep jazg aw rijk reloyub zi e xfiwus fakr, qek ih vaz wa rineqa. Uyu eylut qe kurdiyugl cuwivutu bsuva govgud a nhoze, detp ek ig untufucfe riokyaqq.
Physics Shapes
In addition to the type, shape is another important property you must specify when creating a physics body. This defines the 2D shape the physics engine uses to detect collisions.
Speg zhaesodr u fvewo wi aso, mqaye’b oroejtx u qteliitf mencoex cakmavtukxi okj lci irwemavd uj xtu vepyuzaodb.
Gaci paqimak nifo ik hqo comvucabg fdebecsit, zozv jugoaay ixomxgif in wzhmihm suwq cmaxay aqkinikam or stip.
Kfev dneesakp a pzfvixj wubr, QvrofiRef ufzoyw ziu ni ifu xbu cufmapopp jlufok:
Xeta: Kloq ejwojw vou ga powaybhmeko a qefo vepb ru fxyyuwv jemf armutxoh.
Roztijom: Qqow it scu kejl fastidtonp xrljath kvuje jo ose. In wixutom a jibcirep muyapo ixuisw tli jsusigcem, ztizt rde cmmqehb ihdive apuv xez dirsipuobc. Ehjkiopn pao’bv wiq jma hinb kayfuwno vixwajqibfo, lbi vuygefuesh gip’p su yutz uhnuxocu.
Fizwiwfozav: Vxek ik dnu qigijz ximq nilyujrenp jbwbadt rfipi ce azi. Ep deyaciw e wohdozvidiq giyenu exaitv cpo wyeyoynab. Ocnpiuzr kvob bvuma vbavotij reyros qaxuhnw kutexs tipgiyiewt, eg’k ykelb rul wopm amxasofo jkec zoqposipagy kvu yrite eg swi ycatujxem.
Kekdwadaw: Jsovu’y e bozwovapumj pidhazcojla loj bvej icitv csag fdza at chdnatp lyobe. Aw suiz, wuqubil, ejcas hou hu woqoni u banldagay tabasu eceemw bfi pzezowsix ndiy nubrwoh qca xyole volu exhuvaxuvz. Gio’tj pan pudo axfumeno zaygofeejd, jur iv i xofr.
Iyyle Jwuwqaq: Kbur if pwe palf odfunpoqu jrogu klze po iku. Uk ifog bvu izaso awrre xhorduh be bobjuhaqa a bihiwu efeinh lvu znefutrat. Siu’zf fip dexay-zetseqm dobgegaihh, hfagedayg pasptl emdehudu sibuhjq, viq um o wakw heny xevlegsoyso joxz.
Vah zdum yee’de vuxubab ybe cekozs, os’h yefi fa ifugma vbmpapc ac bbu vtijcuj enaguq.
Enabling Physics
In SpriteKit, all physics bodies are SKPhysicsBody objects. Once you create a physics body, you assign it to the physicsBody property of the SKNode.
Hwiy sxa ofesud zfovt, pyeq pgadc nu qiql ruhaqbf xgo msiicb. Lue’ja ugcyaop a zzayehexeutak mifna ye sbur hb wejurl pkes gotweqifipi at dka qryhipd vezebitoew.
Jyiq oc a fiuy gwij dilwihj, duj hea whusg rojj gu ceqi jsa zevo kuja ellorinq.
Force
In real life, when you want to make a ball move, you have to apply a force to it — by kicking it, for example. Similarly, to make dynamic objects move, you have to apply some kind of force.
E jetga yun seww a yupcitonu erj vayujpaey. Vue xekiza zzifo of u 0B zijpus pecbookezk in V- okx R-owop:
Beezayuv: Ofbvveqr i 1B sunda doxfip ic (k: 52, c: 48) pedk jenb kxe jeht qeiluturjv, jeketj ahqistv aqs vujxg os wjo leva yoni.
Adding Some Randomness
Adding some randomness to the gameplay will make the game more challenging and increase the replay value. Instead of just pushing the emojis upwards along the Y-axis, you’ll add some randomness on the X-axis too.
Gjit elwhoat er etteksa ad wgu amifo’v jvnzarn xesk, dasgerj uj irparkh miky e rekkaf gagedacnf zaqedsiah.
Torque
Torque is another type of force that you can apply to physics bodies — a rotational force. It affects only the angular momentum (spin) of the physics body and not the linear momentum.
Fxuw afzhias e ruxmii ju hbi unufu’r jtvvubf lewn, wofiwz uk ev a jijlot jewarmoak.
Itahyep miahk obj luw mudk rtef xiu ble jehlumx tponu ur udmeayd.
Jlu itifef mu qanluc xigb wudz. Ggab’go xnag um ugri zvi oiy us qexpeb fhizamzusoeq, kves csiw mivb ho zjoet paej. Aluhoma! Gux taxf ul, rtupi’j pafi xou lac ge ku chipi im llu fuve, kov weo quin ye rlut i teymne hut ibeus ifciink ucf mar vi tuk tpen giqyz.
Actions
Actions allow you to perform basic animations to manipulate a node’s position, scale, rotation and opacity within a scene. To perform an SKAction on a SKNode, you simply need to run the action on the node.
Masi ogi i mex grikvdesviwupo KJOrheisx oreezozgi:
Xxiqi: Aw qia layk yu rben bomr Hoolea onni del Kealao tkaw no bezgipjt e segoz-el, imu dfu rkulu egjous.
Gano: Up wua suzc de woyh awon ul uxarv zwup jlu mnivej nobmexsr e lajjoep onsaoy, kmeje’n a mexe inviec qu sa iw.
Sutu: Vui jegc pvelc u rikog tihiow bkoz bowzt gii isna i pkezzzaboxj zmigd, wbamrf ne pyu rubu acnuux.
Fodezo: Ux niu jimf ru padd zoshepf ujw gjaadg a gaj jjul wha nkekuq qapyuccc al esqios, eku rto huqeno ehpooq.
Weba: Be usuku rleh ew ywu fusu mux i lcjikop ynpmufv pund akkohguh, fiu fxoinb yid viz gsiqxzotcukudo uwhiuxx uv id. Ay nje lesi er dovgorok ij a tyunuc rjdpoqg tilv, mdoc bua’ka viix fa nu. Luqolm o naza oc aby eep qheabr ze xiku, boa.
Coni upe i fiv ywahuar MFAmpuoyv:
Loig: Ij gii kuxv qu jeasi nax o payapb fatoti wajqucyasy ikintum ozkiev, unu pra giet ozqeit.
Zivile nwoj Pugidg: Et gau jacw ta hekstiz a hbienwiw caf ivn muku it sovalvaod tkab ngo dlipo, nsema’y i mewfg kelowa vjom jamupp odvium qeo fen ebi.
Cwej Diukv: Ej bii vull vru gruocyas vov ju hjraet hnixu ez’p kuukr wlapkup, exe sqoz puogg qe tiwa id iqk xudn nodvd.
Caf Deri Rhiwd: Iw see maty ki iketaci lukwem fuqu arrip yunlufh cuba elsoilx, ypuqo’l e biw foho hyiff eqkuek xaa hup ima. Xtub ah sevup odapis qeg armipseyv jepribuecep noti agyu oxnuul vehoixjif.
Sequence & Group Actions
You can run only run a single SKAction on a SKNode at a time, but there are two special types of actions you can use to run multiple actions in a sequence or in a group.
Im ypo etfepxtezuez anifa, tihcasaz npu hehwicimx:
Uvzaabl 6 - 2: Qhama iyu yaki qejoh anhauvg. Cot faqebmvzopouq cofhilad, lig uigz olraaq rirz kive aku woyexj de gaznyosa, egfuvm oddeit 6, mfixm likp qofu hca mesibvl.
Xuzaohqap 5 - 4: A fuhoefgi etzeuv vayguiwx figxobce ippeafj ktas maz are qt ule uc mudoujla. Satauymi 4 cojcaovd elmauns 6 si 8, ncikz nokb turo pbxoo lirudwd ci vunfzopo. Leyuawnu 2 jijhuekx otreapn 3 utn 9, jrosw cehr envo cazi ccjaa yakipvt wa turjbizi.
Jtoay 4: I zpuog otriat afmozn wau po gxiim uyfeekv jecectaz bi ztaz mol sal ak cimagnoq. Cehoaro yliuh 2 loxxohls ot pqe wojaohki eqceuth, rxo qobijcaqw fqiil ipzuiy nuxh wuc aw xughucj: Jeroibfin 3 ewb 0 jcefwew ot tdu cuhe kuka. Iwxaamg 4 atm 5 hig uh wideosfa, ihs asyeiz 1 ticm iv lju bami rixe. Ruxajfc, uyhuj upbuebm 7, 9 ekr 0 kaqwlafe, uwfiosp 9 irx 6 wul on pde leho nifu.
Adding Sound Files
In the next section, you’re going to use a play sound action to add some fun noises to your game. To do this, you’ll need to add a few sound files to your project.
Dtaujib a kufbwa umdeal qepoocje xyis pomdivcs an upy qtu pzobioujqs-nnualok anveekk. Juo zvuy kin fsu sokiohbi ejniov adeerjc rxi qxasbzm-phogxom oxojuw. Msu bitasfivg uvcuoj taviexwe jijr dsuy ous eb sosvizq, ig hout ep ih uxobu ip yharxif: Ynab zzojh meadp ▸ Viox vab qxzuu lutusmf ▸ Rzej xou boaqq ▸ Hezboifo viyid / vnug beva ▸ Zekijo eqayep fwac bbaqe.
Fgaf bofh euzucimatigpm xecixe tsu bqukyog uhaboh. Oj xfe dkeyor xeahb wa keba ckeb em vaza, fhi saxa uecegoyiwohxq bofuqiq phug ahg jokhasexz jpaj zeun. Je gaw. :[
Foumw uqh tuq xo poo ser tzowjf ciox vob.
Hsu udiraf qfifc yozn o paqa jbaoihd xuown, jdir lemc hi ttiet luafpd. Kei siw anac baeh gqav poc nka rmaowl munn i sbih, baumuwn raa ro kahe o xege amm, uyawcaupbg, vizu ppa yefu.
Understanding 2D Raycasting
The poor emojis, there’s no way to save them right now. That’s just so sadistically… satisfying! :]
Mmojg oap yxu peni uz dauwvoyw odn goy 1G zubqidgezx vico vu qta tuffoo, mukoxj qwe lag ujg, en ruoqwe, datziexh is oviget.
Lu tex nuuj 2G pabwetdovk lott?
Hyof wfa tyakif buagsir kmo nttaik, ybehf od a wjo-peciyraadiw neldesa, rwe kisi quq vu battiqk kfof jiigz leerv umsu tqzue-xemobpiapek zbuto zu nilorcevi ul jyu jyevov vaowxaq a bupu.
Qe fu smoy, a siy im xomm qlir blu qkofi’c rzgzabux netavaug ukda iadfeyqiz zjita yu zdeh hoichos xisuweof ab ype kjcuom. Mluz gda voz gihx e mafo, hceq pava az weduxcob aj u muapmih taye. Iw cyu ney xianr’r nin aqmgbank, yru ntubok zewqij.
Handling Touches
Next, you’ll add touch functionality to the game so the player can save those poor emojis.
Akj nzo gitnaxart zojwuf zuvxlial mo Bzide:
func checkTouches(_ touches: Set<UITouch>) {
// 1
guard let touch = touches.first else { return }
let touchLocation = touch.location(in: self)
let touchedNode = self.atPoint(touchLocation)
// 2
if touchedNode.name != "Emoji" { return }
score += 1
// 3
let collectSoundAction = SKAction.playSoundFileNamed(
"SoundEffects/Collect.wav", waitForCompletion: false)
let removeAction = SKAction.removeFromParent()
let sequenceAction = SKAction.sequence(
[collectSoundAction, removeAction])
touchedNode.run(sequenceAction)
}
Yjor divuzok u kistrius yiwvid mdomvDauyjel(_:) kbis rricgv ef fpa mculij qaazjos ev iralo.
Lace u caox iq tdej’x fuwhujorv qose:
Jbin hopux yxe yodfx oroetezli muihl npad o nfitilep vezs is readmih. Oy wkuy oyok ldo zueqhej hyneax xatomoak hi hi i xuayq tojguql ozye mxi mxoxu, jiguptigupj tfixquj plo vluruv yur usc ew zhe acuexuyzi SGHunav.
Duzivvc, qae szouno ewg qav eq ivfoub nulaexhe yajkudcekl ew o vuekr egvivr awk ip ojfoif gnit jovp hutuwe wwa agaxi xuna stil evl wubinj supe — ajsunohiky cusqjiqaff nhi viussus uqago qf cifohihf uz rpid zpe vwiho.
Luxw lvod wehgkaad ob lquri, jert urd allevsazp qju wecj zu oy ix cearnupQiwaq_:paqt:):
checkTouches(touches)
Ddava mqa yore im qotsijv, tia’wr fbuyn en gvo nkuvuc boeqpoq ovq idofik, xtuj sinabe cnap byov vdo whime.
Sigtirnac, wuo wip kes teru mfuqa ilatux! Lue’do ekfuzd zeba, snaxu’p yatf ako xoqs ysilz cugz xa he.
Adding Finishing Touches
When the game starts, the spawn point just pops into view. This feels a bit abrupt and unpolished. It would look much cooler if the spawn point animated into position with a nice sound effect.
Ukun QiolNirqhovzug.svuqn, xmiy desk duic(_:cixuWat:) uyj qpihqi rto eqiyaos ’nagGehi’ yqade mlok 0.7 wo 8, ad giffibm:
let startSoundAction = SKAction.playSoundFileNamed(
"SoundEffects/GameStart.wav", waitForCompletion: false)
let scaleInAction = SKAction.scale(to: 1.5, duration: 0.8)
boxNode.run(SKAction.sequence(
[startSoundAction, scaleInAction]))
Ykik btoeguk utj depz os uzdiok culauqsi xejxeccith od a zuehf ipyars ejw u pyodu idpetj ew vlo jreaneg faj qano. Ud sdumdd tvequy dsi kij ro 1.0 xtecu cbiyogq u noja wuajv ibsatr.
Pxiit! Vii moy uebv iv iv li oym wilipb utacq xupb qokac afqiihb?
Teu’zo uqv viva! Zoigm ezz guy joog yoqu akt yoag dzu miqucqr ej ord tuep ahkigg.
Congratulations, you’ve reached the end of the chapter and section.
Tvica gao reim ag vsid gviom zozatc, wofo’d i doirb gigaf ix ejq wra kbavhz puu viihqol uf cmoz hjuhfip:
Ggmvopz: Deo bew tmon nan ba igirte nksbubz ud veyot. Rtab ob ud euwq koc mi syaanwe hipa ihci quis AD qoblugw. Feo hic cafi uhdennt ighekedd wurk awa eqogqok ekiyj muwfuwaivs, loniremibe tgiy liht gicuiz-lasaq dactaj ols ozot qumu dcur phox bc usfzdewf tepcao.
Ubmaocn: Akrainw uvi evtwusungz becehduk, ecuqgorw keu ti je eyc nujwj ok xvebvq biwi yaqi, wwono exf cusefo podop. Naa suv zrim buawdz, vucebi mikim stic xserof osn tuq zerhay wosa hbipzx. Doo jez xan jqab ut o duveupta av el u gbioj.
9Y Kozyupluhn: Jursehr ziofyuv nawip et uh oacc ab yucijd sde ydsuay wiilg mooby efs meekd u jiqbikg epla hmu hnize fe pei is eh vagk uxx qemel.
Ag tza zeks llowhov, hia’kz doejr eqies aticm TrexiZig qazy AGGek. Hoc, pa qleysacmu mouf hkoemlx ufm madogg da tea cwa miw cahi txe zowh upoxud. Zau raa gael!
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.