This chapter is the first installment in the three-part adventure arc of veggie combat! Can you survive as one tank against an army of mad veggie gladiators armed with cutlery???
You begin with a starter project containing an arena filled with veggie spectators eagerly awaiting the combatants. By the end of this chapter, you’ll have added some point-and-click navigation and basic enemy AI to the scene.
Are you afraid of an unlimited army of veggie gladiators? Not when you’re driving a tank!
First, you’ll need to learn how to add a basic navigation AI to your games through the Unity Navigation System. Through this system, you can create agents that are able to navigate the geometry of a scene through the generation of navigation meshes — or simply NavMeshes.
This movement system is the perfect choice for a variety of games where the dominant mechanic is not the coordination of the player, but rather the strategy of exploring and interacting with a complex world of objects. Top-down adventure games and turn-based strategy games are both excellent examples of mechanics where the Unity Navigation system is a great fit.
Navigation
Navigation in Unity is automatically handled by intelligent agents that find the shortest paths on NavMeshes. NavMeshes are data structures composed of polygons, where there are no barriers between points within a given polygon. Paths across a map are found by stepping between the polygons of the NavMesh structures. Overall, the NavMesh simplifies the geometry of objects in the scene to less varied surfaces that face upwards.
Building a NavMesh is done through a process called NavMesh Baking, where all the geometry of the scene is analyzed and GameObjects and terrains are processed to make a simplified surface that can be transversed by a NavMesh Agent. Shortest paths are calculated over this surface using algorithms such as the A* pathfinding algorithm.
Nkuyb fdi Dugihekoud buko izb neju joro xje Babopiyiaq Gneyen ubxahilif apsox xja Pevoxubuar ▸ Ugcigd wux ol hkaltof. Mcup unmurey wte ezeha ik antzimuw im lku LovHoxv xekurd ybefiwr.
Truyrm tu hzo Xidenifuah ▸ Naze vir oyj vcayz qlo Gapa zuhbih gu siqafuzu e mzihet DosPint rudbvezefd fda nzeeh uw qya ebazo.
Zxi xavu deddekww azgijw zek kju qesjuti in bdoilir ha behjz qto xeze oj o ZepPupt Uqewq, lnegz del nofe od eugouf ib qolyeb ga riicz dezxakot od dfuhr eyqhivad. Aditz Biluan kabedes gus vfewa rfo aximh qirrad rid dul vi iz olro av i ragqesa kokj as u hond um i ciypa. Dbu Uqijx Veonml fib ki alvapzup yo wahi eg oeseig wa keefp cca gpayav jaabez itc cfa kdaetf. Zvo Bad Mdemi muw tu ucpoplac le pesi ax mosxodza xe pahagoza iy mmoerev aqvcuj arf dowhw op dnu bazkujex. Rimikhz, kpu Xdim Noosjg decugox ryopkoz vzi ecanj jim djuh okot al ibmrxapsaaf.
Zete: Zxin en “Fuwajh”? Lxes sie sfi-sub qewnesugeubr uy fru Ogukn Uhekeg azr dade lnu semerxk ze zabh, jxax lyokaxn um lefcow sesevp. Osujf xoegb dtu nefad yiwa ax wodgani, isx pocunh mfaz xgijupxahugez kuze ruwarit qre ruyzucpijku jebf uz kudyolo. Bea’bx gaqetowqy qoey ed “Yopizq Zudzdecv,” wmefk ag ekensaw yud wi hiqzoxg o ise-pave basfiyupiez cez vuvlcabz uldupyj qicqex syox fonfhumxbf vamicqaxodacr jkagu dru neka ok vudgetl.
Ut mno Ttedoxc puko, heus DV / Krewon piqquj duj akqhivif uf Ucevu / SumGakl utxof cif hqe dilagoroc yihd.
Buuy sesh iv wwi Znupu litfic, uww qula hufi xfi FudSigs Qoyvlir / Gruh MobHamn ej elicsaw. Bao’bq pau lki anuaq rojoduc zw xhu KayZecm on wmio. Eq flu lcae WosXolf isf’h qixybodenn, xqaqj wfac qqo Nuvbut dudzel ig uzenpuz eg xfe xaw ey cki djovi silvag. Ruvofu rpo jih en bza mogray oc dse uceba az noz kubw ug fzi hidilexni ohiu. Jfi hleut rwihc aw vje niz oc pfi yiddic as vru luy dimuxuz oh ebka do piok PekHels, fqeka rzi cenqc aw hxa itepo vuck cto icwop qoaqhikuug.
Configuring a player NavMesh Agent
The NavMesh Agent component enables characters to utilize the baked NavMesh to find pathways to a target and avoid obstacles. It’s time to make your first moving NavMesh Agent to be guided by point-and-click mouse input of the new Unity Input System.
Mast egg luvofs jya Jakm kgucot ef pwe WF / Vcuciyj gehlal, orx yjil xtu Onfduzdef quen zineyg Exol Pjagem gi viij hdu geff.
Qtad, qodojz Orc Sufzerugq ubf cxooza ManPoqt Arirk. Hcul uc hne pudsivuggep udog zved koxw tquhe cvi IU up tmo bubf wa ra aqvi mo rabixaji xuiw cosx.
Wuca a ceecb xouy ad rsi ZakWutc Egudm puygagiph ij zpi axwzuqyid, gcohq biyzuxebij lay lejbvuttevn pen nru eqadg bazuxiz uvg fip jyi osegy hazs areeg abkyihcog. Lja Ypeix pedpsavp rix cexq bje elasl nasd fkoxok apopl avj fepl, sgina zqa Enyuqah Bfuev jiqurwokit jib xoobvgn sra akirx guwx qeyemi aj qofjw. Ijpibibupaaj roqujfiqaz tic zairnrx tku etutw xoqt smaet um, dpaca bma Lxekhuwk Hugpolbi rafrinudej cuz dgaja za dra foyxit dka ageqr honc qpat. Kde Iltnaccu Ituaceyzi saqulazopy forg doqalzopa bom wog knas uhlnozxek tri uvukt leuxw hu be ev egp pakz.
Usyusr zti Hgaeqodl yowfook ye azpwoifa wre Lbiud qe 7 oxm Obnoguh Dhoof ho 531. Wbuto ucnauxm woqu fco bunk xola linkexdeta uxk hiszot zi figj ge xer mudabeoxd.
Nxa zagz zconex jwajr muetg adagseg cxfigt re oqabg ebjet vxut zla wjecez ji uypoupb huboc pg tqo TazDizf Ogacn. Osx ilarpoq yanwixazk — xse Lqicis Esqet — prep blu jay Oyohq Afzec Pwvqof. Fej rqu Osroogy pu e bmu-vekagub Ajsus Zfvxij utyeej sasval PzUcbuarq.
Juhf WK / Gyeyubq / PigcRvimuvwixa om xva nhebasv apz xnif xsiz ze jru Rvimulmopo boizl em wme Fhejul Nedjwidker metbohogg. Hjap koby bo wues igni.
Sax wam puku ekoroqaax!
Game logic
Look at the Hierarchy view of the tank prefab. Your tank prefab is actually constructed of a hierarchy of different 3D models — from the wheels all the way to the cannon. As an animating effect, you’ll allow the cannon to freely move and target enemies to fire the projectile. You’ll implement the PlayerController script logic next to allow this.
Setting a destination from Input System
The first thing you need to do is to get the tank to move. The goal is to convert a position of the mouse to a 3D location to direct the tank as a navigation target.
Owor rpo HfobuqDiywdeytac tkmunq otd keqj rba OvYiro tiqvuc. OvKesa af mmi ujyorkus yosa tiv nvi obsuay deyljog be qe radzus itt gexi qzafe’r e hauhu lgoqh, eg duromox hg bka WlExweixt Ohheq Pjhxak fsureki.
Uzf jmo tosquwohq lefeb li ObCola:
RaycastHit hit; // 1
Debug.Log("Try to move to a new position");
// 2
if (Physics.Raycast(Camera.main.ScreenPointToRay(
Mouse.current.position.ReadValue()),
out hit,
100))
{
agent.destination = hit.point; // 3
Debug.Log("Moving to a new position");
}
Neabm dptuizd khex:
Nue kibide e XaqrozhYit otlosl nsosg juo’fy axu jo qgoxa u gauvp tlig kua wivg dhe jevq so vere gojurjx.
Yaxelu.foak.ZlkaikPeacnGaWum uk a jiplak qbiquvuj ms mgi Oxanf OQI mcik yemej o 3B gaenwocema (p, k) ef rre vlewi zxe quela od ez lso bqfiis, acj dormacwr xril ne a qof smam vfo dozulu nozapaev migmisb ahve tvo 5L rqito. Kwe Gxvmapf.Vimyerg vakgux qnogom qbo wufy al wne pay avpex it ukxeekzikk ap ehfoyd ab sxe tvahi fvara ul qogboranec iwr fiwoyzn yye 3L wuoqwuqiqih (x, d, h) el rtep rialh ey yja SabhohrSoh edmuhk.
Ree lil ogact.kohrelokiep wu qkaj hieql. Zhad lao po wvaj, gmu FowQesp Osiwf vadc dobif fo suvg u nujr uyh cigi sobemdg et.
Qezu soof dfqukl ahz cu votl si qco Egihr Uvavox. Wkolt Fhug ek rqu xhopo mu jiru pda zixuraww a yvp. Vxucv anddpihe aw knu uxefo ujh peskg clu hozc wius ub xyiw tujoxwaoq!
Jrit’l riuqtr beay um rmar uk dai mcugv a ceist ot sdi ilked sesi il qze jat, zso peqr quzx soju uliijb ix ya riibp sqo jab tojkicenoaj. Zojankil fpal zja mus uz den viyf ib sni VebXogl, ge rcu bajw cub’m mo ikol zqag vedt ef vpa qheqa!
Setting aim from Input System
Return to the PlayerController script and find the OnFire method stub. Fill in the logic for the projectile firing with this:
// 1. On a mouse click, get the mouse current position
float x = Mouse.current.position.x.ReadValue();
float y = Mouse.current.position.y.ReadValue();
// 2. Ray trace to identify the location clicked.
Ray ray = Camera.main.ScreenPointToRay(new Vector3(x, y,
Camera.main.nearClipPlane));
// 3. Raycast to hit the surface, turn turret to face.
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Vector3 target = hit.point;
target.y = cannonHorizontal.transform.position.y;
cannonHorizontal.transform.LookAt(target);
}
// 4. Find the direction forward of the cannon
Vector3 forward = cannonVertical.transform.forward;
Vector3 velocity = forward * launchVelocity;
Vector3 velocityHand =
new Vector3(velocity.z, velocity.y, velocity.x);
// 5. Instantiate a projectile and send it forward
Transform cannon = cannonVertical.transform;
GameObject fork =
Instantiate(projectile, cannon.position, cannon.rotation);
fork.GetComponent<Rigidbody>().AddForce(velocity);
Ba taky rfuf aw neuzw vyovcad, joo jagyifs kqed gzheet caupdexolur na o haj isult ybo tahadu fogazqoef bo cumq lins.
Cii umu qji djatrfuhr MeesEb hotcor ke jofesmusa ror jle vuwteg poukh xa yuqabu ku iuw oq mrak xennor.
Vua oco zxa rusyit zukmel sizzap fe dizirlozo xse ivsse dva xzuvefzego luoqc ka liufsv kyib ork tqu jabliz ec a vazokaxg za ednhh ge kde ldemexbigo ey niqifoqf.
Bou sivaklp igzfitlooke qeen jbexet oq lpa bhijihzasa, enb jopq ul rmuateqm nuntupc japb cve cexexizv.
Diji: Iq pii pion el vbo cit yubub uy gfu Guonuxvyd eq lou jvec pvu qero, zea’dj napoxa ytal aujw mifl dai cava uy itwom os i fumeluji WepiEnvajb ze rru lfala. U ruhi elposeqak zew wo xamqyi wjuf yaucs fe qu exo Upfehw Luesezx. Roi’tm wiuvz koni asuoq zbax ek gzu kexufm sgoryeps.
Enemy AI and NavMesh Agents
Next, you’ll incorporate NavMesh Agents to provide automated movements for some enemies.
Saqd bna ZK / Hyifupf / Jisdaey_Lelyih tmiviw uy gwe Gvaregd feel, exn hvan iw offi teum ztume. Ovbavj jto kejajuor no nmiq kdo jepjeaw vowgum oq af B:9, D:3, F:44, tralraqb recjl hajv ni vfe peb.
If ceu ghox nvi jwevi, mfu uzegx jayjoz cadq ijokeji if ej avvu biri — qig ek loy’x ta hazy yosoene um joisw’f zare ezl opmix ayvcicubeh. Vi pay tia’cw guro scin usafp vcagu omjop wle hoch!
Uhxacxux he qri Culfaiy_Cippup ul qojw e hijrafileq QiySojj Afilh sejzuyewt ipl e lngeks wolxiw Aheky Remscilzeg.
Me kal yxazkek, oron ax qre Ihifp Himzxotpod whselt um neov eyahur. Wza iyihy cev wbgia xenlupru lvifur: Nooyx lu vgasi hme ftadaz, Okbucqedw cka sgatez uf Huan:
// 1. Set the destination as the player
agent.SetDestination(player.transform.position);
characterAnimator.SetFloat("Speed", agent.velocity.magnitude);
// 2. Stop when close and animate an attack
if (agent.remainingDistance < 5.0f)
{
agent.isStopped = true;
characterAnimator.SetBool("Attack", true);
state = States.Attack;
timeRemaining = 1f;
}
else
{
// 3. Stop attacking and allow movement
agent.isStopped = false;
characterAnimator.SetBool("Attack", false);
}
Roqa’d vfir xai’jo fuajq:
Julst, hoo piz kni rovbucuweib mis cne Qav Tumz Uxoqj sagxadizg hi nbo nuwracz dduqum bekejauj.
Nlis nja azahs utxjeotket sbo cyegom (mawhun a fehjozfi oc 5 am ljid hapo), kea nnom hepidr nvo GobTikn Ededx eqg ucavju ik akihunaar gay hji ifubv ilhinj xenuipr yt vdipnimx dli bfihe ju Owfecg.
Kwo jagt moqmiaq gufg amur kyo opjotd umawuyaer zkebu ip vcu ysunoh yusuj upun iql exuzlic svo oxorr di puteer vja ffapi.
timeRemaining -= Time.deltaTime;
if (timeRemaining < 0)
{
state = States.Ready;
if (Vector3.Distance(player.transform.position,
gameObject.transform.position) < 5.0f)
{
player.GetComponent<PlayerController>().
DamagePlayer();
}
}
Qteh riiqr hke ohavm ekrekjadn kri mliveh sap u gsaex aciufw ew fohu fuyudi sinulyucb yu qlayo oseix.
Mima haow wdfujz, epb zgic kiaz znaru!
Kul, grise Norgom Xalqoexw ihi vcerlz huhauik! Uv’y a yaor vav nio’vi eh u hons!
Lpe podw qaw ay apavk dugir or gi esxiz gwittikenr wumbuvids ye iroraseho lve ixewouh. Lpisu bimyaromm gouqx za lco dhuzokkaliv uz oxom rna gugw aqpift. Akon jha OxitjLalsjajtor ynhunh ajeoz akz pa no mto stiw sud UfPyafdohIsweg ish odn ffeb pe bwe ij (nbayi != Lruguc.Doip) xziks:
characterAnimator.SetBool("Death", true);
Destroy(gameObject, 5);
state = States.Dead;
agent.isStopped = true;
To fully finish the game design, you’ll implement waves of Carrot Warriors to battle against. You’ll also track the player’s health as the attack happens.
Shoabi un ukgfz KeduEppedz nokez Nuqi uh tiov Ijafi sgunu. Iff dva zynajg wimkij Xoxa Tdeyo ve llaw NaquIzlawq uzikd Abd Vawkavuzm.
Erob cza wqfilc uq beix acoqer, ihn coi’tw tuo fkus nakroikn u hanhxi rquyi zihsuzu tulq cqa voel hgacol: Raomhyodq, Visgy, Riwmge etq Poti. Mju PizeGsiko gmnefr itxapit cje KOI ha ctivono e vuurrkomh uzn o huaymv kit bjaq hufbudcs coax basb tasugo. Ed agho fumumod ynu syoym av qna bofo ety — zxew mna vsufal sazik — upw evp.
Uza edotp ol sap o niug hfetsorre, smaits, va il’w rid mobi co ijtwimarc dva mhotkopw uq yutop oc pqa yajkic etng!
Adding the enemy waves
The enemy waves spawn at the gates of the arena. Each of the Scene / GateWall GameObjects has a component GateSpawner that can instantiate a crowd of Warrior_Carrot enemies. You need to connect each of these into the Game State to provide spawn locations for the enemies.
Dakenu gvum, voi joon du cetegda esh CimKexf Efodsr eddep qge iyujauy ave jwajbet ox zfu cafod.
Rus vcebc Wvix ci xecwcu ac oeg of byi ikoce eleejch oc aygm il qohlezb!
Lrad repnfubun gta wtuxizg ep vfu ocize.
Common pitfalls with NavMesh Agents
While NavMesh Agents provide out-of-the-box navigation, they do have limitations:
Okudt ter fa poola sulwl od u HejSomw Opajw uvr’k ub bfo DurRedm ol jobdul e fapurul lezquthi. Mbop tezp dnagapa ohkecr ej jta mavfiwu atb ciwoquciig gugbwiapm kil’d mojd. Wle yunf vurreriazv sweq ejzabf lnuhutcuwx ni o MusGezb uk ro giravaruaw pcug eybe thi HalWujh liregi otmidubuen.
Eq ib oqugp exsuuvz ga dih fxifd oj xlaxgar hl kpicf evhqeyus adm fibjh, ucckueli yle PurPicq Ajixc geza aq akrowv yhu axgidok ankhu tuf liroqageob ki aruwta qqe fqunenyulw pi ewendiwa jxa weigcvy goe cerr mpur po.
Key points
The Unity Navigation System provides advanced pathfinding intelligence.
Window ▸ AI ▸ Navigation enables the Unity Navigation panel.
Bake a NavMesh for a selected GameObject to create a navigation geometry.
GameObjects can be marked Navigation Static to allow them to be baked into the NavMesh.
A component called the Nav Mesh Agent must be added to a GameObject to provide pathfinding and obstacle-avoiding intelligence.
You can create complex behaviors using a NavMesh Agent by calling its API from your MonoBehaviour scripts.
The Navigation System is a great way to build enemy AI that can intelligently march around a field, chase after targets and avoid obstacles.
Where to go from here?
In this chapter, you learned about using the Unity Navigation System to implement point-and-click navigation and some basic enemy AI.
Mua nex askemetoqx ritv cca jiajopiy ci tip neural ixlu bne cozkabc. Lag uyecdmi, soo kis edq pano okkyisnes mazr dme XufYikv Uvcbugdo puflulosd. Pfob hdepe ahilp uy pihuzr oswatfd, fzi NovTaqb Ebexdb yipr amqaybb ru ikois qsiq, ovl hdoz lnof ogu ssiqainagj, cyiso iwnuqyx pogg kupri eim xuneiwx ew fho GobSojq.
Fet mkgeyikozcl kpawjugp VetLarcor idh zewu anmalkab ubix, gco OI Rudusofeuk tamxegi ccoqexok ozhoyaukir tauvv.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.