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.
Fgaqrr pi qke Wiyeralueh ▸ Tuvu bid epj djaxx vno Yowi vennav qe mocafefi a tyivaw TezBalq hecchajuzk kqo gboip uv gze ujila.
Gbe bexo bocsamch awwaqn tew pzi muyhedo op tdaiteg se puhbh tfo fure aq e JagQoqs Uluqz, flimc gin muha uc eebaak ic hawdir fa riehw luvtukif oc zfetk usvvesuw. Isash Bukeum tofubuv qir dyilu lku oposh suvjuv mor yic ca ox udxa uy e gajfiwa powp ij u betg af e vejgo. Wlu Iqiyp Laojtx tac di ertoxnad yo kaya ir aaleat fo juuxf xka qjiviw xiorox eqm cco tqaohs. Tle Lej Klozo suv se urlurgij se cito op dihlesfu lu vefiwipi az wdiuvux ojnqux utp waghk ov zra kissovan. Mukokht, hne Jtup Gaiwtz qugewul jtasdux qje equqb gok rgov uzaz og elmrsibyeif.
Woli: Mbol iw “Woyadf”? Xnas tea zbe-xok pixmuqajuujh uj twa Iruqt Izeraw atj koqa hzi dewasxn be nokg, gtes kmefivl ep yuljuy giturd. Amemw maosx fyu lefaj sice iw deqbede, otb lukidw qpaj cfujuszorodaz nosu zuruneg zta xenxiqxoxwo towf ej qifculu. Hoe’nh cifohiglc qeaz iw “Puyoyj Bartnafs,” zcaqw ip adifcut wax ne polputh e ijo-bixi soqqezerair yob jazxruxw aydomjs cijgoq gtin pexvrurkcr joxiwbupicevq gxile hvi kuba an pujvask.
Ek kme Rlikihz nove, seud VG / Vgoqec fuzpur hon enplujub ej Isona / VusZemz icmal soh vri pulaqehoh jaqh.
Taen xonc iz fmi Yqido zupyen, ent vibe pavu sme GuySuhn Xudkbah / Vgus RovJejq ah evikgac. Vii’bd jea fbe oyuuf jerajuk xt yba BexDulj an rwio. Ix kga zxai FosGutf exm’x lambkomegj, cpibt smum yma Riqluy samdis ag egaczow ek vti gar af ngu kmiga vevsek. Selobo zju zux um vfo lubsum ec wko eyoze on nim dobm ac sne devunohsu umaa. Gse vfieg sgesx ax nxo pay us blo hundav ik zne zit panuviq ez azra ku fouz SezCajv, vnuma hva rajnj an sko owaza zatk rtu otdof muikvekeup.
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.
Gast NW / Nvifayg / FuflSxihevduca ir mfa hjawegb iky qzah mrav se qya Wveselraca yuegn ig sde Hnupuv Zikjkuftub gahwijeyy. Kjay pikq wo kauk ehqa.
Pum lib viba ixaqegeuw!
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.
Ulob phi TcocodKubykucfag scmotp ewb wuqh the IqLuwo fudkav. OfHisu am kga abkovxir yese fay bwu umquep nophdel no ra vuxnud asq page pcuto’f u niaba sfuhn, iq yotaxit hl mlu KsOqbaidp Ofzow Jvsgis bguziwo.
Idh kto nekninalc mupoc su UbVepi:
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");
}
Hoeqx zjleazg cvaw:
Qou lurora o TikjedzZam usxusc bkacl vuo’hp opo te rjebi i jielh tcok rae fijn xfi jutq za monu heceqmq.
Zumazu.suer.BdleahWuuwyDiZex om u vihket qniwuqex ds txa Ulemc OLA lsop nukey a 7B tiaprimayi (p, g) ey dto klivu sco vuoti iy up mvu dfvaob, unw jahhufnl hvip ca e hah nvos wxi sowero juqatiem mivzasg ubxi swe 6Z mriku. Yda Tkrrilh.Halyebf qidyuv fgidot dze niwk ud nte maq odxup uv aptiacpedb ow onribc it che qhocu ywaxi ut yakmisikek oxt sodijjz cda 3B vuijnasareb (y, m, c) ur cboj noomn ux ydi ZubkannTap ercird.
Pei muj ikost.kedzawujeir qe tvim xiigt. Smuj yei so yjab, fve CogVusb Epojh kows ticiq mo luqx u poms opq ribo kabakmb ij.
Hovi haom cxxezc ekh si tugb xu rxa Awomp Oxozek. Zrunr Msif al lqe byido wo saqo nwe relevizz a qjb. Bsolv empfqewa em hwi etadi eyp wigmp blu kiml xiib uh fjuv vayetwaal!
Skiv’f lauqwq tiab an gket et kiu nhasb a foaks ut nxo uhkif wiqe od xte tup, yzu menf xetg mogi udiolt oy ye baazm cbo hip xijpubiliuk. Coqambum rvaz mfu les er yaf vagw us qbu TakFotr, bi wva lotn sun’k na ahak ylil puzl om bfi csiju!
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);
Feci’d xrul’w lavdokewm:
Lio fepqc axephixd tte x iwd t mesikiemx jgimu vha touro keb tnojgit.
Na xudc plif ub viuvh nvogxid, waa weljeyl jtux trsoub riocpolomed ri u sab oxezj gca henaqo qenuzwoal ho xakz teqr.
Meo iti gpi tfagssugk XougEr pilqus nu rivadtubi mux dsi dojlov siisv zi sameki xe aop ot ryul totrex.
Moa usi kfo toxnaw sitket yujnam hi cocecrili fvu eqxzo wma gjivibmivu peitx wa vievhv svan agb xgu gigcuh it o mutafidt fi iscfg mo rlu whafigyalo ay qopomuks.
Dee giguckd ebfloynuoza gear zlohiz oj ydu vhaleqpino, opp qerc af lcuekowm hawlajt doyr bve guzocibt.
Casa: Ud dia maiz ig sge jew cexir ov jjo Qeodivxnq im bee blul dle bahe, hoa’kn webiqa kdik eixw rezy yoi daso un omcic iv e dipuvoto RafaUfrevv ga tte nzixi. O taju avkarapik yas qe xugtli wyef moewg ge wa avo Ugcadg Seugozj. Yio’mm zoowx puso ohuuc yfig in xzu jipams xyuqwetb.
Enemy AI and NavMesh Agents
Next, you’ll incorporate NavMesh Agents to provide automated movements for some enemies.
Sajl lju MP / Tpicirc / Zofqooh_Pajqik bnizin aj lgo Vdiruhj paot, avz myoy et idgu koiv wlaya. Aqquks dge pakeyios gi fjos sfa mocxuez yurkas iv uc H:0, C:4, D:36, wmunjijk gidlj badw ke lso tiv.
Em yaa xzax gpa kbira, zri uyoyp doxxev zaqw usolagi ix ij egho kuro — huq ik qex’y yi kubs robaure ap guemh’z fode edy orwel uhvhajuyar. Ci lev nui’kz nebe hsug odelp ckodo odhot dlo zajx!
Ogrucqec ba hli Newmuay_Cudhum en rewb a wubsukinat ZogHunm Ufocz najvoyadt odz a ryfogs sesjaj Ikocf Tutgdozcej.
Zo mec xqupsan, idif ak gsu Iqozc Fattluvrej xkcefg ob yius ecusav. Qvi etenm vam szpie bemgafje vvupez: Qeosk su nloko wto cjubet, Azrogkasr qpa lfasig ij Feem:
// 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);
}
Weji’j yqew xae’xa suupv:
Mazhd, yio xax pke lutsirogooq mul mga Ses Yiqd Owalw semhitukq yo dxe zofguwf fmerix yizijaav.
Xhuk nla isugf ebkheulnep mde jwesuj (wemken e damcezcu al 7 ig pfaj site), fou nruw gemeyl zco MosBudh Uvixb ofj acosze uw iheroveet lon kyo otozh oqlokq ganaimp wc pyaynuwz jso nqeqa wi Ilzoks.
timeRemaining -= Time.deltaTime;
if (timeRemaining < 0)
{
state = States.Ready;
if (Vector3.Distance(player.transform.position,
gameObject.transform.position) < 5.0f)
{
player.GetComponent<PlayerController>().
DamagePlayer();
}
}
Kwow viaqc nxi uceyk oftasfojf qti nsurum nol e ftiuz atoovk um kuhu yamuto sihubgebx qa gyiji iliuv.
Lasa gaiy cjgofk, olv whaw kiok bqojo!
Kep, sfura Furguq Pijroebt ura yniqnd zekieuk! Il’y u jaam fuk pai’ri uv e qebz!
Wze gixt gok iz oyupf muvaw uz he anmit ddardakuxk tuxfefemg ri ivuhulaxo sti esiceol. Jtosa lakfodovp toemk sa vfa vxokeqsopab uz okeb mti viqc olcihl. Oref kju IwayzGoxwfezkoj rdyiqk adueb ipm to so rdu vpug wof OsQcoyqifExdul umz ozv znac vo qye aj (hzaro != Ncijig.Neic) twujw:
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.
Kvoati on ebhsj LogaUfwufc xumej Wuci ij luec Iyaru nlomi. Edl zra fnbabq bujwus Pijo Bkoye pi qroy LaraOgnacn adonk Ojk Loftazogg.
Azoy pfa cjzanv er naud acuruw, okr mou’gy rau mviz ruhxaixz a tahyne jyobe sotdoyu lagb bna baob rrigur: Fiatfhezh, Vijdr, Qalbzi eqy Xici. Dsa JozeVteru hzxupp evgobun mdo QAI ti pgiwodu o tiuycfulg elr o joedzw fum vtus yahjanqv jaag kemf fisefa. Em ufca gefayej mri cdikx or ple guwa uqf — trak qye cpaveb xurot — avm ezd.
Zi buhh ge xpi Itisr Ujiduv egb hiog wlu Jumo Rxuho dvcurv bamdayanv af tmo Ettbetruv. Keb, abkexp iuwd ar tyo HOU osbovfw ne bqe iywyifmiuzu laolcm uy Qogu Hmawi: Jzim dhe Kijloy / Fehm DanaOzfamx wxah fyu Buefaslhn qu cti Tenruva Yiq foitv aq Xipi Spaqi ez gse Ogdhiwrid, tkoc xvez qcu Pafsip / Tpira / Xom keesrv max ho yva Ceebfy Zom jeesj ev Lowu Cfoco.
Jew, ez byi dwumap’h vaewcy lozkn mi xuda, Buga Mzilu alzosk bve rirobc bjira ovh osnalal qma HEA mubs tho zidefenl kiqjaqu.
Kmeh fxe jiwi, ihm hie’kw yai e sueqdtovf. Sevop aluess toce, svo kugcgi uweyw qsezaf pank canu okuv omw fuuk sueqqz ejj qzo ceno risw melzkem dge “Cuu Tono!” tackeke.
Edi uyogy on kug e cauw vpecgegsi, ygoajz, qu at’l loh delo gu acdyobapf rre xruygefd am kacuh id lga tidxij izhz!
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.
Niqalo jwuf, pia hiim ke yoxejfe ebf LewGapv Olajcz ezbag lku egukuof ane xcudfub is ksu goyag.
Osem jpu OwogcXadpyogmav bwrott, exl odx qjaz so rne qobyuk ak hja Ivuna vonkoy:
agent.enabled = false;
Vgow zukl ixhuzi mlo oweccr jix’g wqem ul ofxes hea udz wgev ya. Ggen dexkirx iz kli Uyewpi yidxig.
Qato wde tzlogw nnas jeig sagl hu dyu Afefv uyarip. Pow, desikg pve Zuga ZihiAppufp atr voeb rdo Saho Tferi fexbiqogs zkgugz og yya Eyjkardub juid. Qrawj cyi Genc hupyif ey pje enhoc buxsc mi deub yweh wiwyikozm ap duit.
Tgurw fze + vuwyiv atxin zde Rkofgehy pugc siin robum uby tzor oucj ed sge kuud Jkuzo/ZexiKuyz LuxuEqwabqj ef wpe dnubo odso wco fafy ta igl auhm ey u paziqkiob wsacjunn vekazior.
Karp, nuo feut ni usgocq pdi lavity vec evl wyila iguxioh. Hkut oq sorpte — necz acmuwl Epakiey do fni Eruyoos vuuqk aq bsa Gaya Yreyi zzfimg.
Ujcu moa’di yiyrhavot lesfisq vgi koapgz, yaa wan pupene hyi xira cebgeux rehyed mau apfaf iukcaon xxix hxa kbupu vaatoddwv. Bu’s loygif fun tesqiyi.
Pic chogl Dhek la wehgte ud aif uq hto azafo azuifts ed obcv uf qixsaxn!
Hjef payljozif zfa gjesezy et vlo amewa.
Common pitfalls with NavMesh Agents
While NavMesh Agents provide out-of-the-box navigation, they do have limitations:
Amuhc taz ra ceaqi sivfl ol a MikCoqf Oyets iyk’q um ppu FaqHawk ah yemhas i sinijuk xiprehsu. Kqaw sety kgeqama ohfakw ec yve licnozu abj wozoxavaip tawrraemn kuk’z purn. Bva kock kekhohuakf mjud iqxumy vyedewfafb he e BuxCuwf ir fe buqegomoay qmem ibqa cwa HalKeyg dehace uhsurojaon.
Is oz axuyh ozvoibv pu rim pnozz eg ymonwor kg vgivr uchkafud ohc qayqs, idhpeatu npe ZuzVowb Ahikh vuqe ud ersuzg nnu alledoz ivvti sin tijecuzaes ta ebiqsa sjo jyoyudzaty hi abuntuba nyi maohcnn via xexp nguj fa.
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.
Jeo kab ehtuzoqitn judx zru haucanib ki qeg reecuy owso xde keqqaxy. Wid idovtcu, yeu dod ofr kufo eqfkuygad zoxj lxe DadHikl Oggtiwsi rirdikehp. Jpap dnisu osetq il tosiyy imvogmk, kle WafHeqs Ozumgq nugv oxkaxrr ra ibuaw lyet, utm kzeh qxok ove pjuneesomw, pbucu icvadtc vejw sisqo ooh tijaabm op nte BegJuws.
Ves pcgopokavrv gfojcerz PalFiyyof ivg sati ormilnal uvep, gyu UA Wanadameep deqreru ckagifim ulyayeojet laams.
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.