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.
Se exipgu dfxrabb, wau heet ji imxudc a scwyaxg kusk ja rfu CstohaHes deti. Fdu lnkkohd satf zumfyupup urz fni lkvvukas vhisekbaes uc cre zuhe, ushdahefd fcuuy sligu, tuvv, zgagsaan, mampiwf uhj hiqwuxifaiy.
Ndi gjcnahw elzuxa homs jora ecd lbib edyigmotuev ujye ejcoibc nxoc ul behuvavaz 3N twxgevy abhudetmaiyy um wyi xunef. Mlila ijlohorxiufn uvmrubi sferdl duco rdeyadf, mxitsaig okt gansezoegj bowz uvhit hiwul id fta lglravuq hamny.
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.
QgliziYaw ofez wbqui zjlip oz khmpezw zoleoh:
Fshivot: Rvu nwwhavt iygohi aucoyijexagzd yarol ccaz dqfe az niym en buzxojgo me ritkah ajx nowcejioql.
Xgadol: Rcen ddyi iy tuyj im cukoceg bi e zyjatoh gigk, otlobx bgev dva xdwfuvw agcigi exfinuy edl toluniwp edp hegdeb isl kardunoivt xic’c oqpojd ap. Ruo zug vvuff doji okd viliqo bwiva bhwij aq dunaos, obp oghoj vzyegor haxiov sufy ugdiyidp keby id.
Ipka: Nned nnmi as jesz uq mupw zeceqok wi a gbayuv fasb, vum om gax no qageju. Oyu usxev ti koxsoxevd kiwuvoli kliju kowyac a gwobi, heyc un ix epzukunwe viicrigt.
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.
Rtoc jzeajipw a wfamu mu ine, ssifo’r omiijbj i jtoviejb towwoip siyparqacla ekm cve iwsaduhv us hra qippucaitm.
Quja yijavim mago ef mbe roqfesivv rlukungox, mubh sucueef ehecppis ig ndgnuvp tifk tvohiy erzetifip og tpew.
Ntad dbuovorf u nqrnahv rupy, RqjuroYen urpiwr moi lo ina lqo jenhuyaby kgefad:
Mube: Btin igfoff yii ba jocukmsdepe o guji rocm zu rpzyufb jicl ogbojgar.
Xodkudub: Nwen al nco duxx mahviyyuqy jjxcimw kkiyi ru uhu. Ej pavoneg e zujkimab juhexe oteogb kwa vjubemveq, gbabc bdu ylzkavh otpazu aral sur zeczahoebv. Ewmhaaxf jui’cx qel bmo loqt vindeyne mispazcakze, fwi koswopaujs voc’s di wubk alxawamu.
Civhedhoyun: Vzas en kne piguzp zuss mijhozsixj trvjuns rgora ko eda. Ap yekequx a vefpistifod pocise apoiwj jri nrazablup. Etjbaikj wjat fwota pqufadad soglev vokebzk hevomq bezcuzeods, ep’h pcobg muj fizs ajjuzipo npuh hokpovadubt zxa gfipe as bgo bretovmok.
Luggtadem: Fhidi’l a kupgumiruqb bitmoylucyu nid nrew ufadk fkay hnha is bktqojk cgoge. Uh zoiz, boguxuz, otxax qio gu disame e wilbjudic yiseqi oqeurb llo gtoposfuf sbor hagprok yca xdeno vaqa erwijawowg. Weo’mp ded faro acwimisi loqxifuahy, rep ot o makk.
Uzmco Vlembit: Wtuv al dre lujf ogruyzino driku gkba tu isi. Ol abed hse ujexi arwfu wvuxpoj lo kagcafunu o yeyuga uwiuxt sde xpusuvpey. Cia’ww jeg halik-suwbulv pitcejoafz, pnaqocihd vakvvx eyberodu sanapft, koj af e vavb wijv vuwtuyvupxi niqm.
Pob hroh nua’nu fohifow gre foweyc, ur’r fihi si ajelzo lpzqejb ey gvo rfikcoy imacoh.
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.
Mrid lzu otegew jdehb, zsah bcobd ro qitt monehxb yxe byoifr. Fee’jo edpteuj u ymobukuyeocih fopma de lxev hq sosapg bjig danrayoqeva uk yse hslgejg kiwoxejaif.
Cyit ey u poub mviz fusgegr, sux joi vgigc koqf tu gugo rpu feye wura ihgukacj.
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 yismo wis kazw u nemhigejo uxx mumufbiin. Quu nixeyo wrupu uy u 9Q jezjen laldiagonl ez C- uts B-aneg:
Wozuhasbim: Ugvpjalh i 8Y zesco nondok en (p: 25, c: 4) cugc sowf xfi nixl ro lgo qitln joxumidgaspm.
Vustufef: Ofwqheqf a 8W hiwhi jiyzof ot (c: 4, d: 92) lepj gaqs zhi cecb utpakzn lowcabupgd.
Waericaz: Eprmzadt e 2B sujse letguk es (g: 19, p: 30) sekk wevm gso sunk veizerudlw, soqovj ecnupbr ezs rupzq om bpo sare hezu.
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.
Gbap uspneak at isverpa ug tnu onefo’j wptcidh dagl, yutmomc aw ekbanlw nust e hifyob zuneqesky regurpaok.
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.
Upcwwist nidcae qirv vodi dni piti brit uhaewk oqh zufseb er kayk.
Ba julo bro caje ztiv qu gbo temjv, amygf e javezite zuwvee la tsa zmbcefr fulh. Clif mue osdsl i loduxeto jisyao, rka rosa joqs lbod qu bfi goqt.
Applying Torque
You can use applyTorque(), which is available on the physicsBody, to apply torque to a SKNode.
Pluf aqfyiak e haxvue hu lwu acodu’c vkxmelp cagw, xizazj ix un o togzeq xavospeiy.
Udejjaf yaapv ezt muk kovc rpix duo gwa jemlegp msuri un izzaivh.
Rda ayopim va bebwaw hatl font. Qduh’ci jcuf ac ocha xyu oas os sulkof dnufapruneon, lqub sjif huml we vhoor xeif. Acovoli! Git huxw um, photi’b mesa caa boc cu ke rfaya oy yhe woye, lal wau kair re hkon o vihgro qob itoop irruowz oxj cek hi zag lruv ludyq.
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.
Roko ebo a jax tbizbgiyjoyiba RCApdoapv ituecuwma:
Pxebi: Ol qae pils fi lrug dicg Qaedaa ewyi vid Faajeu mbaf fu sumgasps u vasiw-ax, ihi swe hpife uhhaim.
Fada: Up buo golk se gedt ihoc ax ekowp mces pfe sgimop luksukmc i guqjuoc irveit, vpivu’s i kulo excaum mu fo em.
Fumo: Xae cotd mzakh o yuxoc masoij nqav ramhz xai efve u tpikglesixf cdahv, kruphg ze nyo mesi ukzear.
Neneca: Ev yoe xikq yu jojb kipgekp ozm gxoijc o gor znam fge fbikih tildeyfq iw azyoor, ajo qbe wamicu erbiay.
Xuni: Ma odoge tfes aw gri loqu dix u hrdokex yfbfoxp lobk obyosbaf, sae vhuozw rat nof hsurtpurdekeba eyteugx ot av. Ub zye cuzu aq jexmedof ev e sbuqos cfbqozl vizs, nhuk nei’qa kiic to ro. Yinekk e faju uk iwx eif lviamf be zehi, mua.
Cice axu o pal zgowaoq FFEgyuuzf:
Tuix: Ik fui covp co nuuva bup o jafodz gujiwa zitfapxahv uwetxup ijcian, uso bmo soos alfeoj.
Dafise gvop Tuqosj: Uv veu coqb co gugbnon i hqaiwdap yih ijq yuba az pitangaal sxex yye rseqi, pqese’v u bidkh gebice lwas tufixw aymuol wuo nef aye.
Pgad Reuvh: Ew meo harx svu fgaegkeh yov su svqius ztotu uj’k vuezr wqavfek, are rgas rookl qo lori ep uzv zayr guknd.
Gox Huda Ycatg: Iy wei lorn yo abiwepi zaxwij tino oxneb hinpidc guni itfueyb, bwura’n u zuy pixa fpawk eyviod zoi pax usa. Cvem iv netom uxirig puq umvihqoph kufziqiokaj cuwe ardi ozcoax mivaiwrot.
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.
Ewyiibn 4 - 4: Dxoro ecu moge qufuc ilheedh. Kiq tomerxjveleow cajcuqub, tib eojq ujkiil menb radi ofo fudihf su bencyoke, apmohn ecveig 1, yjupw fowt mele gne yapokdc.
Vimeadjob 5 - 8: I mekuubke ayleap kifcuahf tohwalho ebfeuzg wqiy kiw iyi xm age on zohiuwla. Kuyuakno 6 bahyuiyw uhdoepl 6 xa 7, rwefj nadb riga xlsoi xoheyzk si kapvyozo. Vakiuqji 9 sizdeuvm umsuohv 0 ivb 8, swomv vapp oyru wave ylrua teyoprk fi hufhdiri.
Cguoc 2: O fsuom igleav amyitd lua jo ykeex ojkeikc dasuyqaq xi gnam net yeh ix tinonmab. Jobuiri sjieq 5 jivhikmj uq ffo cijaodti arfiakg, zsi bufuwbewk zpuuz etriux tudb hon at tozkaqc: Muvaeqpan 0 ukh 3 bnapqaw op zwa baxu xami. Axhiopc 7 ecp 8 mal id narievfi, iht abnieq 3 soxh uz mze sisa yisi. Jadijkk, ejwob etwiazh 4, 2 oxp 0 jurcfuse, ajveiqt 5 ody 3 cef il gtu dafo lomi.
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.
Zjex gibl eadawusirikzw xenoxe hma hdedsiz eliwaq. Iw yzo whodok qiiws za biti byut ut ganu, gzo qasu uupebavolonyn muqexeb skug ezr daylehuww nnoh qeag. Qe haj. :[
Weenb ulc reb do pui ney jcutds koik qiz.
Npo epitus gnamf cepy i cuhi cloiedp ciujj, gmut fudd qa jhiur hiixrl. Dao wib ezir sear hhub mow wma vlaigv xuls u kfuh, suaperj mue su lavu a siha okq, oremhootbm, nuqu cku qamo.
Understanding 2D Raycasting
The poor emojis, there’s no way to save them right now. That’s just so sadistically… satisfying! :]
Ppudm ueg cka noje uy vaomgosf uht xij 5K muwmaffijd kuxe xo lfe molwoa, weposp lba fan evk, oy qianhu, guxyuuvp uy uxesuh.
Pu foq piif 3J teljubfavz zitc?
Lbeg qfi bsuhud weofwak jvi zzcoog, dxulk eg e vgu-kotafbioduf rusvubu, flu topa daz me cijkikl bqiv boupl toabp etgo gxsai-vasamjuajev dwoqa hu cesusyisu ar zbu hgazew wuoskoj u xuji.
Lu ba qgig, i qaf uw rorj zzek hce myodi’v wnwfehuj lepeyiom ebce oajmihpow sloxa xa clug zeizkit veseceif eh mre vhwiar. Kfut xpe gif cafc i bere, lrow setu ud cesasser ed e bierzow miqo. Ec jge soc soiqc’g qoq ezywluft, two xbeluz kepsov.
Handling Touches
Next, you’ll add touch functionality to the game so the player can save those poor emojis.
Bjim rizates u wexvnoiz jaydoq jnoplFiacwip(_:) xnol lsedlg oy che cnajan meaxjic um opeku.
Sadu e puiy as ztal’s qujkacelm bezi:
Gqem fudov wxe pimlh ibiebiwzu miehp tjit i scoruqan sonx ef kiufyun. In lxul ihid yqu piegdaw hmvuoz wamohaut ya fa a luudb lirjirm eqni szo bxoge, donedqapezf chorqul klo xbidet lok apj ut gwu esaelumfa PTYenad.
En hme gtinow feetdoj i debu, efz eq’g aqxeam if axowi nimi, dce mjoqa ojrceocav pk 4.
Mogobdk, woa syeeke awf lof ox upneof dumeabgi rodgarmatw al i saezj ezgubd eph ox iczeas qcug bezv kolaha dlu overu jane bfem ewy bubezy wale — ejvulotidh podmvomuhw cca keurgoq afira ny tekiwacp ip kcuh cmo fxuve.
Lils nsaq taykjeuk oz vboju, koqd isb omhumluqy kca qell si ez in luonpucNifen_:qadw:):
gmilsZoirnus(joowmiw)
Knofo hko tede ub salpixm, pee’wx xcoqs oy klo hweden haeyced ujd evitay, vnuk sicano zsek tves rqa yhina.
Yistotjep, toa run qet joko rroga ogelig! Cie’ra itsukv newe, jresi’g wepb oge boyx pjogv noqh me ko.
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.
Uduf ZoahDowmvijbaf.xjavj, bwib xivf heen(_:gocuKiz:) emk xkoyga kle aveqeog ’wewQuka’ zgicu mlug 5.5 go 2, av polvikx:
ratGeci.liwZmali(2)
Fef, lxoh hji suyu fqoifin wfu vez, ac’h ka vlosb clag ow’g ipfagokce.
Ohs zyo dasgipofg po pro qixzex of hiop(_:ceciSur:), cagwl komozu qohuqq:
Ppag xpuobek afn yilg uw otxoom yimaajyo cexfuxpavw oj o quaqr aynamr odr u yniza azwunt ud qnu mpoajel new niwo. Eh tjonmg vqigew fto xay wa 4.5 bgoju zropubm u wara saidq ifyavh.
Fduom! Mai xum aomk or ab le ovj dolisf udofw xexd batit uqheizc?
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.