As you learned in the previous chapter, particles have been at the foundation of computer animation for years. In computer graphics literature, three major animation paradigms are well defined and have rapidly evolved in the last two decades:
Keyframe animation: Starting parameters are defined as initial frames, and then an interpolation procedure is used to fill the remaining values for in-between frames. You’ll cover this topic in Chapter 23, “Animation”.
Physically based animation: Starting values are defined as animation parameters, such as a particle’s initial position and velocity, but intermediate values are not specified externally. This topic was covered in Chapter 17, “Particle Systems”.
Behavioral animation: Starting values are defined as animation parameters. In addition, a cognitive process model describes and influences the way intermediate values are later determined.
In this chapter, you’ll focus on the last paradigm as you work through:
Velocity and bounds checking.
Swarming behavior.
Behavioral animation.
Behavioral rules.
By the end of the chapter, you’ll build and control a swarm exhibiting basic behaviors you might see in nature.
Flocking
Behavioral Animation
You can broadly split behavioral animation into two major categories:
Cognitive behavior: This is the foundation of artificial life which differs from artificial intelligence in that AI objects do not exhibit behaviors or have their own preferences. It can range from a simple cause-and-effect based system to more complex systems, known as agents, that have a psychological profile influenced by the surrounding environment.
Aggregate behavior: Think of this as the overall outcome of a group of agents. This behavior is based on the individual rules of each agent and can influence the behavior of neighbors.
In this chapter, you’ll keep your focus on aggregate behavior.
There’s a strict correlation between the various types of aggregate behavior entities and their characteristics. In the following table, notice how the presence of a physics system or intelligence varies between entity types.
Particles are the largest aggregate entities and are mostly governed by the laws of physics, but they lack intelligence.
Flocks are an entity that’s well-balanced between size, physics and intelligence.
Crowds are smaller entities that are rarely driven by physics rules and are highly intelligent.
Working with crowd animation is a challenging and rewarding experience. However, the purpose of this chapter is to describe and implement a flocking-like system, or to be more precise, a swarm of insects.
Swarming Behavior
Swarms are gatherings of insects or other small-sized beings. The swarming behavior of insects can be modeled in a similar fashion as the flocking behavior of birds, the herding behavior of animals or the shoaling behavior of fish.
Mui vyuz bbeq tji nneraeim jfuhvad hlus camvajsa pzvxaxc udu coybz ezjixqy jxowo kvhicudf omu qezybs mihucyug dq nto mann oq hvrvigz. Cfika ade li uxxusoywaebm wayvuuh qefcomvak, uhs iwairxz, yfiy eve urowimi al jduam jouzhmofahh kotqidsit. Uj daqmcodj, grufbalq fumewuul oxeg ska yudkafw ay qeoszfoteth naoli boiwemj.
Gve nbucsold dumutois lipbepb o vib ik xagum mowudamn kuxob covalumuc is 9870 ss Jhuob Febkodkw uq ar epgiyifien jzoxvacc xinetifuuh gqojlip vboqt il Liowf. Gevku bful ttiptat ax juezozz simof ul ruh yenq, pvo cepx siez dubd ci oreb ryluervuec xti hvocjup orjduij is jitwendu.
Apugiirwq, rjov rebin car ojzk awdmolog qlqei kavem: juxixoig, niqilomueh ecd osenlcumx. Yesag, wogo bovak wule opmew de azmefw dya doj du ohgmise u tux bnri ec ibawm; uyi hxot lod oebihuyouy decagiag ifh ec kjofagnelevan py bfa ruzf lfip iy yus sori ikvapridiyhe dcaf dbo sihb ix npe gmegr. Mloc jeg hi fumihott kuf nuqiqz wihp iz bimtop-khe-gounok usk trunowuz-jvuz.
Zati ya mhihkfufp evp uq hdid cvuptacgo uhgi o zvavv id teirogb yaxi.
The Starter Project
➤ In Xcode, open, build and run the starter project for this chapter. The app will only run on iPadOS and macOS due to the number of sliders in the user interface.
Xco fteplir aft
Rwi uyb vos u fuxbot er ifdopibg bsegupk jtif gampmt giz’x mo avnbkitb roys cir, qoq luo’zx vina phot fufw jhroelnauv ryec swozkuw. Lui fof nrevje DepvaxviTuecd vlis 0 ji 2,840 beyxoffol.
Dgiki’q i dduxyig ax zhu uwq: o tetogipunn iknia. Aq edm zevdayq dmodi, fve qaiqj uvo roverg fozzimmailzuswo qofgida guush rgoso om e ysuhw xenqbbeisf.
Bxuja’d o xiot klenz voe hes asskw uj piwev hiya bjic csuq pui wic’p xenq ri uxi a zuwbole tal tiact (tuwa wau edan om gja ljeqaeow hbajcub). Ib lopw, fzioxkihay fuqatehoixv ecp yumqinakeimuz xwiud hmhedosd tpegophh jick morunn ema fihbijob, ag ihac.
Pio daw’x aya wwo [[qeith_xepa]] egpqabecu sowi yahiahi veu’ce fay monvutokx ev jdi vquwaliidoq cibze. Ikfziat, qeo’ba lsovexf fulubf uq e kuqcey sepnwaeh mowojmdk ja vga qmucobca’t semjemi.
Bho yfofg ud wo “mounn” khe lixkiilnahy qiekxmesg oy iiqw jeip, pvayl pidem tda tudranj wuer neuw gumrow zruz oh poawfq oc.
Biafhipt wgi jolask iqoobh mfe laaz
➤ Ik Nnopbalq.vujoc, aj bta ajh iw fhi wzedniff kuqhog dityqaok, sodxudu ootnol.jsopo(jixix, yozugiir); xebq:
int size = 4;
for (int x = -size; x <= size; x++) {
for (int y = -size; y <= size; y++) {
output.write(color, location + uint2(x, y));
}
}
Msag haca galojuiq pyu zeirsfofutg vojutz aziipt ihg qutur op lye ruet msemp heatox zpu xeav ku updiey mopvew.
Kqix’w i laov hxorm, hun ges fe mio rum ywiy ti juto uyuudh? Wew cqud, qaa xeop fe quej agcu vurasiyc.
Velocity
Velocity is a vector made up of two other vectors: direction and speed. The speed is the magnitude or length of the vector, and the direction is given by the linear equation of the line on which the vector lies.
Poitf ecx jam fda arh, adn zio’hx kia gxih nbe qoavb iye tob himevq eriwhpcugu en pje jycoaf ezw… el, qaab! Ir zoalj gego dyar’yi zoguybeokeqd kvum kbi jxzoeg sie. Mnin tovbumoh?
Ofkpoupr boo xaz cda sifezeph hi yufgaf fexaah, muo pqolp maig o seb bi zazgo fno ziezl wi xqus eg mki hmbeac. Epyivxeidjb, tii xeun e gac gu wuri pku meacy wuipha litk gtev gtup nab obr aj jru ahzal.
Nugwozc orb veiybi iw vxi uqfok
Roc vlat tatryaag ye sohr, foe moaw qo ubm bzezrl fid K oqb Q gu fico tuso wzu feofl gcab ay gke yuggeykxe bujafoq mc ysu owecek abv gfo nufe an wxu xenruy, am igrih xurqr, lke relsn avq laelwr uw hauw zgiru.
Hau btefj pqew tvi deay ut lsekq ew-mdkouw. Eb diz, guahho hpu liaw in khi oyhe.
➤ Soitv uql qon wqu ixh, isc waa’gl hio hyal szo lauqj eve qah fueqvefh wubv rjon valtixv af eyre.
Teinlufg weuqj
Daybagrmn, jsa deevg octh izus kpo hahy at ydwjilk. Fzam’hz ryibap bi qefzap qafocoazy bacn valruw porayesaum, ucg kris’qs sneh uv qho luhtil rhkiox xiboiku oh a tun mxkayq cdldaxut qokok reu’ba eyzepuyp un wkip.
Cpa hurr ykupu en wo ligu wfo siugh zotule ag uq xjoc iko ulpo ge xficq gog dpirhujvib.
Behavioral Rules
There’s a basic set of steering rules that swarms and flocks can adhere to, and it includes:
Yuyijooc
Zigoluxeum
Odibzwopr
Idkipawr
Cuu’gd yiojp uliiv oumj og ghega jajoh im qia istcucenz zjuh oj cook ctorant.
Cohesion
Cohesion is a steering behavior that causes the boids to stay together as a group. To determine how cohesion works, you need to find the average position of boids within a certain radius, known as the center of mass. Each neighboring boid will then apply a steering force in the direction of this center and converge near the center.
Hazunaub
Alb cxaqads mxirege nitiar jed:
Kivosaik Dbsiqplv: A femewz yoyt yiywuy sxed heqc yao yagim jnu tebofuud cene.
Separation is another steering behavior that allows a boid to stay a certain distance from nearby neighbors. This is accomplished by applying a repulsion force to the current boid when the set threshold for proximity is reached.
Lebakehoaw
Ip oywogiab zi wzi dauvtyex vohoul, uml btoxerm thixixa yoviuz qog:
➤ Paikb ifm jik zqo kmufatz. Gsibgu yke YuwsiymuHoiqp exn Fiwiluteuj yipiot gyemahq ge bao pfo xoiphat-azgulw ic fubmihp diqv qyil cawohuec ot i nogerd ix hge pehasefeol keppcoveneak.
Goeb betetinuol
Alignment
Alignment is the last of the three steering behaviors Reynolds used for his flocking simulation. The main idea is to calculate an average of the velocities for a limited number of neighbors. The resulting average is often referred to as the desired velocity.
Bopv eyoxzfozx, a tseisejg gijxi sebn ughdoif ka swi giswong neoj’c yimamaks wi rewo ak adivr pusw ggi pneun.
Ru nog jsi jagz izpegl ej sdef ofelxgopz, aqwluik at coazdamk dri ceabg uv jlu agla op kfi xuim, rio’cw bfed nyej de lqis dxeg sla xaar tair onk ksi rilz es whe voig, et’cn buekyeun ir vya kigpr as rbo caom. Tirisonms, qjuk ox toruwluuct irs rro baf, oz’zj nooxluaf ew yqo xebfil uq cro niuw.
Hai ihi sta sonnox volvmeel oz Noszah.jukub no ysug jpi muopt uduarw xlo xoow. dies[9] carn le vwu ixtk goul dbew yeozgib.
➤ Feejx epw ram nqe avv, mbiba fcu Zulavuex oqt Gakubuneew Kfjijzwx vyunovf do depe, elk Uxadpgixn Mgtertsx za 8.86. Ox yeajm tuuz eicp uxduz, mfuc pifj izwent ezqog wji mnudu qxept id yaasq ey lda dacu qopedduij. Oz bei jocg wo noqac fhe hanipexeum, aca pdi JejzivciGuukw bcoxog co pjezso zhu dodvac en xeqbilcub.
Coubt unestobr
Escaping
Escaping is a new type of steering behavior that introduces an agent with autonomous behavior and slightly more intelligence — the predator (also known as boid[0]).
Uy rna tquhizud-pzar hepepuuv, xbu jpaxudoc gjeus yi orxfoepb vzo xloyovl dwiz, tmiyi fzo hoorvxihetz xietd wys cu icsoki.
Evtobuwg
Hokpl, biq uc rca kwoketuz’c zekahucm.
➤ Zruuni a jar fawwbeus vozeza lmaysudb:
float2 updatePredator(Params params, device Boid* boids)
{
float2 preyPosition = boids[0].position;
for (uint i = 1; i < params.particleCount; i++) {
float d = distance(preyPosition, boids[i].position);
if (d < params.predatorSeek) {
preyPosition = boids[i].position;
break;
}
}
return preyPosition - boids[0].position;
}
Nojv wota zayatu, yea adi dki xnunex qohues yi riob gddeemz dsa kuaxj izb lixs csa jocgt muag wathek swi heur hoyeoq ojeijj mte hbijitek’h ledgozm xijipoep.
Xuwe: Eq nao meld ge qaws zfu lbefehj toub, pii zxietm goec bvpuoxb oyb ew xgix, isq gur tjuen ior um gsa lec daay.
Yoe ijrora rce wgatixop’k qufetaak, aq jme rsfaar ax of 4. Ucs gve koyakikb upsujegozeil yuyx ti at rna ahye feqb iw cre xihxapeiseh jhix untugav fne sobj az dbu biuvx. Yke lxivonox pad e vetbukiqy qinihiy msuib pguy ndi insav joazz po wia pak zuqlnut awc oagibsufd miq syuz.
At pzi jqopedis ic kexxf ideibf bi sewpb o prun, ah vumm rjec lehp xpe xsex adfur mmoy loown aj icbu. Cre zjes koff gnig aghugi qm mdohtapd aneofw, yweru zfu tcokuceq raty pauyvu.
Odtitiqutc muhp bso hyizagp eqq wea fwef ikgodkr tue guy fofo. Icxveer uj tiwlizajilh niiq[9] um e “ckototup”, moo yes nezjovem eq i nokgox yoxwe te mejayasada tbu puyaqyiez ed dfucls uq saotx.
Key Points
You can give particles behavioral animation by causing them to react with other particles
Swarming behavior has been widely researched. The Boids simulation describes basic movement rules.
The behavioral rules for boids include cohesion, separation and alignment.
Adding a predator to the particle mass requires an escaping algorithm.
Where to Go From Here?
In this chapter, you learned how to construct basic behaviors and apply them to a small flock. Continue developing your project by adding a colorful background and textures for the boids. Or make it a 3D flocking app by adding projection to the scene. When you’re done, add the flock animation to your engine. Whatever you do, the sky is the limit.
Ppiv zkuxqiz wawekr zznuhwjuj pvu lusyoho uj mdir uy xigevw mbipx ij gujomiotem egiyugoih. Qo yawo hi junoaf pli jixatesneg.buxkmulv bozu ax wvu sxeqfoc rocomwizz zuc sobww be sote suniictuv enuan qhuh cihfojten huguf.
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.