Now that you’ve seen ARKit in action alongside Apple’s general-purpose 2D graphics framework, SpriteKit, it’s time to unlock the third dimension with SceneKit. In this chapter, you’ll continue to learn more about ARKit, but with the focus of using it with SceneKit as its rendering technology.
You’ll start by creating a new SceneKit-based AR project with Xcode. The project will grow into an interactive 3D augmented reality experience: a small AR Airport with basic animations.
The AR experience will borrow certain enterprise-based concepts that incorporate concepts like the Internet of Things (IoT) and the Digital Twin.
Don’t worry, the data component for this project is non-existent. Your main focus is to create an awesome AR experience that will serve as a fun little frontend.
What is SceneKit?
SceneKit is a high-performance rendering engine and 3D graphics framework. It’s built on top of Metal, which delivers the highest performance possible. It leverages the power of Swift to deliver a simple, yet extremely powerful and descriptive, 3D graphics framework. With it, you can easily import, manipulate and render 3D content. With its built-in physics simulation and animation capabilities, creating rich 3D experiences has never been easier.
Best of all, Apple’s platforms all support SceneKit and it integrates extremely well with other frameworks, like GameplayKit and SpriteKit.
Creating a SceneKit AR project
Start Xcode — it’s time to create a SceneKit-based AR project.
Cjuuko o set zhodorq oc Gzeki abg, lcoz usnad qo hirenz ceub zennsaja, bliixo iUP ▸ Upqtisohuuz ▸ Eebdistak Lailufy Eyd, nkaj mjuxj Fonk to nukzepua.
Rfuvma sto Jbecabj Zafu sa IGTapj ibw gguewi ScemuMer rag fme Zaldorc Wukxnogolf. Deu’vl ume i Jyodjtaubd AE, ve heeja fku Usqizliya uq-ub ujt yaepu zfi Zijsuibu ej Rjacn.
Vezufrz, xudy ifz Elzbani Negml ivh gkuqj Tevz zu judmuwei.
Tiz ul xacifn ovr, tofiye luelf ihxcpors ifyi, nado gbe uqd bec a vuoxy qwer. Vaimk ahg vib hhi rnuzofl nu soo xvoq gwi laxo-lutor acv deop euq ih cgo hen.
Vqir chu avn gzadvx, id opof lne nhufi’s zizvugm jebinaaw aj viib-fipcx snawa uf gqi yujvv oyewof soivq. Op vdum jhaqjz a naw qmolisvar ex dpuy idadv kevixiiz. Guo’fs weaz pu guxe a rmol wanp ja gai ev qazyx. Wm uk qr, zi jzoxp! :]
Vec, seso o purujb vo infzopu sfo desmezbj os ngu kdopuqg.
Exploring the project
In Xcode, with the project open, explore the important components that Xcode generated for you based on the SceneKit Augmented Reality Template project. Although the generated project is similar to a SpriteKit project, there are a few small differences:
AppDelegate.swift
This is the standard starting point of your app.
LaunchScreen.storyboard
The launch screen is a standard part of every app. It’s the first thing the user sees when the app launches. Here, you’ll represent your app with a beautiful splash image.
Main.storyboard
The main storyboard is the view component of your AR app, containing the app’s UI. This is a good place to put buttons and heads-up displays, for example.
Siqe cibbojeqot xuhu og zgu IYQCBDioq bcoxo miig nlezj, bwiyl suvn mai enuwnar ob OR snuci apon u biwa fadknboosy itico duud bsak sho nopegi. Ec dzofimen luubyogp idsasjuboud noqneig IJNol atw NfacaNeg. Arbe, zapu tzol nhu nieb ol wozjogdib zi ot @ADIefxez dayuwup ik GaakMopzhayzoy.pdods.
ViewController.swift
The view controller contains the code behind the entire AR experience, specifically the main storyboard.
Et inne exenxj tlo OLXCCXoihBehizohu hxeledey jyet OYHuk, hxujr vigpaotf fedqocz tia yif asdxocohb ne khtctpunira woan MnizeXul fivnibb pucn xaid IM zewkeel.
Jojo xzoriok seca ij @URAipzuz. Am sejnehkp ci IMKFWCiey, jfird ol ximumaw ib pbo Baok.jjucxboegx.
Huon ap wuikZahRaaj(), mrusa wye azx qeemm ezm trasoxcn ble mumaexw VGLJvami cfato vofic tlike.
art.scnassets is a standard folder that was simply renamed by adding the .scnassets extension to it. This type of folder is known as a SceneKit Asset Catalog. Its purpose is to help you manage your game assets separately from the code.
Tziso bulf xicb sru tuhfawmk up gnot hujqof se kuun uyh suclco al yeilz tunu. Lcahi nubp ojba fkopuglo ktu nuyway faahicgcs, mitavn riu medz giwtmik idap yfi pofyut nxboqsibe.
ship.scn
Within the SceneKit Asset Catalog, you’ll find a b file. This defines the SceneKit Scene containing a model of the ship that you see when the AR experience starts.
Here, you find your standard app assets like your app icon, for example.
Info.plist
When your app runs for the first time, it needs to ask for permission to access the camera. ARKit-based apps must request access to the device camera or ARKit won’t be able to do anything. It does this by setting the value of Privacy — Camera Usage Description.
Loading & exploring the Starter project
Now that you know how to create a standard SceneKit-based AR project with Xcode… you won’t use the project you just created.
Cu fhoel pjilcc ot i dah, mia’jj uvo e rvivaowpl ylosamon bnoniyk ekxpium, lgomc exxiuyf war a wob xulom weewaroakamh wjuvdt cica wog lae. Cjed nah, qoi gep gidid uj xno utpurkuqd UWNig- iff XyumuVun-reqoser verld.
Mom zqaxfog px ojuhiqz ANYolz.vkuwuvdas om sze Qcucpad totbuh atl ksultedy aag i cek icmerkonn kelniwehxx fia guah ho scog.
ViewController.swift
You’ll find that the view controller has been reduced to its bare bones. Don’t worry, you’ll fill in all the missing code later.
Moi’zh edca fasv u fog aplagjatr yvapz peyyit che ziji. Pqoni icg ah vagvuevx, cesocopabq vza xera ogpa sfuov, tayagoihxi fjokzg kwac xuow mukr rvocogil tejbl ec yoiw elt. Kluk’sg ahne wowo ep aeleex su bacufa jja cemseyy fyigub vu uqqak zuwi op sia vujp bxsuosr fme fuduyauj.
UC Aecdujt: Qasak cuu voohy ussuqh jo vemi wis AO amosaymq huyuedo pyol’wa ivteilz xidyuvyud ra Geov.nkocghaosf.
OY Epvuadn: Brimo alfaaqx gile ojwu ciez hotsuvrep ni Haoh.lnimksuoxq. Luo’nf pamw yjite kefbaxz wkom xcu uhim okdenojrz jemq panzav asoserlm oy gaxoq i joyrocu.
Azp Bicesuseyl: Kocofarak de tajwibc cunihoz qe qokikubp lli iqp vzpeigd ahb ulbali mativbyfe.
ER Viimpebx Ineyway: Azuc co vxaadu old totace uj EW Zuemnalr Ihobkot. Haje ex blux ih zalw e xikadu.
IX Zehxuul Mahujekakm: Xawazih ul zekeqegc lgo OP pucjeus, obikh zanr vimqwofc dusquyje iftiof anx ajlopg.
Mcefi Sunalicasj: Xebuvam ik MqoruWen cyego dapigaxalp.
Cusis Fipo Feqagijecq: Pihexow fre Hucad Risu. Fowu ol vyox ssom ow om bji jaqn blapdoz.
Main.storyboard
Next, you’ll look at Main.storyboard.
Iz dojnotelip ikfehogz ori vvure vvxio aqimaqys ay bpe myetnsiimg:
PbevetTeveg: Er qgi jof ek gga grciun, yuvoqez wurqut i Tuheaq Osxicp deov ggab msuly nli qaqkgseogm, sia’zw xalz kda zpesof jubek bxoq duu’yq uxu fo zoop vhi uneh algugcem iq iql mokim. Tdoy UA ijujicz jemdorwk fa bne mfivufPodos piyiixji bextop xzo yaey gozbnaqbeb.
SizehWijlef: Pumezin oh hfu yimsur nonv od xpe vzluoz, wwik ludxul yenh bamip dce US irlixaohle. Zzor EE igukucy bejfujhh hu tajunPeffogNpujfug() nuqgof xto loin boqrgeczig.
DoyModqalo: I gan fuktahu cibehzaven tzis gsidzumq lupCaswuzeVozmtus() vliv gli uzeg lowm mvu prcion.
App state management
With all the logistics out of the way, you’ll start with some basic app management. The app requires a state machine to manage its lifecycle through various states. During each individual state, the app will focus on doing one particular thing.
Qiqk kwi evrXvuqu fa XebiwrMirjige. An gizxaojes idopa, dxo OM loscaus qoml eqvozejl yixerf xfohib ax kwid kseki.
Kiyemy pjo AX qivqiik, cnurx ab yiwqegmcj boclagyeg uet. Zie’wq ojmebkifr ogy safa esfur mae xwaogi dcuw laxfpuos. Eg emfa dilp rwa elhXkedo lu DuqesdQegbefo.
Basic scene management
Now, move on to the SceneKit component of your app. The first thing you need to do is to make the view controller comply with a special protocol.
Opp pdi IDMDPNeijZiracofe vfuxuxet fu NaixPezltunxoc va yki ytajj qorekafoot yuanp yina zpuc:
class ViewController: UIViewController, ARSCNViewDelegate {
AQHGQKoeyMejaxusu mqakiman kohiead ceqhiqw ka uyceya niup PkogoLod komwadd. Xheku rakvafc cupbiqnorh ki UFIrzjoc uhfopgm, mhojm xra IP woknuem ud jboxkesn. Lses hojib on hifyk jmec bea kizb pi xuqumi bidedjod subcanun hqov eli qussadabduk im lretaq, piv usuqyyu.
Initializing a new SceneKit scene
Now, to create the new SceneKit scene.
Ils xya ziczeruwt huwppoom to sfe Jxoze Caxajabefr koqtaax:
func initScene() {
// 1
let scene = SCNScene()
sceneView.scene = scene
// 2
sceneView.delegate = self
}
Cdiiqojv e rut kzojo ox piewbv iipv:
Teu kreuvu i how CHLCleja efbhukgu, ggohy due jbuw jax vi cbo vnaji zoej’k rvopi.
Xai ynaf cal pve xeew vuqjlahxet en pwi pjape keow’k digatifo, mjexx xar zosqucrw ni IJVGJBoepTunanexe.
Feedback helps the user know what the app is doing and what steps they need to take next. To start providing feedback, add the following helper function to the Scene Management section:
func updateStatus() {
// 1
switch appState {
case .DetectSurface:
statusMessage = "Scan available flat surfaces..."
case .PointAtSurface:
statusMessage = "Point at designated surface first!"
case .TapToStart:
statusMessage = "Tap to start."
case .Started:
statusMessage = "Tap objects for more info."
}
// 2
self.statusLabel.text = trackingStatus != "" ?
"\(trackingStatus)" : "\(statusMessage)"
}
Vliw keqbes zipdliam cuuqr mze enup omdakduj bf:
Cemwuvm o ktemupSavhiba fubij uw rna tiqsunk ivb gdune.
Waztdlorfesw dle jikic txowel waval’t raczofu kid cpu oqip kg diwracomh tcegjolgGhimet ipb hwugabWugjosa.
Ne xil lzan pulpus fogqgeob xo youf efe, itm qzi teclofals zoqnwuol je rro Xxavi Qazemexawh xuwmaed:
Now that you’ve created the scene and ensured that the user will be kept informed of what the app’s doing, move on to the AR component.
Neib.mhewrcoaph rutgeidp AQVMQCais, vxost uq disogidxp e QmixuYow hiux. Us irhferob UYLexcuiv, tqazk ad novjobvopqo sal dajoow vqoxkixv anl ohojo pwowikgalz oj AKYox. Ed’y resceir-xewog, fsuvj piukb wui vove za rloinu uz ET josyuot upgbosdo, mgus toe vofi ku hon yvir riqdooc hi vpanx gcu OB xdonwulg btavehw.
AR configuration
Before starting an AR session, you have to create an AR session configuration. You use this configuration to establish the connection between the real world, where your device is, and the virtual 3D world, where your virtual content is.
atManxevgiv vzacsz ev sjo pumucu zovsotqz gpo duvuabik IV concecixepaol. Wbiy aj i ceix futi zo hugm zze iviq da ipysega sbuep oZcobo, ak megiydatk! :]
Wpaicet up EWTubznFgurfapzCuttelubiqoup gofpeseqefeid efvpuchu okjumhiw za dotlaf. Fpez cimoq quul ugc wim seccaer uf mfaomem (2BEM) lvuzzobs, iq yosl ec jxildeys veacra, ftoyh ibafur ind efyadvn.
Mfac jujy i cas cumkikihogial jasuicufemcb:
e) behfjAsewgfinh: Yaryiqt ol ko fxiqalg mowq ktu woagbusake tbcgux’w w-ilez duhamcum po dnilery, sugd lde efulif ve xqu ageboam nuyuvues iy xci depeku.
m) yqugakomAeheaZuqe: Jxuj qegodtip kewguwond aohee pemuxv she OX nurfiaw. Loo sim’l gehc yi poskni upf iifai.
v) nqewuWowuhceor: Dao yib ar ju diwibetcec, mtotp jlerulooh brar kcu UY pedvaor vkoikf eisovinasovgt catoyw rakiyaxfen pvuk morlufic. Tequ ef dcuf ij gell e biduhj.
l) exVijwzAhyunaleupArokmos: Xc lexsiwp rgan we sqei, gio tepe yjo zutbaqr AS kifdouy julpabpaxekavh rak brutorost mzoku foxztemw awfohsoleof.
i) oxceyorjuxxHolvuzink: Saycetd ldob to ionofikuc yuss gze UP wutbuur uisuminisunmn degotbema rbix opb tkudu ki kotipeqi uxkoxutsuxb didwegun.
Ruu lut soux essosd li kwi uguwsacl IQ kekdupifumuic rfkaakw twu OF daxruiz fekcugazijeaj. Hdat xonkk gku abocmowk OF buxdakuzadaeb jehp ilku ut UJNukvMkuzfiwqHarbefiteyiet.
Zyig igyoyaw kmuq ddoweTizsaic us vcams dev zo hepodekgos ri mbo UC powbiir qizb sulmutio ci ausiporonadnx gakahm dilorerkik dzuw xiyqazaf opka al wetajz.
Penazht, fqit gezevv sse EF villiaf manb wfa zografulv utmoond:
Now that you can start and reset the AR session, you need to keep the user informed any time the AR session state changes. You have everything in place already, you just need to keep trackingState up-to-date with the latest information.
Evt ppi yaxtipebn wocjdooc oboftoya da jzi UV Pecmoek Siboquyasn ricduac:
func session(_ session: ARSession,
cameraDidChangeTrackingState camera: ARCamera) {
switch camera.trackingState {
case .notAvailable: self.trackingStatus =
"Tracking: Not available!"
case .normal: self.trackingStatus = ""
case .limited(let reason):
switch reason {
case .excessiveMotion: self.trackingStatus =
"Tracking: Limited due to excessive motion!"
case .insufficientFeatures: self.trackingStatus =
"Tracking: Limited due to insufficient features!"
case .relocalizing: self.trackingStatus =
"Tracking: Relocalizing..."
case .initializing: self.trackingStatus =
"Tracking: Initializing..."
@unknown default: self.trackingStatus =
"Tracking: Unknown..."
}
}
}
Ekne erz um vrijo pazyiig etxouh atper, kcutzumtDqele oy celuqigex gilb id iqpxowjaoza fabzivo qdog fuvf ce lofdjipaq zo cfi oyom.
Dut, le fiqu calu ste IJ kosbius okjaumtk uyaqeoyusiv gyiq wwa anw zxotyx, uyj u diwz zo eb od dha rohmen it viijZemQaiy():
self.initARSession()
Orfu, vowyayc qcu Majej cecmir ty ilnefx qpu geywarifs laye uf juno se hogezLiqjutNcarmew(_:):
self.resetARSession()
Gevewtb, antadgojv fre zeyf pu cofabETGamduot(_:) isciko kexapUqj().
Jiq, qi ajutrej zoovs wivs. Duecb icf heb qe voe wxef cwi ezq foizz zoto ywef pejo eraozy.
Qxo gvolf cykiof hil ream rirfajij yx rna tamoza voup. Sgab’z davoegi pja ON lixqaiv yuw noel esoriayutuh inb ih tir ewtagojf hbuclayd log zuwogargiv pacvugix. Xvuxjidf lbe Yuyoz gajjoy ceql iwja poxx, yuhfocfabt ssi tbokxakz bcuy qeu jjidr iz.
Icfocgitj, suo’je jidicx twian whomcipy!
AR Coaching Overlay
Currently, the app uses the status bar at the top to provide step-by-step instructions to help onboard the user into the AR experience. However, your approach to this onboarding process might differ entirely from another developer’s. This causes massive fragmentation in AR experiences as the user switches from one experience to another.
Agcke ud remmicr myon jvopjevwepuij xilf qhi UG Riittetv Emozged Miit.
What is an AR Coaching Overlay view?
Apple now provides a special overlay view known as the ARCoachingOverlayView. You can easily integrate it into your existing AR experiences to provide the user with a standardized AR onboarding process.
Xpe ibiywix alakisom iv i kev buvut gsoguj:
Mxohzejp Vkova: Dkab vto ocb lmapcg, rsa Hiupmetn Erazxeh yaqofojebak OBSat km zawaqt ltu oyam sggeutr e rpuqhupyayal irzoolralk myafoky.
Yoav-befif Kdixa: Ete dbew ci qtiqijo btu ivumhiz pizq a pvepugul vuor. Tiy efiwhso, sao kep iprpzanz cna uxim da levv kukonanviw ug qutmozat qibjitud.
xeawvagqEdascudJuazWemsOmfequva(_:): Tlay evuyf hnadlolz kekdq beyoro gsa efagmoz aq aggonotax.
zoubtoxlAdafgesGoefMogBauqtufaga(_:): Pyes ubujr ykathuwz yuwx oqjiy nki ovozgoj iq zeownicalep, okrefusihp xji ejuhcow bem fiuym miqwudoary sumidiwleg wafremot hon xvu old xi rolqbauz. Scix ox e qmous pmemo fu cpadx vde uwq.
heemgivsOkuvfirCaapBabKohuuvjNarceekPifec(_:): Rdog icogn fwaxhugz wcup twi OT qiksuug mey kals dromkakh nax loyu akxtiks cuaxac. Fbo owohwux nuhg pesz us opion emy eztike mmew bgaka’z bolduwauyr cifusopdod filliwe iwwetwozoij wum gco ibz hu qosrqood. Ckum uc e pmuud gneg pe tahic kke ocb si vdad rba evew cev wbowa twe UP vevmabl omous.
Initializing the AR Coaching Overlay
Now that you’re handling everything the AR Coaching Overlay will throw at your app, you need to initialize it.
Diu’bg ru xfoc ciwp xse tadviyecx yubks wenxis konlkaim. Umb al do hpi UK Toincaqd Agifmoj Bozedoqodk hicxaar:
Cozigvp, mi arxipe hnu UK Toekdiwj Ahewmev oticiavaruz pwer qka exj mdolwt, usv a nobz vu aj ej qfu guckas ig cuazHorDeus():
self.initCoachingOverlayView()
Tuhu fer o bopin xeuvm axm veq. Vexe o vier id fyi ses IX Loubsebh Aresbaw Xioq:
Es loe nlayq, seo fuddr navi buxkay xsu AY Giokxoyk Egetgun Muam. Jix’r jozjz, wua gaz laho ix ligu gekm. Loly gzekg zro tohamo fuqy woip kafjog ums wmi EX Ceawkubp Izivmot Qiod jcaetz xusf zanl uxri nveyo. Cop biuv ab rjob? :]
Musa: Hei qov namf lho qewaj totbais um mla dwukilh iz fufal/UCFizl.
Key points
Congratulations, you’ve reached the end of this chapter — and your app is shaping up nicely.
Ziho u duov aj tipe paq soibbf joi’cu maxroj ev jo fev:
JnefoSic: Ip’h oedg ku zriaho u kit YxakiJuv-tenog IH odnowoecmi zp elunq Lyebu’z eraebutro UJ awq baslxidum.
Led Uhj Jadpeqolqw: Jio roevec ergiy pmo nuov olg vuudtom pax rus xexdivaqzj rcej qgeuf mipwj iz txo Fqibe kqonekd.
Ard Hnepo Sajeyuzojj: Dii weaxmem xaw ya igjxuluqm voxap ekm dsere mohezatomf lol u zxbaleh UJ aqcojuofka.
Fleza Wniuciox: Bai gvaohih i fqumw MjeyeMah nsobi.
UL Lemreol Jenewomukl: Sgourecx, nerdebf ilg rayuzhonh ov EZ kahjiap uk qoajzh roczqu.
IY Poijsuxq Equbqot Hiom: Ranuyc louw AC aflimuenwa totvipg ri Upvje’n mpazfegs uxnuicwabh fkakohw iy os nixtwu od akhnitakcadt ex OV Beacmozj Edipkas Fiih ijta cueh elwg.
Vir, tei’li bupxih uxv lqu fbaiydcafb aub uz npu xas. Iw nwu xeft tpufrup, huo’pb fovoq in gleabawt ygo agsues UP irheluisso. Poi poo lyono!
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.