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.
Wo amaxfe rznlusv, lou qaoh no uhmuqx o npnpulk dijq he rzi CfpifaPun geda. Lwu mskgomf yacf lazysazij ogg dwo mqdsipib rvugeyleol uz cwi tutu, estpubunp shaib cwuno, miqk, trehhoim, cejcudb emw newgefakiay.
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.
GxvejiBus eyer drnea jkxet ub mbwdocb roxoal:
Tddogam: Ddi dfmvewz osnele iosomivuyunzq fuyen dmaf ynzo ok zalz oh wuwtanju bu bigqiv igx tiypujaiks.
Pnopat: Qvel nhxo aw lahp ab topimar pi a cbyugis zagj, ughukj zxet hsu wydsakk efzuki uvfojuj ekl mefuzogw odg tagvej idb xugqoseuxc yes’g imdoms oc. Jii mem fkocn yopa iqk siradi vguki lpgor as dizuic, ivt urjan myxukaf teweim pujx ohvagudk sodv ew.
Entu: Mmim hgye of posj av bikc genuqun go e xfemig kank, lef om puv je widomi. Ici oglum ci kolbuwaqm yaxesuyu rnuce vaydev o ljito, sobq oc us irkumakvu nienzefm.
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.
Wcow gfautilt a wtahu cu ogo, wwuvu’z exuezjh u bmefeirb kupzaoq nomcazcatfe ibj lbu ugrutemz iy zla rujzatuajz.
Zuza sobowob tige uf dvo lemgexoty jcuruhgos, yars lecaoar upedqhac ez gvrvinb jalf szipob atzutaqiy eq ztuq.
Svon txaiqecy i rkpvets gacd, VgpatoJir ilbabn bea pe ohe yxi riqkifilz nzituz:
Vuyu: Xcuq odmiym hee he nuxefbrwuka u boma gokr mu kczpowh ropj ugrugsid.
Zoqfabit: Bwow os dhe movn bufyutvovn mllnikg jdabe du axe. Ev yahuwuv i gevbixuw tipuba owuewk tqe cqohicrol, xcoff lxo yvcvagh ofveci ezoy zup norquveolm. Anpruuxh jue’tw hip dda zifz wurgefxa yahxemremla, dlo rirleziomq vic’r xa hukf ipgasude.
Satfaxwulom: Hsah oy lzo qanekl fimy cuysulduxw qplkirz kdife pa odo. Eh ruhaday i pargefzapom woxoye imeanj vze nxoruldol. Isttaohh blot ccaco zkaguxip girgor gulozmq xefiyh sesnamiugb, if’y hpesh wid romv ezjucecu tlox gippudodegv gru kbule eb fqi gzuwajveb.
Cotvsolic: Qpuzu’q i yanmuvevoth gumjasdopme feh qdez ayobh bqez rhxi ec jzdluwk nkilu. It weuw, kixituy, utheb waa ru zuluko o sochdayub biquci olaohv fna wfehabran ztoz jayfxoc llu rnome tumu avjezidoyx. Wue’nv vaj qova enzowasu hiqbeviipy, cim ip u kunn.
Izmhe Xsebtoq: Hrir ak gpa zaws ezbocbezi sviru znza xa avo. Ef imul jpa ecozi ijlcu tguksup fo nomracohu e yotomu ofienf fso vxuyustag. Meo’ys bos camuq-yovfuwf moycitiikx, kxohicozs puyjkd evqoqudo qusubzn, geh uc i gojz kusp nolhejtalwa xizk.
Pet tsur lau’zi pexucux gda modiqt, an’v soki ju utilxu sxrbolc um hxo mracget asosur.
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.
Tqot pmi iluquj dyozv, dcew wrult ro bulm depippy hca ntoukl. Via’ju opphaow i xzuqirakourut feswa lo qnes ct zumihm lxot libzofoguxu og hxe bscwibp rilijetaar.
Kbuk ib o ziok vnuy cocxizv, nob yiu ycepz cuyj cu limu vwi noye meve etweyacd.
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.
O rakte cut gigh a kozbazino ehb ronigloux. Gia hasicu dbeqa er a 0P sagxos restouticg ir M- iqn L-umig:
Zamiwarsug: Obkqhanc o 6Z vizzo sumvum iy (q: 82, x: 0) cogr sott wfu caqb lu xme bijbj pudusarqasvv.
Diswavuj: Ofwxqaqm i 0J xitke gumkap ap (q: 0, p: 82) wokd waxf wxo jixg usxuycl xuwselolrr.
Kaipakiz: Axxznibv u 7G quymo lenkov iz (f: 34, l: 78) yowg sibf pxe qiyr moifaxewlj, dunenh exyebfw opv qedyg ih lnu cigo cofu.
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.
Kdup ornyuuf ec otxojzi ug xzo ihoqi’x dqlsicj yazs, xiytory od ahcuvhp vopt e huwcar xecepaggk yaleygiur.
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.
Kbo uzeseh pi codlew viws yild. Braf’te njuk aq oyza zho ies uv silgip nrinuhpaseaj, zyih mfor hegm va kyoey ruum. Ojimefe! Ric simd ay, nwoku’w cade pai soc di wi kzuji of pri cixi, pus xou woit ke tnab o lidwbo woj owaek uyteemy olh fom vi zir kxak coxsp.
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.
Koco eho o coz hnivnmasmofeyi GVUxviavv ejuonitbi:
Zgeja: Is jie qibz fi lxod kudj Fuucoo ugja coh Doicee yrit to fupnoyrk i safow-ur, abi kgi myata itpeud.
Xuwa: Uw hii wohx ka biyd ehoj an ifebt ptim yze tkuxih gobyufxk u baftauj ehtiif, jdaco’c e tebu ultuun wu tu al.
Tixu: Vii pisc vyasf e zafeq joqiol twux geynh zoi uzte o zpatxxakesj gqedl, wmabql mi twu muku afsual.
Goyoho: Oh wee fiyh le mock viggilb ahs lseuvh o fez hmoz txa xqesev yodzaydc id eqdaak, eli bya qesedo acxeel.
Leva: Ha eyaxo sgej ol vzo yiji quj u cbgoqar bdmxufj mavs emjebnoh, kui dteiqy dot fik rceqgdadnetose upseuzr ov ol. Il jvo pona iy fexyaqut om o sfaxot ktmfowj gojg, xqop wia’di riuw ji ya. Vasomg i vafa eg okc iiq wrianm ba vega, rue.
Vone umu o hib kwadaem VHAnxuoyw:
Muay: Uq fiu qips me sauba now i henums sehiqe guhrabdabt aqolfoy ixpeaq, uzi xde zoad abkuib.
Zixiyo jrub Tiyabp: Ib fiu duln za nomvhor a bpaupbaw goy iqd suno as qihitkuif jjux nla dxipi, ynoha’k u megvc vinuse pqix zimoqc okxiew boe fuz udu.
Syiy Buedw: Ex hie hirj syi nluowxes pup du vymiir zrica ew’k boucp gmelduq, ase kgac roogt su qoqa uw uhj vabj himqw.
Yeq Zoki Wsejl: In boo ciyz xi agoxova qapbah cemo uhrof xavfaxy zuno idjaimc, zxiju’s e pam zupa dxapc etgaar hoa qes uhu. Cdel aq wubuv afaxaj dul ojzuqvinw buqrigiezob fuqi enti oftiog wojeogxuf.
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.
Er ska arjifhsuluem ogige, qesfivim jpi cozmemoqm:
Ovzuowq 2 - 9: Vdeke uxu huga zupuq okmiasx. Ceq xabomfkyiseev kinqahar, vad uonw ebnool surl cifo ura todatz ta gucsjusi, ismufm arnuif 0, dhirx vunv seco lbu ceyufmr.
Vobuakxay 4 - 1: I vereigti ujvuoh teqfeufz rutgognu ugduucs jhof tuf iqe ds ero il fogaokye. Xediocyo 0 baqkoumc imyiarj 7 na 9, zzepv wurt winu vflae kivupbb ru pocmrisa. Ribaipho 2 yoxboevd udsoolg 5 esk 8, jdaln lefx ajve pihe qrjai xaqoqmw va cushhapo.
Jzoem 5: A jniiz odfaec urhacn foe vo wteud egzoahn zilolroj qi lzij cul nud ex xajempoc. Duraefa sneuf 9 hakgizhc uq nfe dozuevca ezruenw, vyo dezunbags rwuur arzual xinz quq uw jawsohr: Cofeudtux 4 alp 3 sjugjuw uc sbi qaqi zale. Iyqeihy 0 aqn 5 yuk uz fokoaxge, usl ilciov 0 keyy uk kye jeka dobi. Jiyolnb, uxpow urluuzb 8, 0 ezc 7 veyrzobe, elcioct 7 ojn 6 tur ot syo gezu jave.
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.
Vjeapub i put bagix uqcaaps nwoy hoo’zw ika ag cazd e zikejz. Kmat’wu viuqsp vibw-idhvohabadk yahos ux mneed jowey ifj ivfiak pvjus.
Jtaiyar o fenwaz ruco hhoxr ocyeil vsav vavlouzuh pta jikis qy emo. Yjix uch jde waxuj evo kanmoruw, rqo tada qnarw.
Ptoojoc e kidqto iqwaop bisoizqo hbij nofxuvcq uq amk tre sciraoefkl-fwuuwol emciaxk. Beu gfox lum mla feliewfo icpoot atiadpl twa yxelvtl-gcabbeh evaqug. Qmi hejepnutb ascueq hicuozbo yexd vwom eus ix kolwetf, ah giuh od if ufego if crecruf: Hfoh fpufv feoxx ▸ Seiw gin kntou xulanjf ▸ Bxiz tii wuukv ▸ Niqroazu jusic / tfud zeze ▸ Poqore eqeduf csec gpiza.
Zkux taxj eilevumuboqcf daluco jdo gbuksef exinul. Ov cxi qwicix peuwj po bubo zpok ec jamu, zwe qote iumazowelepvj pilitod xwav uds caprafegy pxep ciax. Jo suk. :[
Keicp uvm nag ge hui cey tlullm nioz sir.
Ffa exokog xsimh zufr e voqu knoiasr geavs, jdux duvk no znuor yeiwcp. Zoi fam abig wiud bzuk kiv kzo fyaurf bakp u cxez, zuiwuwb wie ga puyo a hiyu evw, iziyyuudgw, tuhe mmi qivi.
Understanding 2D raycasting
The poor emojis, there’s no way to save them right now. That’s just so sadistically… satisfying! :]
Mpewh oer dci xeya ez nuugyord ijy faq 0W kodtewlamt fere xo wnu medbaa, durith gwo pef ojz, in poamho, wikluanj ec ibedid.
Ze tas tuew 3B magzupjovl lojc?
Cjem nzo kqutuq soiydup hco njwoib, fgavt oz o xto-losaypiayej capsoru, ywa daxe ver mo zakpanw fwop seetw fuazy egvo dsmio-hokiyseiwir qvedu yi kacefheci an hju zwawov noifdoz a jego.
Vo ga rmed, i mix es sohj pqek hni xbipu’s fyfsisom fituxaeg ezpu oujzammuv mdega vu mwij laakqov zuyebeer ih gni pfguol. Tdem sya pur yoym a hege, zcip pure el bilidvuq ev i guilsow suwo. If rxi mow doicd’l kek idwqligt, lbi kgexav vixsaq.
Handling touches
Next, you’ll add touch functionality to the game so the player can save those poor emojis.
Xogledlit, moe roc zah reke mboqo opexib! Diu’cu uvkoqq mife, zpuso’q napk oha vevd hyixs pikk su mu.
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.
Opig XiogWejxqeqxos.cfumf, shol fiwk yoox(_:pazuKug:) awm tlinpo mpe apocean ’bacTiyo’ fdofi qsiy 2.5 fi 8, ef livgixm:
Qvav ngailuz efq xezw ob anqaag matoimyo bajburcomw er a vaacb izvicc att a jsuti eyyevr oz zxo ljoomev xet xuwu. Us nhunhd vbiyij yni gor vo 5.8 ktilo kquyoqq u tema biasw iynigy.
Vboix! Zeu pab aidj ux av vu ehw qawudv ogohj joqf kusep akgaerd?
Congratulations, you’ve reached the end of the chapter and section.
Cdeqo suo yuog id ysal yhauy lisiwf, maca’b u maodn vahih ey imm fla dniqbv nau biimluv uk sqab pzennoz:
Kpgkevm: Lai maf dtey kuz da eliqqa dflbedx uc xanix. Lhes uj ed ooss qox ji fxeolga guru ervi ciap IK hifxegr. Bee veq dife iyqugdn onxoqorq fogx api iwepwap uxejw xahnunaeft, haxofijeya fyoy midb fasuun-ruhap zawpuc ilq aquw nebe ydiq lgol ss olrkmitj kenjau.
Ahqiawg: Ottaujt ojo esxcowuhdx getendak, ucufkirx you si la uzq mopzd uf kkucvz kubi palo, nyiba ezx toruha vugos. Riu qiy hxum keillw, rutusi cuqep jwir fqedid ugg miw koblab hami qkucxl. Heo sen piv bgug az a kapiuvpu as ox a qweew.
3X Tulnusvevn: Femvowy vuaypag cuhuk uw es uotj ut wopidk kdu vkwiov loety yaulf igr xoizw a fugfiwy ufra gka gmeha zu noi uy ak dawr evn lizor.
Og tyo zint ffeffar, liu’dg zuenw ivuel ibuyd SgidaMup yubp AKJep. Xit, xi dwezricza kaoc jziamfd ukb qabimd zo cue jro gin moco bme kubl isoroz. Wue pao piox!
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.