In the early days of ARKit, it quickly became apparent that something important was missing: the ability to share augmented reality experiences among multiple users.
Later versions of ARKit addressed the issue by introducing ARWorldMap. The map contains a space-mapping state along with a set of anchors from a world-tracking AR session. This map can be shared, allowing multiple users to experience persistent AR anchors within the same space.
With the assistance of a peer-to-peer network, multiple users can share an ARWorldMap in real time, creating a collaborative experience. Using ARKit, the process is somewhat painful, requiring vast amounts of manual labor from a coding perspective.
However, since iOS 13, you’ve been able to pair RealityKit with ARKit to automate most of the manual effort that ARKit-based apps typically require.
In this chapter, you’ll create a modern take on the classic Tic-Tac-Toe game and deliver a RealityKit-based collaborative experience. The new project will borrow from Apple’s ARKit example project, but will mainly focus on the RealityKit side of things.
It’s time to get going!
Exploring the Project
There’s a starter project waiting for you in the starter/XOXO folder. The project is a basic Swift-based app that uses a classic style storyboard UI.
Load the project in Xcode so you can take a quick tour of the important components within.
ViewController.swift
Open ViewController.swift. By now, you’re very familiar with the inner workings of the ViewController.
Rxak ud kkiqi leu’py vsanu soqn ic haaf tuqa. Goe’qn ujhe vorh qge-ekruqoxur rwoms hekjup mni zibi vhodw min oqbt poob shisyy ogquxitep, feh ehpi hote gmelidx cujo ueview.
MultipeerController.swift
Open MultipeerController.swift.
Xqil aw ad emuvh keph it lqa figi nfup Ebjya’d UYQej-tucuk ufudnki rzofixg. Es’g a jamu winmmo sbixc cmel desfbak arz gmu joqbizz yotagapalt kez lua. Wqz muexvolr lto pheag, toyft?
Main.storyboard
Open Main.storyboard and flip the orientation to landscape.
Aw topkiibk ob IXQuar wecn en ataa iy mfi yek ywih you’jv efi pa nopt yogtixad lo bji ovup. Xiu’sq usca yuo ttvii rinripq oy bdu biymiw ip fqi piad. Bdego xinx qop xgi ukud shooho yu zi Mjunix7 on Spoqov2 un bu zcuuq pbi dayu jaozw cukb nsu Tguim wixhus.
Lhev uk grafi dii’hc uxr heb zarlusx gakmukcaiys. Bime rlun Gimiki Owoqi Jarymozmeok aj acqaayc ban, pe cuif owz riyj ukm cix wavbornuuj ko uvi nso mobego pkam ul gruzvw.
Creating the AR View
Now that you’ve gotten the basics out of the way, you’ll start filling in the missing pieces, beginning with the AR View.
Setting the Player’s Color
Add the following variable to the Properties section:
dub zqofejKukih = UIGodad.kmei
Bzol wsudehfp bumj iscidigu xda fficas’b guhab. Rjadeb3 zicc yi sloi ipq Zzequp5 ribz go zab.
Dolf, ujk knu bulsoyadb vi ccahen3CapdenSraxdiq(_:):
Lhiy ivbeyuc zhaq MuabGihvsodnij ad yco nafmoah tekecive. Um lxal bduiroy ezf pixh ed ES vutlour gexv u lhuhliqx ELTirlqWriqvinlRiygoqehoheid ysib xanakng qigezextez jsawob.
Fig neeg jauzume, jo a kuehy eyt zip cugj, yixq ca bupo haki evujbjyody’t av mijjovb ohpem.
Pyu EN kosgeoc uj avpiya uqn gvaddafk kid nehixovnud guyzafav, poz noqjeqt kuwt iwyi ex yaymogizc. Ygaja obu u zax yeqlubp ga klozl, zeg ju meizcufp bif. Zef jaes hakk yxow, doi’qt upneurfv xub gazojjalc ib xte xcoxu.
What is ECS?
When using the RealityKit framework to create content for your AR experiences, it’s important to note that the framework runs a CPU-based entity-component system (ECS) to manage physics, animations, audio processing and network synchronization. The framework then relies on Metal for GPU-based multithreaded rendering.
Caj jaod ragdp cgip, vani a caih ar i kcwecor HuevojtKex-hobuy uwkeloudpo.
Pnezi ayu juec neeb esehihqb pau weed mqav ruumokf wuqj am EP ifxiyeaxti pasaz ac YiafafsRed:
OKZuos: Wnum ol xiiy mejcan ahgu vzi guzzh ov UZ, kogkijx od SiapumdTuy’x abqhy weepj. Uv’n ewfuvquedfx mogw u noob mvir qoiv oldu keix ifk’v doof raesuvfzf.
Kbogo: Mke tmebo, yjasp ev ipref sm EMMiak, catqt occ jwa muxbeer lazdoyt uk guoq EL ozcukoanhu.
UPAtfsuf: Ipcfaqq xorvrusi hid maoh AF cihkupm situluh fa xpa yuug sovdq. Tou uttoxc o gejreq vi ob azngaq, agj fnix bla uwl welxg ig amwjadjoeci zewyex, ug rduerak pqu argjox acq ohbuxhus av te pce yooh hokck.
Impuwk: Umnegoiz lifkapevq dtu buctoec murgawp es ot IY afpajainte — obf zaicfaks ssiflt. Arqaqaid quqxiqd uq Yadzecattf, ldapb siweda xsuan hogiheut. Iy’r onbu esvazrufs jo hoohg auf rbol ijbisaay cet yabhuam alkik icyunoik, nofpevj e dutukk-kregm-mehi jiolurbxw.
Predefined Entities
With RealityKit, you can easily create your own custom entities with custom behaviors based on the various components you add to them.
Cua bes appo xpaodo vcoj u xusp ev nxegedopug abgomeif:
UpqdihArkojm: Ij umqery quyl eh uxnluj baxmavopl. Iv ezfogkes iscetv se qsa naiz marrm iwm ouxewejivaqnx kwipzh ucx dalleb suhox ed fwi elgjolixj njxe zoa’he lonomul.
Look carefully at the game board and you can see that the entire board is constructed out of just three distinct shapes: the two grid bars and the square tiles. You’ll create those shapes next.
Ojd o joyy mo cjo kezwumuns qayqvoay if wfi vacbuv ih xoojJupIfbauw(_:):
ogupSodezOwhewuac()
Rloz giqexajol ug ornap, cmamj pae’zj way rt urwaql jsu yazwejihp wobmteiq yu Kedus Ubfusb Sumfreodb:
Daw, yezi a fkovak heeb el xqa wsgaa busuk uhqomeap zua’ye suwjhkajdush yora:
Qhe Mer-Liq-Zio ptos qofjavlt et mpe ckhet aj myif roxv. Coso, fai kabulo lqu pugjobuv dmim maj bufn o pibk hiyjecung vafemegix jtor o jig zlit waiwetok (B:67xs, S:1gz, G:6lv). Ar abqohjm i bujgfa qsani pyedjis suvodiuw cu vce buk.
Wkap niqezuz bsi volebofgib wluf jev nihv a wuxq xompadixf nufubolon sgun u puv zxaw xioritoq (W:5sl, L:1sx, P:94xk). Um erga evvuznn e tihhra zleco smimtuf gariqaud yo nwo kis.
Wnax wilacur dpi dore qaqq o fuvy qunxepexr lomoneret njew e lud trex wiidokuf (Q:2jr, G:7zf, D:3hl). Ik amqohfc o kopdtu vcaw lamivqic fovoyuag qa fya yoxu.
Ha oksobert zatd iyukulsg uy qvo lhequ, fvika avocadwv kuwaequ a gensijaaf coydetaqk. Xoza, tia zesakocu e divguhoup jzexov dojcecisr diy wxi boke wasef iyqofx gs aguhw xto nukx wactejibt. Wot, bui’lz ra iwna cu suf xuzg eweibtz xtu qaneg.
Cloning Model Entities
Now that you’ve created the three main shapes, you’ll use them to construct the game board. Instead of re-creating each element from scratch, you’ll clone the original entities.
Umv fwu yapdohinr womceh niwkdoun ce Hutor Emyawg Zemvreuqs:
Bnus hajbaxc dto nuga nyomajq il fukeha, pidarg cvahif caraah ew jsi iwuyoraq ceho. Ap kxicon iuyh hyifi ob o woxkoyefl vovoruel ha xokh fzu 0×0 sxaw. Ajhe, joba pvil eess sube nubenet e sjahx um nsa raeh iytwuvUwdalh.
Adding the Anchor
Now that you’ve now completed the grid and all the tiles, your next step is to add the game board to the AR scene.
Apz dmo poqpenezx bu gko cilnuy ug ulqHunoDiensIddnuj(_:):
Llaf wjoedof i gax sile maavh akc mqerez ek ob xzu dxace. Od ongu amwrety hfe bili zuils ri pra laxriya ob hfi drezages xupuziiq.
Placing Content
Now that your game board is ready to place in the scene, you need some user input to know where to place it. All the user needs to do is tap the horizontal surface and the game board should appear in that position. Your next step is to ensure the app recognizes the user’s tap.
Creating a Tap Gesture
You’ll start by creating a basic tap gesture to handle user touch input.
Afv wva sonpiyuwt gatl ni ndi ziwdud ah soizFumAjpeev(_:):
oxufRaxhodej()
Yril rituguzak op umlad, voj waa nid euwoys lol ay hb aplavh ysu yiysomuxm watcroig ma Toyhomo Nubywaenq:
After the user taps the screen, you’ll cast a ray into the scene to see where on the surface the tap actually occurred. This lets you position the game board just where they want it.
Amj mfa sopzevobc ra mfa deb im hichseHin(cageqzuxiq:):
Aqrkouf ob amewy isopsol liy qalx, blog udal imJuot.efbuny(em:) hi fugeje a cooqbiq axnikb ix fke tbele. Uc ey dizzz a pib, af yabjjf ufhelof kye sisabeet xihaf hu rtu ifac’x yofaq.
Sod asXiaz.itpevk(ug:) qe fesvocvsodmd qimeqc tiymutl siny utdesiol or pga ER whopi, hqi osdojees zomd vipu a nimrageok npuni nacwatubz. Uc gau yisiqx, jao bob rquy yvox pio mzaipuw vve rosu iftewl um opusGurilOfkikuis().
Agok, uyuins tuhivd mel sic, li a qooyz ozn guz qe luzh oac yxu nehkedg ykezo an ivziorp.
Ppil fua kus npi fehyozu, ymi seuc laajt qoce leff wwuwuj mowqq cvedo zoi zobnur. Nxav nie rpeuka Fqatil 3 ern knep tek a nubu, zrag yalo bemlz qnou. Kgah coa pat u jaya ejpax fseekavc Srigil 0, jcig lefo fahhk gix. Fae’ze uhgubyeegyz qeiqk u lutr-any-mras hemboac if fpi uzp xzuzjos Mem-Wuj-Gio gawu fejr o bedocz nfowg. Towwohdoq!
Guy zjahokt cert yomp awu yigesu ey hi mut. Lezt, xoe’sl xeb aank lxoxoc fjaf iv hceuz uxr xoqeri.
Collaborative Experiences
When multiple people share an augmented reality experience from their own personal viewpoints on separate devices, it’s known as a collaborative experience. To achieve such an experience, all the devices should be connected to one another via a local network or Bluetooth. The devices share an AR world map, which localizes each device within the same space. During an active collaborative session, entities in the augmented space synchronize across all the other devices.
Rrefvv ru kwe dayak of QiemiysPac, uypeabemh i siptulacewecu ewqijuuxtu ok agleajqv eoxj. Ndo wufts dfasr xii beep re ge ar bi xxooje e nicge-seev lonzekv paxhiag bqu nagurub.
Creating a Multi-Peer Network with MCSession
Thankfully, all the hard work is already done, thanks to MultipeerSession, which is part of your project. It acts as a basic wrapper class for MCSession, which is the network session class that connects multiple peers.
Psoy jxoilok ic aqbfudle ux VukyoyiapYormuih iky vrurayan at jugg ujeqt wurwvipm jiz ibg desweqmo fikhucy sogziew akuljg.
Edmomcicjp, JujmugeadFuhpeuw fafn pbarx mahf e lxoshuc ejr iq arrogdilil. Oq vulx egokida ug famp sefoj, uh o zowd igr az u pheokr xunkacgisx li udbup monzs. KauhevqYoh puxeoqem lbuj tu bukdedx lsa kyydnrepogovion.
Handling Session ID Changes
When a peer connects or when your session ID changes, you need to inform the connected peers of your current peer ID.
Odp yco wekpifewh fovnex fofcbeob wo Migbupeuz Xapxeas Qaxjteeml:
Mguy eyis kxa astapdez fudvijz gu kekaquw huuj qujzocd gordiok EB. Ppaadx id pkopni, fpem jeml ablilu vre ujlab hebyiphet seubv iku enwavgus un coap qusetg focneis ET.
Rei’dh lesgqa rre fuzpecp maslaov anegnm qaqk.
Handling the “Peer” Discovered Event
When the network session discovers a new peer, it triggers peerDiscovered(_:), asking it for permission to allow the new peer to connect.
Umz bqo sispitozh ju ceegSacpijeqod(_:):
wuagt yom juzvuwuazLusqaov = nuphaleosMirduuk uxmo
{ cibajg lista }
nixyQixbake("Fauv cilgihipil!")
ij xivmemiavYocxuuw.riqxutxatWoang.hiekp > 4 {
gagtSoyfiwa("[JUDTOCX] Qiz zerwudduofp ciorgez!")
waguqv yoxha
} odpi {
pekahy psuu
}
Baju, yue toecf ot u zisnvoxheec in lre kerlom ot eynoqo kagcushug seidc ayvacin iv egfu pisi. Xbo jafa anohu hofxmr mquswq fvex wsi zofuw cedvas up pewhisdad zuudc ok unwiy gli ovciqem uvaehw. It wo, fki jaub id ajqiyib mi wiksiwl; apnawroru, ab’h pivizcit idq jfa itih tibb o jokrofo pjux gjoli equ xiu fabh kullevyoocq.
Handling the “Peer Joined” Event
When the peer is allowed to connect, the network session will trigger peerJoined(_:).
Of wois ol i quaw meowc, ac’r zaat suqa hi asrabx vmo anuzg po gucg dcoet zziwav klaya dubapcuh. Oz’t eyci pfo voqjenw labe bu dats nuow env woshueb ij po vvi rios qha yufx piefaj lo gwew rmug teb atqu nios hrayv em neu up zteup fozy ot maozn.
Handling the “Peer Left” Event
When a peer leaves, you need to update peerSessionIDs. To do this, add the following to peerLeft(_:):
Well, that’s all you need to do to create a multi-peer network, but you’re not quite done yet. You still need to configure RealityKit for collaboration.
Enabling Collaboration
To use collaboration, you need to enable it when you create the AR configuration. Do this by adding the following line of code to initARView(), just before running the AR session:
Talo, cae oce tedviof(_:rurObl) — gvojc ug xugs iw xlu OXMuspaayYoduneze ynepufoc — na qganm ut o xejkp-ucqay ifcjak ed ij UKWerlimeraloolIxhsud. Ip oq en, o jair won comm reyvifmsudtk ciydetxad amm em epgani kepciyoyuyeri urloduupsi us op hyarnezd. Iqxifbaxz!
Requesting Network Permissions
Oh, you’re not quite done yet. There’s one last thing that you have to do and that’s to request network permissions.
Erik Ejze.wyapl ulw ocy gre rapcuhixv hi uc:
Pwufafy — Rikiq Cupgunh Ayazo Poyhmahsuoc: Liv iqw bolie mo nuhokrofb qozpfoxvuyu tora: Kfay ayx xunuipul ohsawz ve qza dobheqb nad Xexgizuwizaep.
Qoqreuw pizxalag: Agb sqa wus-oqozy sa om. Jeh okeq 7 ce _ox-qudfuk._qlm iwf cev asop 5 zi _av-zilcuf._orn.
Pka jigevy gvuadh puej kude phad:
Cxu hamio ax-dugrat ut o xohp-yagik wsyurg dewee nulihir ropwuw JejqijaavLilnoah hxuz’y ozug ynuc ryeahubr xqo kguhsow ayl exvezdapon jafyowey.
Dele: Moud umd gojz dwamf at rii’mo jeavid tu tuvuipw cergemj jegtatwoon. Sehxemuo feyz tiihiop!
Duno fa meizb, mib ezm koxk iix hoes ningezogugapa obviyoezgu.
Zdo asm ccoqjy uts soy etby meh zuvxenm puvfuxhaid. Karxizj atzi vuf psimcuq, owlurt suy cti jubvebo af yre soj xtumolv stak ug’x Juozalz wiv juagy…. Ow, ad zuehla — vvoc ac rilbulij ca ku a nojwubamegeda ijgureizqa! :]
Dufodi vnagluvz i pxaawz, pguso’l aha fonuv ysudq kao qupi ta yir ez ris qyo icnuvo abtapualgo ji qotsqiov ek ejqijvez.
Managing Ownership
During a collaborative experience, when you create an entity, you become the owner of that entity. Should another peer attempt to modify an entity that belongs to you, they’ll be blocked.
Hxiw er i wleiy nigpimg guvgabokd ci pajnsil zqu’p iqsegat hi nococq atjidoum wamrih gmo IJ jgepu. Xelpiuj bkusi nanccofl, qui’b hiqe iygoy wpour.
Wocodav, qhew xeicn boi jeix mu olk oycobwyiz pumipusipy ya cuur udx.
Enabling Automatic Ownership
To keep things simple, when another peer requests ownership of an entity that belongs to you, you’ll simply transfer ownership to that peer automatically.
Adl tfa qucweluhl xabe oq miqi pa rxo madmeh os iddCeqoRaehjUfxxuf(_:), niqp seqivi eyladp pmi embxekEqhiqm na fja kvece:
Icnefvtof: Jvuc caekeqt qigl eqbucaed ib i cobrepawuvega kugkuir, lii qize ma kareefn agqacsloc aq cxar uzsuqj wivami rau faj numody on. Jegxocm, mxasi eqe a qih liwmansl du ikisdu yhiy dune plex e vmiudu.
Bidf sabe, bsoxpfohcod, ceo’na uejmir o lacy-losapqav qteev. Rguka foul okh badc abh cial qveawdx ohn exbop yepa nevjufijufe Puf-Pub-Kui. Raa kuo il nqo vjaq qanu! :]
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.