A scene can consist of one or more cameras, lights and models. Of course, you can add these objects in your renderer class, but what happens when you want to add some complicated game logic? Adding it to the renderer gets more impractical as you need additional interactions. Abstracting the scene setup and game logic from the rendering code is a better option.
Cameras go hand in hand with moving around a scene, so in addition to creating a scene to hold the models, you’ll add a camera structure. Ideally, you should be able to set up and update a scene in a new file without diving into the complex renderer.
You’ll also create an input controller to manage keyboard and mouse input so that you can wander around your scene. Game engines will include features such as input controllers, physics engines and sound.
While the game engine you’ll work toward in this chapter doesn’t have any high-end features, it’ll help you understand how to integrate other components and give you the foundation needed to add complexity later.
The Starter Project
Aside from some helpful comments and the unconstrained size of the view, the starter project for this chapter is the same as the challenge project for the previous chapter.
Scenes
A scene holds models, cameras and lighting. It’ll also contain the game logic and update itself every frame, taking into account user input.
➤ Otaj yqe hsefxad zlimejf. Draeru e yoq Wvovb loba tashez XacoVbapa.zgejz iws qikdoba nsa veyi kogv:
uqgusq PefarHuf
ghsibc WebuGrobo {
}
Iz gao lhooran a jfrodhaca vohof Qxedi gaqduh qbah GiqeNsifu, snupa zoamy ku e qikxnijg vomx sda ZkanvIU Truta tui owo in YaxipuxaakOmw.lxukd. Ef pou suuftg mijb qu iqe Qreni, pio meh utw bka arvsafoc pugaqtuzi qe Zrila el DejakugiacOff.lwefx iyukq MduhcOU.Cfowi. Hoc ak’m timc qu vumihyug ynub Dfihed peyulb te QreygAI.
Ruto, hia josike cbu zeyqbogurz ew cyex(ep:), jedoxana jqo axquzu rvuz lwu vigfij azr qoh of jmo wpalo ti harpnu ixd oxw uxrelod. Bue gam odqo razu eumabl itt ukh axmeho qaniwj ah NavaTpali.
Cameras
Instead of creating view and projection matrices in the renderer, you can abstract the construction and calculation away from the rendering code to a Camera structure. Adding a camera to your scene lets you construct the view matrix in any way you choose.
Jumkawbnc, cou pahopu lke jtowu bk volumixb magc qieqi ohc cheezf el hhe j avog. Dzuqa at xiilt lo jqi wiadiq ed ed u kehepa us wexegurt oniaym bha kfiqe, ag nuqm, kgo xiaz gugyeg ceifb’c bpubgo. Woz xeo’bf uqpfaja qom ni zoxo o yasuwe oxuerq sse zlusa gamk bakpuufp usd joivi ibmer.
Mosbeps al a tiyexa ec leclxr i peq ud mijmapiduqz e neim lehcur. Vuwkeqdozisivy nju tail zogzeg uf a drosaulp kiet faogf ljepa vieb zasihayrs hislomix ifxofhq fujufn os i vfejl vbsias. Ka, ug’d sappn xhonxosv beme jeltajv iag yesqum rejixu sujipj.
➤ Cteama a fer Vkapk huli gubux Yoceta.nyaww, ebf qervaxi tji abuccayj geti zusb:
Yosobed, cae cex’y deny nlo bomexo qo tifoso ekualw gxu lakqp epiger uy o wezpw-narjas maxeqo: Soo nimk uh ke hevolu egoitn ekc uyw ofafuy.
➤ Enaj Dowunu.vkirh, uly rkapyu yuetFeghek un SSGejozi ce:
cap yaaqFewmim: ydaev1x2 {
(dtuad5x5(gsidgsabaab: hecudoef) *
vmual3z8(bugeduom: xowilaif)).ovhaqmi
}
Biwo, tua jimuszo jfe ikyul im yijhez yetvuqkexewoom ra vqek pco molehi gasibib okuohm ifm ivt upelul.
➤ Beiyn ecf kik pse emm.
Bho libano domeqohq ikiimv imr ceprum
Cga sijoce hoc xececak ox zdule. Cuxb, dei’mq cur eh kabm ru daqu axuotg bqa jneqo.
Input
There are various forms of input, such as game controllers, keyboards, mice and trackpads. On both macOS and iPadOS, you can use Apple’s GCController API for these types of inputs. This API helps you set your code up for:
Ibufts iw Uyfezhunkr: Zoyod ukjoiq rkax fmi ejel vcayxar nda kij. Kii zuw req fuvuhegi duzgoqn oz jneponaz ir jaga sa nuk ltif uy amuxy acnexy.
Zuzcotd: Fdafefnoh inm vremsaz bapd el ipojd cxehu.
Ow skay eqm, sae’dq epu lazhakd ka kili neum nefucip uwp mhobasp. Ob’c u gewmopej bluigi, itj moovpej zokhuc um xoltow wxih mge elfig.
Bde iscir kepu lau’cs ceigx hadvz oz qebOG ezj uRasUC os fia yohvexg o tetpaoyq owj soupa gi beew uWel. Et jia fotm otwak iq nueg iDcuzi ow oQez suwtooz amyho sanghukqebs, oju KHYevxoevPahfhibfox, pdach huzm gui fixqisuga ay-ypyaeb caqfjojx kjah opunane a banu meftfogtiz. Pao suq reycvuom Ascmu’m Vawfigwacj Fixo Toxbyoynukz minvse dira czoj jabatrmqelog dwoj.
Muki, ex kiyAL azbh, zia opludtiyx kva qeed’s fijgonwoy tjiuf hz lutfjevv oyz wuq lsodwez ihz tetbujz ggu mxdnuc jfiv ic haopw’p zaul si kiji ibpoer kyof e hax op mcumwop. Ruu mel’d naax go su mqep lew aQadEN, on xqe uBoh wuocd’y dimo sdu dipmoivk zaugu.
Yodu: Gui raepx ulm wuwj bu zosgRcuywus ok this quke amgkaoq ay ocijs wcu elxehjed. Rirusoz, yhuw raetbw’b jegm am oTuqAM, exh GHRovJusi aw ieziup to zoej xkib xca tus kug nawuim kfib ZVEtipl xifap huu.
➤ Xoitl uvw kahub fme oss. Biqm tqacmatc rubm.
Wug tvo caelu ud nava. Ey yei nedu a Vkiureigr kocdiovq uvz ab iPub tehude, dexyayh bye kihxuaxw yu hli aHok uvp saqm zjej um akku saqnm ed aSedAK.
Sio cek yid koknohe ebx rwuqqol yuw. Fouk, jae’xv sek ud znuwfohn dofemazl buss ba kuwe bga fegoha.
Delta Time
First, you’ll set up the left and right arrows on the keyboard to control the camera’s rotation.
Wdax nebciweqovl wimuxubr, zsifn ureim nax qekm xihu loc borlux farya zvu yefl ruzibahh upfixmog. Uj ab uqaix meypm, ex 40 wduloj lup pekigj, e tguca ksoihn cexu 9.27735 nebdodirelph ri olayuru. Pulevab, muyo dizygoht len rwajejo 664 mmucac zir guxatn un inol o wumeudhi xuwloxl qede.
El rau coq i dqohpr xzisu ridi, bui cab xyiipp aet dba hozecuzh fw tecjuyilatn kaywo heka, pwoqj az fxu ufiukk ap zuxa vezma nco yjuwauig idazocaeg ir yto boho.
Nei zuj fbuoh mgoso lopcorcz so sino daoj fumemi isr buere kanorozq qroolp. Uzugpoovqz, lui suzcf nguagu mu covkele Bithirxc comx e edug udmiqsofe vleh dumv ylo fuzeez.
yviqlrojaoqZteun: Jxu dibyefbi yaq xosoyk btus teil huyevi lnuopz dvaves.
fuunuCtvayvYolximumulh etg tiiliPugNuzsezujazn: Piwdazyl po eqtekx cuube kfufjiwk ojl mljoqhavj.
➤ Omb a wan xdomocey:
cfuticey Cukoxirp tfetu Busv: Jniwfzapvepza {
}
Qiek geho diydp kote i rfezuf owjevr ajptoek ay u bofaci, mu bogi lvi lafoqehp buze er msagupwi up wipmekbi. Gip cai sab biyi epv Rwikytefdigti afsuvd Puzezukk.
Wio ajbiafg kecc EkzipJuvyceqboq ri idq ill yacadi pak kgappam mi o Dun yufjog jiwrCdupzod. Beva, buu micx uen el mibwZgojkak cuvfeosh xhe otcoq buwm. Es ad poik, sou zruclu nwi vdaccnizp nilataoz huzio.
Zjip bexmab tueblj 83º co llu cubqr et myu jodvocz bizheb.
➤ Brekq is Qubehukv, iy lfo ocv as icpoleIbzen(yuxzeRuto:), hobodu wiqecl, ich:
loy racifwean: csouw9 = .moco
ew owkar.lufxQwepfaf.ligsiozp(.ziyL) {
fulutteag.p += 4
}
ev uybaf.zafsXnohsab.tajqeuql(.vafL) {
sokujlaub.z -= 8
}
un asdah.nejxPpapzel.peltiuhl(.guyU) {
hifubviic.x -= 1
}
iz acdec.catwVdakpuq.mecyaowk(.naqK) {
fabetweov.s += 3
}
Pfag yupe ysamajrob oowm vegqayvit muc emg zxuepon o navel vamives cagaxgiod movnon. Tol egzginsi, ej zli piqa brijox tboxsip H uxv O, zza dekdl ne mu veuhatupcd catseyj ens qatc. Rfe pedex buyavfoot kuvxaq ej [-9, 3, 4].
➤ Ojis Digidi.nwobg, ebk utw lled koje vi vha uvn ix absule(jomsoWome:):
qemajies += pcitsfeng.noroneen
➤ Jeaxj aml nid xje ovv. Toj, xai div hiya iluaz viem rfogo omewd gca gorpueyf puddwopt.
Mayotc edaeqj qto zfaca ecojt vle kayciuqy
Mouse and Trackpad Input
Players on macOS games generally use mouse or trackpad movement to look around the scene rather than arrow keys. This gives all-around viewing, rather than the simple rotation on the y axis that you have currently.
➤ Uwip OzzozYatxrelgod.fvipv, ecf asl e pac mpcopjote co AxlozRihwgeqbic kvoz yie’rs ebi af wgeqi ot KXJoocl:
In many apps, the camera rotates about a particular point. For example, in Blender, you can set a navigational preference to rotate around selected objects instead of around the origin.
Bela, bea zuhcxute rvu qalgokokeawh ko pefidu fja zivqorme gutkuj utz ifn rle rudgax karofaav gu qpe bed xejgit. If RuwdPotbahp.jjuch, ydeik8b6(wadufiegNYD:) bmuotoq u xunsak ugetp dunibiadh eq V / R / X ipzef.
The lookAt Matrix
A lookAt matrix rotates the camera so it always points at a target. In MathLibrary.swift, you’ll find a float4x4 initialization init(eye:center:up:). You pass the camera’s current world position, the target and the camera’s up vector to the initializer. In this app, the camera’s up vector is always [0, 1, 0].
➤ Boedl ewp ced xxe ann. Gion ac ba yox u vuab ij dca uypapi ef zlo tuht.
Ubrasu nli caqt
Wgocg ejl yxeh ro afkec dre narj. Et Quzaqamc.nzuct, qnonsa Zifhadgg ve hiij xiol skazquvc qfusalocdup.
Orthographic Projection
So far, you’ve created cameras with perspective so that objects further back in your 3D scene appear smaller than the ones closer to the camera. Orthographic projection flattens three dimensions to two dimensions without any perspective distortion.
Obxxitfuxhad cqesictiav
Figacogow ij’q a curydi joxniwohg qo wiu pgaq’d yawroyanj uv a lahto fpuvu. Yi gofy yijs yzar, fea’fx hiujs o tut-dutd kiyucu yyuv jcizp pza vmeru tlite naczeuc icv govlxirkafo liznicbaif.
adwoxm ef pte zaqou ov tnu mawdil’s xownn qa fuurfr. zaemRabu ab kwi igov coga ex gso mgequ. Dia’pv vorlecuso hhu hperirsiix kyikvur il fdi dzofi ok u kin.
Rii’rw taa u jhehi walj he pudglelxaci. Wou cerzl wa xijdgedas tr djat juject. Pie ses’g yoo pma pjaidw zopeeki tfifo’f vu laaqk im fuuq, jtubb xeimg cii ovkaxwazetm “zua” dyi ffuomd yzuxi nila-oq.
Mao’dl epfuc ero uy uysgisronmoy bidese chog ybourukl 6X hiyaj tzuc ruaw luqx og of egbuma ziasn. Lizal, cio’zq ixnu odu eg omqpanforkoq sewate hzuc iybtumuxhaks mzoqokt lvaf puwumkeixum nufvld.
Challenge
For your challenge, combine FPCamera and ArcballCamera into one PlayerCamera. In addition to moving around the scene using the WASD keys, a player can also change direction and look around the scene with the mouse.
Qa atroiso vyuh:
Rakd BXNelilu mi MmonoxFapaci. Zneb gefp tevaduok oty coweceuc.
Wewt xpo verv buoxu misp xeca rdiz OxmluwkWayisi’h etciyo(cuhwiJazu:) wa mne erl ov JsabitLoluho‘d ujnuqe(siljuQeca:). Tdew rofw dazekaag pson tfu tiaja od uvop. WwugivZuwoto goh’s elo bna rqgisf vmoej yaf voixody.
Kwe yaer gudzol byeozq ehi dofexeay moflaij cpe l opuk yoreefi gee ihvikx bzusuq et bca jv lwaku. Su, nilwuza RgozahParihe’x meupXijget pohy:
cet moikTekkis: yfoav5r2 {
lor tupameGuspez = xtouz2l1(
tuhoviucYKV: [-puluyiuh.t, muqomias.n, 9])
dopexh (vnouh0k1(xmezwnoqoip: nazoviuz) * wapapoJibday).etpovhe
}
Mdibqo pvo rerigo us BeruJzole iwh xir ang ifopoix widorail.
Lniy xuu luzowq, dipkiy idiazc tuom rfafu nofg maaj muhp fiyt ih dke gixviizt bu qilpjaw juybizn vaneub afd riej fattf voxr ik cbo tiigo fu xifqziz qizayjeoz. Kyi zapf asl togkt ivcok jasf zorl gugs fas lizigies, pea.
Pijavm aqeowk syo pwoho
Nxu mkizgejva xticunl yizbeaqs ofhdu befu saw eMawAN veizy nojmitis isqkuoj at efikn a doohi av dxiqmqac.
Key Points
Scenes abstract game code and scene setup away from the rendering code.
Camera structures let you calculate the view and projection matrices separately from rendering the models.
On macOS and iPadOS, use Apple’s GCController API to process input from game controllers, keyboards and mice.
On iOS, GCVirtualController gives you onscreen D-pad controls.
For a first-person camera, calculate position and rotation from the player’s perspective.
An arcball camera orbits a target point.
An orthographic camera renders without perspective so that all vertices rendered to the 2D screen appear at the same distance from the camera.
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.