You are on page 1of 519

!"# %&'()# *+ ,*-# !

"# %&'()# *+ ,*-#


by Lonll 5hlmon
th publlshr would go hr, but thr ls non, lt`s only m.
vrslon 0005, gnrotd Lcmbr 4, 20J2
7h|s |s the t|no| lDl te|eose betote the boo| goes to pt|nt. l|eose post ony cottect|ons to
G|tHub (http.//g|thub.com/sh|ttmon/7he-Notute-ot-Code/|ssuesI by !!.59 lM (l57I Decembet
5, 20!2.
l
.#-/0&'/*1 .#-/0&'/*1
|or my grondmothr, Bllo Monl Grnlld [Octobr J3, J9J5 - Aprll 3, 20J0j
Bllo Monl wos born ln Nw York Clty. A plonrlng womon ln mothmotlcs, sh ornd hr
PhL ln J939 rom Nw York nlvrslty undr th suprvlslon o Rlchord Couront. 5h workd
or Romo-Wooldrldg [now 1RWj ond ot th Rond Corporotlon wlth Rlchord Bllmon. Lotr, sh
tought mothmotlcs ot th Collg o Notr Lom d Nomur nlvrslty ln Blmont, Collornlo,
ond ot CLA. 1h Bllo Monl Prlz or outstondlng groduot work by o womon or mlnorlty
wos stobllshd ot NY`s Couront |nstltut ln J995.
1h Notur o Cod [v005j
ll
Ldltor Ldltor 5honnon |ry
|llustrotlons |llustrotlons Zonnoh Morsh
Covr Lslgn Covr Lslgn Lovld Wllson
|ntrlor Lslgn |ntrlor Lslgn Lovld Wllson
Wb 5lt Lslgn Wb 5lt Lslgn 5tv Klls
Ldltorlol ond Lslgn Asslstont Ldltorlol ond Lslgn Asslstont Lvon Lmolo
Moglc Book Lod Lvloprs Moglc Book Lod Lvloprs Run Modsn, 5tv Klls
Moglc Book Rsorchrs Moglc Book Rsorchrs Lvon Lmolo, Mlgul Brmudz, Lulso Plrro Hors
|ndx |ndx WordCo |ndxlng 5rvlcs
Copyrlght 20J2 by Lonll 5hlmon
|5BN-J3. 978-0985930806
|5BN-J0. 0985930802
1hls work ls llcnsd undr th Crotlv Commons Attrlbutlon-NonCommrclol 3.0
nportd Llcns. 1o vlw o copy o thls llcns, vlslt crotlvcommons.org
[http.//crotlvcommons.org/llcnss/by-nc/3.0/j or snd o lttr to Crotlv Commons, 444
Costro 5trt, 5ult 900, Mountoln Vlw, Collornlo 9404J, 5A.
All o th book`s sourc cod ls llcnsd undr th GN Lssr Gnrol Publlc Llcns
[http.//crotlvcommons.org/llcnss/LGPL/2.J/j os publlshd by th |r 5otwor
|oundotlon, lthr vrslon 2.J o th Llcns, or [ot your optlonj ony lotr vrslon.
1hls book wos gnrotd by th Moglc Book Projct [http.//www.moglcbookprojct.comj.
Ldlcotlon
lll
2031*45#-67#1'8 2031*45#-67#1'8
"The uorld cround us motes in compliccted cnd uonderjul ucs. We
spend the ecrlier pcrts oj our lites lecrnin cbout our entironment
throuh perception cnd intercction. We expect the phsiccl uorld cround
us to behcte consistentl uith our perceptucl memor, e.. ij ue drop c
rocl it uill jcll due to rctit, ij c ust oj uind blous, lihter objects uill
be tossed b the uind jurther. This clcss jocuses on understcndin,
simulctin, cnd incorporctin motion-bcsed elements oj our phsiccl
uorld into the diitcl uorlds thct ue crecte. Dur hope is to crecte
intuitite, rich, cnd more sctisjin experiences b drcuin jrom the
perceptucl memories oj our users."
! #$%&' () *+,$%-. /01-&' .0)2'& 1&'.2-34-0,5 632-,7 899:5 ;(<
1h Notur o Cod [v005j
lv
!"# ! %&''%( )&' *+ ,&-'*./ !"# ! %&''%( )&' *+ ,&-'*./
|n 2003, os o groduot studnt ot th |ntroctlv 1lcommunlcotlons Progrom [|1Pj ln th
1lsch 5chool o th Arts ot Nw York nlvrslty, | nrolld ln o cours colld Lynomlc
Bodls. 1h cours wos tought by lntroctlon dslgnr ond |1P odjunct prossor Joms 1u.
At th tlm, my work wos ocusd on o srls o sotwor xprlmnts thot gnrotd rol-
tlm non-photorollstlc" lmogry. 1h oppllcotlons lnvolvd copturlng lmogs rom o llv
sourc ond polntlng" th colors wlth lmnts thot movd obout th scrn occordlng to
vorlous ruls. 1h Lynomlc Bodls courswhlch covrd vctors, orcs, osclllotlons,
portlcl systms, rcurslon, strlng, ond sprlngsollgnd prctly wlth my work.
| hod bn uslng ths concpts lnormolly ln my own projcts, but hod nvr tokn th
tlm to closly xomln th sclnc bhlnd th olgorlthms or lorn objct-orlntd
tchnlqus to ormollz thlr lmplmntotlon. 1hot vry smstr, | olso nrolld ln
|oundotlons o Gnrotlv Art 5ystms, o cours tought by Phlllp Golontr, thot ocusd on
th thory ond proctlc o gnrotlv ort, covrlng toplcs such os choos, cllulor outomoto,
gntlc olgorlthms, nurol ntworks, ond roctols. Both 1u`s cours ond Golontr`s cours
opnd my ys to o world o slmulotlon olgorlthms ond tchnlqus thot corrld m through
th nxt svrol yors o work ond tochlng, ond srvd os th oundotlon ond lnsplrotlon
or thls book.
But thr`s onothr plc o th puzzl mlsslng rom thls story.
Golontr`s cours wos mostly thory-bosd, whll 1u`s wos tought uslng Mocromdlo
Llrctor ond th Llngo progrommlng longuog. 1hot smstr, | lornd mony o th
olgorlthms by tronslotlng thm lnto C [th longuog | wos uslng qult owkwordly ot th
tlm, wll bor C crotlv codlng nvlronmnts llk opn|romworks ond Clndr hod
orrlvdj. 1owords th nd o th smstr, | dlscovrd somthlng colld Procsslng
[http.//www.procsslng.orgj. Procsslng wos ln olpho thn [vrslon 0055j ond, hovlng hod
som xprlnc wlth Jovo, lt lntrlgud m nough to osk th qustlon. Could thls opn-
sourc, ortlst-rlndly progrommlng longuog ond nvlronmnt b th rlght ploc to dvlop
o sult o tutorlols ond xompls obout progrommlng ond slmulotlon? Wlth th support o
th |1P ond Procsslng communltls, | mborkd on whot hos now bn on olmost lght-
yor journy o tochlng o vorlty o progrommlng concpts ond thlr oppllcotlons uslng
Procsslng.
|`d llk to lrst thonk Rd Burns, |1P`s oundr, who hos supportd ond ncourogd m ln my
work or ovr tn yors. Lon O`5ulllvon, th cholr o |1P, hos bn my tochlng mntor ond
wos th lrst to suggst thot | try tochlng o cours on Procsslng, glvlng m o roson to
stort ossmbllng progrommlng tutorlols ln th lrst ploc. 5hown Von Lvry, dvlopr
xtroordlnolr ond outhor o lto Andto|d Med|o, hos olso bn o rlch sourc o hlp ond
lnsplrotlon ot |1P ovr th yors. |1P oculty mmbrs Cloy 5hlrky, Lonny Rozln, Kothrln
Llllon, Morlonn Ptlt, Morlno Zurkow, ond 1om |go hov provldd o grot dol o support
ond dbock throughout th wrltlng o thls book. 1h rst o th oculty ond sto ot |1P
hov olso mod thls posslbl. Brlon Klm, Ldword Gordon, Gorg Agudow, John Luon,
Morlon Lvons, Mott Brgr, Mgon Lmorst, Mldorl Yosudo, ond Rob Ryon.
Acknowldgmnts
v
1h studnts o |1P, too numrous to mntlon, hov bn on omozlng sourc o dbock
throughout thls procss. Much o th motrlol ln thls book coms rom my cours o th som
tltl, whlch |`v now tought or lv yors. | hov stocks o drot prlntouts o th book wlth
nots scrowld olong th morglns os wll os o vost orchlv o studnt molls wlth corrctlons,
commnts, ond gnrous words o ncourogmnt.
| om olso lndbtd to th nrgtlc ond supportlv communlty o Procsslng progrommrs
ond ortlsts. | wouldn`t b wrltlng thls book l lt wrn`t or Cosy Ros ond Bn |ry, who
crotd Procsslng. |`v lornd hol o whot | know slmply rom rodlng through th
Procsslng sourc cod, th lgont slmpllclty o th Procsslng longuog, wbslt, ond |LL
hos mod progrommlng occsslbl ond un or oll o my studnts. |`v rclvd odvlc ond
lnsplrotlon rom mony Procsslng progrommrs lncludlng Andrs Colubrl, Jr 1horp, Morlus
Wotz, Korstn 5chmldt, Robrt Hodgln, 5b-L Lllsl, ond |ro Grnbrg. Hothr Lwy-
Hogborg provldd o grot dol o xcllnt dbock on Choptr J0 [Nurol Ntworksj. 5cott
Murroy provldd som rolly hlpul odvlc obout lnlln 5VGs ovr -moll. Mony o th tltls ln
th |urthr Rodlng sctlon wr suggstd by Golon Lvln.
| om lndbtd to 5honnon |ry, who dltd thls book vry stp o th woy. 1h knowldg
thot | would olwoys hov hr corul ond thoughtul dbock on my wrltlng ollowd m to
plow ohod, owor thot vrythlng would com out soundlng bttr otr sh got hr honds
on my choptrs.
A spclol mntlon gos to Zonnoh Morsh who workd tlrlssly to crot ovr o hundrd
lllustrotlons or thls book, dvloplng o rlndly ond lnormol look. | spclolly wont to thonk
hr or hr potlnc ond wllllngnss to go wlth th low os w chongd th lllustrotlon
rqulrmnts svrol tlms. | olso wont to thonk Lovld Wllson, who com to my rscu ot th
lost mlnut ond dslgnd th lntrlor loyout ond covr or th book. | om portlculorly grotul
to 5tv Klls, who dslgnd ond bullt th book`s wb slt, hlplng m to dvlop o "poy whot
you wont" modl or th dlgltol PL|.
As |`ll xploln o blt mor ln th proc, thls book wos gnrotd wlth o nw opn-sourc
systm or publlshlng colld 1h Moglc Book." A crock tom o |1P progrommrs, dslgnrs,
ond ortlsts workd ovr th cours o mor thon o yor to dvlop thls systm, whlch
gnrots o book ln o vorlty o ormots [PL|, H1ML, ond morj rom on slngl A5C||LOC
ll, oll dslgnd wlth C55 loyout. Run Modsn bgon th projct ond dvlopd th orlglnol
Ruby / 5lnotro romwork. | om prtty sur |`d b struggllng wlth puttlng th plcs o th book
togthr wll lnto 20J3 l lt wosn`t or Run`s ddlcotlon to slng th projct through to th
nd. 5tv Klls contrlbutd countlss bug lxs ond nglnrd th systm thot ollows us to
rstyl cod commnts to th sld o th cod blocks thmslvs. Mlgul Brmudz, Lvon
Lmolo, ond Lulso Prlro Hors contrlbutd ln mony woys, lornlng th lns ond outs o
A5C||LOC os wll os C55 Pogd Mdlo. |1P rsorchr Grg Bornstln provldd o
trmndous omount o odvlc ond support olong th woy rgordlng th oros o publlshlng or
th wb ond prlnt. Prlnc [http.//prlncxmlj ls th ngln th Moglc Book uss to gnrot o
PL| rom on H1ML documnt ond |`d llk to thonk Mlchol Loy, CLO o PrlncXML, who wos
onswrd mony o our qustlons [ot llghtnlng spdj olong th woy.
1h Notur o Cod [v005j
vl
|lnolly |`d llk to thonk my omlly. my wl, Allkl Coloyros, who supportd thls projct
throughout whll hovlng hr own glont tom to wrlt, ond my chlldrn, Lllos ond Olymplo,
motlvotlon or lnlshlng thls up so thot | could spnd mor tlm honglng out wlth thm. |`d
olso llk to thonk my othr, Brnord 5hlmon, who gnrously lnt hls mothmotlcol
xprtls ond provldd dbock olong th woy, os wll os my mothr, Lorls Yo 5hlmon,
ond brothr, Jonothon 5hlmon, who wr olwoys trmndously supportlv ln osklng th
qustlon. How ls th book comlng olong?"
!"0 1&23-'4.'(. !"0 1&23-'4.'(.
1hr ls onothr orgonlzotlon ond communlty thot hos mod thls book posslbl. Klckstortr.
|n 2008, | compltd work on my lrst book, leotn|ng ltocess|ng, publlshd by Morgon
Koumonn/Llsvlr. leotn|ng ltocess|ng took olmost thr yors to lnlsh. | dldn`t tok o lot
o cor ln chooslng o publlshr or thlnklng obout th trms. | just thought Rolly? You
wont to publlsh o book by m? OK, |`ll do lt." nortunotly, my xprlnc wos not ntlrly
posltlv. | hod lv dlrnt dltors osslgnd to m throughout th procss, ond | rclvd
llttl to no dbock on th contnt ltsl. 1h publlshr outsourcd th typsttlng, whlch
rsultd ln o grot dol o mlstoks ond lnconslstncls ln productlon. |n oddltlon, | ound
th prlclng o th book to b o th mork. My gool wos to wrlt o rlndly, lnxpnslv
[block ond whltj, poprbock lntroductlon to progrommlng ln Procsslng, ond th book
ndd up rtolllng or o "txtbook" prlc o $50.
Now, | wont to mphoslz thot my publlshr hod good lntntlons. 1hy honstly wontd to
produc th bst book posslbl, on thot | would b hoppy wlth, thot thy would b hoppy
wlth, ond thot rodrs would njoy. And thy workd hord to mok thls hoppn.
nortunotly, thy hod to work wlthln o vry tlght budgt, ond os o rsult wr strtchd
xtrmly thln. |n oddltlon, | don`t thlnk thy wr trrlbly omlllor wlth th world o opn-
sourc crotlv" codlng nvlronmnts llk Procsslng, thlr world ls computr sclnc
txtbooks.
As o rsult, or thls Notur o Cod book, | lt lt wos lmportont to try sl-publlshlng. 5lnc |
dldn`t gt dltlng support rom th publlshr, why not hlr on dltor? | wosn`t hoppy wlth th
prlclng, so why not st th prlc mysl [or, ln th cos o th PL|, lt th buyr st th
prlcj? 1hn thr`s th qustlon o morktlng dos o publlshr odd volu ond hlp you
roch on oudlnc? |n som coss, th onswr ls ys. 1h O`Rllly Mok" srls, or
xompl, dos o wondrul job o crotlng o communlty oround thlr books ond products.
5tlll, ln th cos o lornlng to progrom ln Procsslng, rochlng th oudlnc ls os slmpl os
on RL procsslng.org.
nortunotly, | qulckly dlscovrd thot thr ls on thlng o publlshr ors thot | wos not
gttlng rom my sl-publlshlng poth. On vry lmportont, hlghly cruclol dtoll o dodlln.
On my own, | loundrd or two yors, soylng | wos golng to wrlt th Notur o Cod book
but only drotlng o llttl blt hr ond thr. On my llst o thlngs | ndd to do, lt wos olwoys
ot th bottom. 1hn olong com Klckstortr, ond wlth on oudlnc slttlng ond woltlng [ond
Acknowldgmnts
vll
hovlng spnt cosh monyj, | llvd ln or o not mtlng my dodlln. And th oct thot you or
rodlng thls now ls on lndlcotlon thot lt workd.
Most lmportontly, sl-publlshlng th book hos ollowd m o grot dol o lxlblllty ln how |
prlc ond dlstrlbut th contnt. On Llsvlr`s wb slt, you con purchos leotn|ng
ltocess|ng os on -book or $53.95. 1hot`s rlght, lty-thr dollors ond nlnty-lv cnts.
|ncldntolly, or och -book sold | gt o royolty o 5, whlch ls $2.70. 1hot`s rlght, two dollors
ond svnty cnts. | | sl-publlsh, | con mok th book mosslvly chopr. 5lllng o dlgltol
copy or $J0, |`m rduclng th cost to th rodr by ovr lghty prcnt ond trlpllng th mony
pold to m. |`m toklng thls vn urthr wlth th PL| ond ollowlng buyrs to st th prlc
thmslvs.
|n oddltlon, by ownlng oll th contnt, | om obl to rlos th ntlr book onlln or r os
wll os xprlmnt wlth nw dlgltol ormots. 1h row txt o th book, os wll os oll th cod
ond lllustrotlons, ls llcnsd undr o Crotlv Commons Attrlbutlon-NonCommrclol llcns
ond ls ovollobl on Glthub, whr rodrs con submlt lssus [not to mntlon pull rqusts!j
wlth corrctlons ond commnts. |lnolly, by uslng mor lxlbl prlnt-on-dmond srvlcs, | con
mor oslly mok chongs ond kp th book currnt, rloslng nw dltlons os otn os |
llk. [A on-tlm purchos o o dlgltol copy o th book lncluds lltlm upgrods or r.j
5o thonk you to Klckstortr, both th compony [spclolly |rd Bnnson, who convlncd m
to tok th plung ln th lrst ploc ond odvlsd m on how to llcns th bookj os wll os oll
th bockrs who took o chonc on thls book. 5om o ths bockrs, through gnroslty
byond th coll o duty, ornd on xtro thonk-you os port o thlr rword.
- Alxondr B.
- Robrt Hodgln
- JooYoun Pok
- Anglo McNom [Boyhonj
- Bob |ppollto
All o th bockrs dlrctly contrlbutd to th lnlshlng o thls book. Just th shr oct o
slgnlng up to contrlbut mony or drot ond lnol vrslons llt o lr ln m to lnlsh, not to
mntlon provldd m wlth th rsourcs to poy or dslgn ond dltlng work [ond som
bobyslttlng durlng 5oturdoy mornlng wrltlng ssslonsj.
|n oddltlon to contrlbutlng unds, Klckstortr bockrs rod pr-rlos vrslons o th choptrs
ond provldd tons o dbock, cotchlng mony rrors ond polntlng out conuslng sctlons o
th book. 1wo such rodrs thot |`d llk to thonk or |rdrlk Vonhoutt ond Hons d Wol,
whos xprt knowldg o Nwtonlon physlcs wos normously hlpul ln th rvlslng o
Choptrs 2 ond 3.
1h Notur o Cod [v005j
vlll
9)#+&0# 9)#+&0#
5"# 6,4' &- ',&- )**37 5"# 6,4' &- ',&- )**37
At |1P [http.//ltp.nyu.duj, | toch o cours ntltld |ntroductlon to Computotlonol Mdlo. |n
thls cours, th studnts lorn th boslcs o progrommlng [vorlobls, condltlonols, loops,
objcts, orroysj os wll os o survy o oppllcotlons rlotd to moklng lntroctlv projcts
[lmogs, plxls, computr vlslon, ntworklng, doto, 3Lj. 1h cours mostly ollows th
motrlol ound ln my lntro book leotn|ng ltocess|ng, ln mony woys, 7he Notute ot Code
srvs os o ollow-up. Onc you`v lornd th boslcs ond sn on orroy o oppllcotlons,
your nxt stp mlght b to dlv dply lnto o portlculor oro. |or xompl, you could ocus
on computr vlslon [ond rod o book llk Grg Bornstln`s Mo||ng 7h|ngs 5eej. |n th most
boslc sns, thls book ls on posslbl nxt stp ln o world o mony. |t plcks up xoctly
whr leotn|ng ltocess|ng lovs o, dmonstrotlng mor odvoncd progrommlng
tchnlqus wlth Procsslng thot ocus on olgorlthms ond slmulotlon.
1h gool o thls book ls slmpl. W wont to tok o look ot somthlng thot noturolly occurs ln
our physlcol world, thn dtrmln how w con wrlt cod to slmulot thot occurrnc.
5o thn whot ls thls book xoctly? |s lt o sclnc book? 1h onswr ls o rsoundlng no.
1ru, w mlght xomln toplcs thot com rom physlcs or blology, but lt won`t b our job to
lnvstlgot ths toplcs wlth o portlculorly hlgh lvl o ocodmlc rlgor. |nstod, w`r golng
to glonc ot sclntllc concpts ond grob th ports thot w nd ln th srvlc o bulldlng o
portlculor sotwor xompl.
|s thls on ort or dslgn book? | would olso soy no, otr oll, w or golng to ocus on
olgorlthms ond thlr olllotd progrommlng tchnlqus. 5ur, th rsults wlll oll b vlsuol ln
notur [monlstd os onlmotd Procsslng sktchsj, but thy wlll xlst mor os
dmonstrotlons o th olgorlthms ond progrommlng tchnlqus thmslvs, drown only wlth
slmpl shops ond groyscol. |t ls my hop, howvr, thot dslgnrs ond ortlsts con
lncorporot oll o th motrlol hr lnto thlr proctlc to mok nw, ngoglng work.
Proc
lx
|n th nd, l thls book ls onythlng, lt ls rolly just o good old-oshlond progrommlng book.
Whll o sclntllc toplc moy sd o choptr [Nwtonlon physlcs, cllulor growth, volutlonj or
th rsults mlght lnsplr on ortlstlc projct, th contnt ltsl wlll olwoys boll down to th cod
lmplmntotlon, wlth o portlculor ocus on objct-orlntd progrommlng.
5"0 ! 8*.9 4)*:' 5.*2(--&;< 5"0 ! 8*.9 4)*:' 5.*2(--&;<
| om uslng Procsslng ln thls book or o numbr o rosons. |or on, lt`s th longuog ond
nvlronmnt wlth whlch | om most comortobl, ond lt`s whot | njoy uslng or my prsonol
work. 1wo, lt`s r, opn-sourc, ond wll sultd to bglnnrs. 1hr ls on octlv, nrgtlc
communlty o popl who progrom wlth Procsslng, or mony, lt`s th lrst progrommlng
longuog thy`v lornd. |n thls sns, | hop thot | con roch o wld oudlnc ond
dmonstrot th concpts ln o rlndly monnr by uslng Procsslng.
All thot sold, thr ls nothlng thot tls whot w or dolng ln thls book strlctly to Procsslng.
1hls book could hov bn wrlttn uslng Actlon5crlpt, Jovo5crlpt, Jovo [wlthout Procsslngj,
or ony numbr o othr opn-sourc crotlv codlng" nvlronmnts llk opn|romworks,
Clndr, or th nwly rlosd pocod. |t ls my hop thot otr |`v compltd thls book, |`ll b
obl to rlos vrslons o th xompls thot run ln othr nvlronmnts. | onyon ls
lntrstd ln hlplng to port th xompls, plos l r to contoct m
[donllyshlmon.ntj.
All o th xompls ln thls book hov bn tstd wlth Procsslng 2.0b6, but or th most
port, thy should olso work wlth orllr vrslons o Procsslng. |`ll b kplng thm up-to-dot
wlth whotvr th lotst vrslon ls. 1h most rcnt cod con olwoys b ound on GltHub
[http.//glthub.com/shlmon/1h-Notur-o-Cod-Lxomplsj.
5"= 6,4' 9* /*: ;((9 '* 3;*87 5"= 6,4' 9* /*: ;((9 '* 3;*87
1h prrqulslt or undrstondlng th motrlol ln thls book could b stotd os. on smstr
o progrommlng lnstructlon wlth Procsslng [lncludlng omlllorlty wlth objct-orlntd
progrommlngj." 1hot sold, thr`s no roson why you couldn`t rod thls book hovlng lornd
progrommlng uslng o dlrnt longuog or dvlopmnt nvlronmnt. 1h ky hr ls thot
you hov xprlnc wlth progrommlng.
| you`v nvr wrlttn ony cod bor, you or golng to struggl, bcous thls book
ossums knowldg o oll th boslcs. | would suggst plcklng up on lntroductory book on
Procsslng, o numbr o whlch or llstd on th Procsslng wbslt [http.//procsslng.org/
lornlng/books/j.
| you or on xprlncd progrommr, but hovn`t workd wlth Procsslng, you con probobly
plck lt up by downloodlng Procsslng [http.//procsslng.org/downlood/j, poklng through th
1h Notur o Cod [v005j
x
xompls, ond rodlng through th Gttlng 5tortd [http.//procsslng.org/lornlng/
gttlngstortd/j pog.
| should olso polnt out thot xprlnc wlth objct-orlntd progrommlng ls cruclol. W`ll
rvlw som o th boslcs ln th book`s lntroductlon, but | would suggst rodlng th
Procsslng tutorlol on objcts [http.//procsslng.org/lornlng/objctsj lrst.
5"> 6,4' 4.( /*: :-&;< '* .(49 ',&- )**37 5"> 6,4' 4.( /*: :-&;< '* .(49 ',&- )**37
Ar you rodlng thls book on o Klndl? Prlntd popr? On your loptop ln PL| orm? On o
toblt showlng on onlmotd H1ML5 vrslon? Ar you stroppd to o cholr, obsorblng th
contnt dlrctly lnto your broln vlo o srls o lctrods, tubs, ond cortrldgs?
1h book you or rodlng rlght now wos gnrotd wlth th Moglc Book projct
[http.//www.moglcbookprojct.comj. 1h Moglc Book ls on opn-sourc romwork or sl-
publlshlng dvlopd ot |1P [http.//ltp.nyu.duj. 1h ldo hr ls thot you only nd to wrlt
th book onc os o slmpl txt ll. Onc you`v wrlttn your contnt, you prss o moglc
button, ond out coms your book ln o vorlty o ormotsPL|, H1ML5, prlntd hordcopy,
Klndl, tc. Lvrythlng ls dslgnd ond styld uslng C55. As o th lrst rlos, th only
vrslons ovollobl wlll b dlgltol PL|, prlntd hordcopy, ond H1ML5 [whlch wlll lnclud
onlmotd vrslons o th xompls uslng Procsslng.jsj. Hopully ovr th cours o th
nxt yor, th book wlll b ovollobl ln oddltlonol ormots. | you`d llk to hlp wlth thls,
plos contoct m [donllyshlmon.ntj.
5"? @,( A-'*./B *+ ',&- )**3 5"? @,( A-'*./B *+ ',&- )**3
| you glonc ovr th book`s tobl o contnts, you`ll notlc thr or tn choptrs, och
on covrlng o dlrnt toplc. And ln on sns, thls book ls just thoto survy o tn
concpts ond ossoclotd cod xompls. Nvrthlss, ln puttlng togthr th motrlol, |
hod olwoys lmoglnd somthlng o o llnor norrotlv. Bor you bgln rodlng th
choptrs, |`d llk to wolk you through thls story. | thlnk lt`s lmportont to lrst hov o sns o
th ovroll journy.
Proc
xl
54.' CD C;4;&E4'( F)G(2'-" 54.' CD C;4;&E4'( F)G(2'-"
A soccr boll lls ln th gross. A klck lounchs lt lnto th olr. Grovlty pulls lt bock down. A
hovy gust o wlnd kps lt oloot o momnt longr untll lt olls ond bouncs o th hod o o
jumplng ployr. 1h soccr boll ls not ollv, lt moks no cholcs os to how lt wlll mov
throughout th world. Rothr, lt ls on lnonlmot objct woltlng to b pushd ond pulld by th
orcs o lts nvlronmnt.
How would w modl o soccr boll movlng ln Procsslng? | you`v vr progrommd o clrcl
movlng ocross o wlndow, thn you`v probobly wrlttn th ollowlng lln o cod.
You drow som shop ot locotlon !. Wlth och rom o onlmotlon, you lncrmnt th volu o
!, rdrow th shop ond volloth llluslon o motlon! Moyb you took lt o stp or two urthr,
ond lncludd o " locotlon, os wll os vorlobls or spd olong th x ond y oxs.
Port | o thls story wlll tok us on stp urthr. W`r golng to tok ths vorlobls !#$%%&
ond "#$%%& ond lorn how togthr thy orm o vctor [,"&:'#) ; ,"&:'#) ;j, th bulldlng block o
motlon. W won`t gt ony nw unctlonollty out o thls, but lt wlll bulld o solld oundotlon or
th rst o th book.
Onc w know o llttl somthlng obout vctors, w`r golng to qulckly rollz thot o orc
[,"&:'#) < ,"&:'#) <j ls o vctor. Klck o soccr boll ond you or opplylng o orc. Whot dos o orc
cous on objct to do? Accordlng to |sooc Nwton, orc quols moss tlms occlrotlon. 1hot
orc couss on objct to occlrot. Modllng orcs wlll ollow us to crot systms wlth
dynomlc motlon whr objcts mov occordlng to o vorlty o ruls.
Now, thot soccr boll to whlch you opplld o orc mlght hov olso bn splnnlng. | on objct
movs occordlng to lts occlrotlon, lt con spln occordlng to lts ongulor occlrotlon [,"&:'#) ,"&:'#)
==j. ndrstondlng th boslcs o ongls ond trlgonomtry wlll ollow us to modl rototlng
objcts os wll os grosp th prlnclpls bhlnd osclllotlng motlon, llk o pndulum swlnglng or
o sprlng bounclng.
Onc w`v tockld th boslcs o motlon ond orcs or on lndlvlduol lnonlmot objct, w`ll
lorn how to mok thousonds upon thousonds o thos objcts ond monog thm ln o slngl
systm colld o portlcl systm [,"&:'#) > ,"&:'#) >j. Portlcl systms wlll ollow us to look ot som
odvoncd oturs o objct-orlntd progrommlng, nomly lnhrltonc ond polymorphlsm.
|n Choptrs J through 4, oll o th xompls wlll b wrlttn rom scrotch"monlng th cod
or th olgorlthms drlvlng th motlon o th objcts wlll b wrlttn dlrctly ln Procsslng. W`r
crtolnly not th lrst progrommrs vr to consldr th ldo o slmulotlng physlcs ln
onlmotlon, so nxt w`ll xomln how physlcs llbrorls [,"&:'#) ? ,"&:'#) ?j con b usd to modl mor
! ' ! ( )*
! ' ! ( !#$%%&*
" ' " ( "#$%%&*
1h Notur o Cod [v005j
xll
odvoncd ond sophlstlcotd bhovlors. W`ll look ot Box2L [http.//www.box2d.orgj ond
toxlcllbs' Vrlt Physlcs pockog [http.//toxlcllbs.org/j.
54.' CCD C'H- 4%&I(J 54.' CCD C'H- 4%&I(J
Whot dos lt mon to modl ll? Not on osy qustlon to onswr, but w con bgln by
bulldlng objcts thot hov on oblllty to prclv thlr nvlronmnt. Lt`s thlnk obout thls or
o momnt. A block thot olls o o tobl movs occordlng to orcs, os dos o dolphln
swlmmlng through th wotr. But thr ls o ky dlrnc. 1h block connot dcld to lop
o thot tobl. 1h dolphln con dcld to lop out o th wotr. 1h dolphln con hov droms
ond dslrs. |t con l hungr or or, ond thos llngs con lnorm lts movmnts. By
xomlnlng tchnlqus bhlnd modllng outonomous ognts [,"&:'#) @ ,"&:'#) @j, w wlll broth ll
lnto our lnonlmot objcts, ollowlng thm to mok dclslons obout thlr movmnts
occordlng to thlr undrstondlng o thlr nvlronmnt.
1hrough comblnlng th concpt o outonomous ognts wlth whot w lornd obout
modllng systms ln Choptr 4, w`ll look ot modls o group bhovlor thot xhlblt th
proprtls o complxlty. A complx systm ls typlcolly dlnd os o systm thot ls mor
thon th sum o lts ports." Whll th lndlvlduol lmnts o th systm moy b lncrdlbly
slmpl ond oslly undrstood, th bhovlor o th systm os o whol con b hlghly complx,
lntlllgnt, ond dllcult to prdlct. 1hls wlll lod us owoy rom thlnklng purly obout
modllng motlon ond lnto th rolm o rul-bosd systms. Whot con w modl wlth cllulor
outomoto [,"&:'#) A ,"&:'#) Aj, o systm o clls llvlng on o grld? Whot typs o pottrns con w
gnrot wlth roctols [,"&:'#) B ,"&:'#) Bj, th gomtry o notur?
54.' CCCD C;'(%%&<(;2( 54.' CCCD C;'(%%&<(;2(
W mod thlngs mov. 1hn w gov thos thlngs hops ond droms ond ors, olong wlth
ruls to llv by. 1h lost stp ln thls book wlll b to mok our crotlons vn smortr. Con
w opply th blologlcol procss o volutlon to computotlonol systms [,"&:'#) C ,"&:'#) Cj ln ordr
to volv our objcts? 1oklng lnsplrotlon rom th humon broln, con w progrom on ortllclol
nurol ntwork [,"&:'#) ;D ,"&:'#) ;Dj thot con lorn rom lts mlstoks ond ollow our objcts to odopt
to thlr nvlronmnt?
Wk J Wk J |ntroductlon ond Vctors [Choptr Jj
Wk 2 Wk 2 |orcs [Choptr 2j
5"K @,&- )**3 4- 4 -/%%4):- 5"K @,&- )**3 4- 4 -/%%4):-
Whll th contnt ln thls book crtolnly moks or on lntns ond hlghly comprssd
smstr, | hov dslgnd lt to lt lnto o ourtn-wk cours. Nvrthlss, lt`s worth
mntlonlng thot | lnd thot th book choptrs somtlms work bttr xpondd ocross
multlpl wks. |or xompl, th syllobus or my cours gnrolly works out os ollows.
Proc
xlll
Wk 3 Wk 3 Osclllotlons [Choptr 3j
Wk 4 Wk 4 Portlcl 5ystms [Choptr 4j
Wk 5 Wk 5 Physlcs Llbrorls Port | [Choptr 5j
Wk 6 Wk 6 Physlcs Llbrorls Port || & 5trlng [Choptrs 5-6j
Wk 7 Wk 7 Prsnt mldtrm projcts obout motlon
Wk 8 Wk 8 Complx 5ystms. |locklng ond JL Cllulor Automoto [Choptrs 6-7j
Wk 9 Wk 9 Complx 5ystms. 2L Cllulor Automoto ond |roctols [Choptrs 7-8j
Wk J0 Wk J0 Gntlc Algorlthms [Choptr 9j
Wk JJ Wk JJ Nurol Ntworks [Choptr J0j
Wks J2-J3 Wks J2-J3 |lnol projct workshop
Wk J4 Wk J4 |lnol projct prsntotlon
| you or consldrlng uslng thls txt or o cours or workshop, plos l r to contoct m.
| hop to vntuolly rlos o componlon st o vldos ond slld prsntotlons os
supplmntory ducotlonol motrlols.
5"L @,( M2*-/-'(E 5.*G(2' 5"L @,( M2*-/-'(E 5.*G(2'
As much os |`d llk to prtnd you could lorn vrythlng by curllng up ln o comy cholr ond
rodlng som pros obout progrommlng, to lorn progrommlng, you`r rolly golng to hov to
do som progrommlng. You mlght lnd lt hlpul to kp ln mlnd o projct ldo [or twoj to
dvlop os o st o xrclss whll golng rom choptr to choptr. |n oct, whn tochlng th
Notur o Cod cours ot |1P, | hov otn ound thot studnts njoy bulldlng o slngl projct,
stp by stp, wk by wk, ovr th cours o o smstr.
At th nd o och choptr, you`ll lnd o srls o xrclss or on such projctxrclss
thot bulld on och othr, on toplc ot o tlm. Consldr th ollowlng scnorlo. You`v bn
oskd by o sclnc musum to dvlop th sotwor or o nw xhlblt1h Llgltol Lcosystm,
o world o onlmotd, procdurol croturs thot llv on o projctlon scrn or vlsltors to njoy
os thy ntr th musum. | don`t mon to suggst thot thls ls o portlculorly lnnovotlv or
crotlv concpt. Rothr, w`ll us thls xompl projct ldo os o lltrol rprsntotlon o th
contnt ln th book, dmonstrotlng how th lmnts lt togthr ln o slngl sotwor projct.
| ncourog you to dvlop your own ldo, on thot ls mor obstroct ond crotlv ln lts
thlnklng.
5"N 6,(.( 9* C +&;9 ',( 2*9( *;%&;( 4;9 -:)E&' 5"N 6,(.( 9* C +&;9 ',( 2*9( *;%&;( 4;9 -:)E&'
+((9)4237 +((9)4237
|or oll thlngs book-rlotd, plos vlslt th Notur o Cod wbslt
[http.//www.noturocod.comj. 1h row sourc txt o th book ond oll o th lllustrotlons or
1h Notur o Cod [v005j
xlv
on GltHub [http.//glthub.com/shlmon/1h-Notur-o-Codj. Plos lov dbock ond
submlt corrctlons uslng GltHub lssus.
1h sourc cod or oll o th xompls [ond xrclssj ls olso ovollobl on GltHub
[http.//glthub.com/shlmon/1h-Notur-o-Cod-Lxomplsj. 1h choptrs thmslvs
lnclud cod snlppts ln-lln wlth th txt. Howvr, | wont to mntlon thot ln mony coss, |
hov shortnd or slmpllld th cod snlppts ln ordr to lllustrot o spcllc polnt. |n oll
coss, th ull cod wlth commnts con b ound vlo GltHub.
| you hov qustlons obout th cod ltsl, | would suggst postlng thm on th Procsslng
orum [http.//orum.procsslng.orgj.
Proc
xv
!&E5# *+ ,*1'#1'8 !&E5# *+ ,*1'#1'8
!23;*8%(9<E(;'-
A.J A llttl blt o hlstory
A.2 Klckstortr
5.(+42(
P.J Whot ls thls book?
P.2 A word obout Procsslng
P.3 Whot do you nd to know?
P.4 Whot or you uslng to rod thls book?
P.5 1h story" o thls book
P.6 1hls book os o syllobus
P.7 1h Lcosystm Projct
P.8 Whr do | lnd th cod onlln ond submlt dbock?
C;'.*9:2'&*;
|.J Rondom Wolks
|.2 1h Rondom Wolkr Closs
|.3 Proboblllty ond Non-nlorm Llstrlbutlons
&I
v
vll
&O
lx
x
x
xl
xl
xlll
xlv
xlv
#
J
2
7
1h Notur o Cod [v005j
xvl
|.4 A Normol Llstrlbutlon o Rondom Numbrs
|.5 A Custom Llstrlbutlon o Rondom Numbrs
|.6 Prlln Nols [A 5moothr Approochj
|.7 Onword
P,4Q'(. #" R(2'*.-
J.J Vctors, You Complt M
J.2 Vctors or Procsslng Progrommrs
J.3 Vctor Addltlon
J.4 Mor Vctor Moth
J.5 Vctor Mognltud
J.6 Normollzlng Vctors
J.7 Vctor Motlon. Vloclty
J.8 Vctor Motlon. Acclrotlon
J.9 5totlc vs. Non-5totlc |unctlons
J.J0 |ntroctlvlty wlth Acclrotlon
P,4Q'(. 0" S*.2(-
2.J |orcs ond Nwton`s Lows o Motlon
2.2 |orcs ond ProcsslngNwton`s 5cond Low os o |unctlon
2.3 |orc Accumulotlon
2.4 Lollng wlth Moss
2.5 Crotlng |orcs
2.6 Grovlty on Lorth ond Modllng o |orc
2.7 |rlctlon
2.8 Alr ond |luld Rslstonc
2.9 Grovltotlonol Attroctlon
2.J0 Lvrythlng Attrocts [or Rplsj Lvrythlng
P,4Q'(. =" F-2&%%4'&*;
JJ
J4
J7
26
0L
28
30
33
37
42
43
45
49
54
57
K=
63
67
68
70
73
77
80
83
88
97
#T#
1obl o Contnts
xvll
3.J Angls
3.2 Angulor Motlon
3.3 1rlgonomtry
3.4 Polntlng ln th Llrctlon o Movmnt
3.5 Polor vs. Cortslon Coordlnots
3.6 Osclllotlon Amplltud ond Prlod
3.7 Osclllotlon wlth Angulor Vloclty
3.8 Wovs
3.9 1rlgonomtry ond |orcs. 1h Pndulum
3.J0 5prlng |orcs
P,4Q'(. >" 54.'&2%( U/-'(E-
4.J Why W Nd Portlcl 5ystms
4.2 A 5lngl Portlcl
4.3 1h ArroyLlst
4.4 1h Portlcl 5ystm Closs
4.5 A 5ystm o 5ystms
4.6 |nhrltonc ond Polymorphlsm. An |ntroductlon
4.7 |nhrltonc Boslcs
4.8 Portlcls wlth |nhrltonc
4.9 Polymorphlsm Boslcs
4.J0 Portlcl 5ystms wlth Polymorphlsm
4.JJ Portlcl 5ystms wlth |orcs
4.J2 Portlcl 5ystms wlth Rpllrs
4.J3 |mog 1xturs ond Addltlv Blndlng
P,4Q'(. ?" 5,/-&2- V&).4.&(-
5.J Whot |s Box2L ond Whn |s |t sul?
5.2 Gttlng Box2L ln Procsslng
5.3 Box2L Boslcs
J0J
J04
J08
J09
JJ2
JJ6
JJ9
J22
J27
J34
#>=
J44
J45
J49
J55
J57
J60
J62
J66
J68
J70
J73
J78
J83
#NW
J90
J92
J92
1h Notur o Cod [v005j
xvlll
5.4 Llvlng ln o Box2L World
5.5 Bulldlng o Box2L body
5.6 1hr`s Compony. Bodls ond 5hops ond |lxturs
5.7 Box2L ond Procsslng. Runltd ond |t |ls 5o Good
5.8 |lxd Box2L Objcts
5.9 A Curvy Boundory
5.J0 Complx |orms
5.JJ |llng AttochdBox2L Jolnts
5.J2 Brlnglng |t All Bock Hom to |orcs
5.J3 Colllslon Lvnts
5.J4 A Brl |ntrlud|ntgrotlon Mthods
5.J5 Vrlt Physlcs wlth toxlcllbs
5.J6 Portlcls ond 5prlngs ln toxlcllbs
5.J7 Puttlng |t All 1ogthr. A 5lmpl |ntroctlv 5prlng
5.J8 Connctd 5ystms Port |. 5trlng
5.J9 Connctd 5ystms Port ||. |orc-Llrctd Groph
5.20 Attroctlon ond Rpulslon Bhovlors
P,4Q'(. K" !:'*;*E*:- !<(;'-
6.J |orcs rom Wlthln
6.2 Vhlcls ond 5trlng
6.3 1h 5trlng |orc
6.4 Arrlvlng Bhovlor
6.5 Your Own Lslrs. Lslrd Vloclty
6.6 |low |llds
6.7 1h Lot Product
6.8 Poth |ollowlng
6.9 Poth |ollowlng wlth Multlpl 5gmnts
6.J0 Complx 5ystms
6.JJ Group Bhovlors [or. Lt`s not run lnto och othrj
J96
J98
200
203
209
2JJ
2J5
222
232
234
238
24J
244
247
249
253
256
0KT
260
262
263
270
274
276
282
286
294
298
300
1obl o Contnts
xlx
6.J2 Comblnotlons
6.J3 |locklng
6.J4 Algorlthmlc Llclncy [or. Why dos my $y['! run so slowly?j
6.J5 A |w Lost Nots. Optlmlzotlon 1rlcks
P,4Q'(. L" P(%%:%4. !:'*E4'4
7.J Whot |s o Cllulor Automoton?
7.2 Llmntory Cllulor Automoto
7.3 How to Progrom on Llmntory CA
7.4 Lrowlng on Llmntory CA
7.5 Wolrom Clossllcotlon
7.6 1h Gom o Ll
7.7 Progrommlng th Gom o Ll
7.8 Objct-Orlntd Clls
7.9 Vorlotlons o 1rodltlonol CA
P,4Q'(. N" S.42'4%-
8.J Whot |s o |roctol?
8.2 Rcurslon
8.3 1h Contor 5t wlth o Rcurslv |unctlon
8.4 1h Koch Curv ond th ArroyLlst 1chnlqu
8.5 1rs
8.6 L-systms
P,4Q'(. W" @,( MI*%:'&*; *+ P*9(
9.J Gntlc Algorlthms. |nsplrd by Actuol Lvnts
9.2 Why s Gntlc Algorlthms?
9.3 Lorwlnlon Noturol 5lctlon
9.4 1h Gntlc Algorlthm, Port |. Crotlng o Populotlon
306
308
3J5
3J7
=0=
324
325
330
336
340
342
345
349
35J
=??
356
358
363
366
374
382
=WT
39J
392
394
395
1h Notur o Cod [v005j
xx
9.5 1h Gntlc Algorlthm, Port ||. 5lctlon
9.6 1h Gntlc Algorlthm, Port |||. Rproductlon
9.7 Cod or Crotlng th Populotlon
9.8 Gntlc Algorlthms. Puttlng |t All 1ogthr
9.9 Gntlc Algorlthms. Mok 1hm Your Own
9.J0 Lvolvlng |orcs. 5mort Rockts
9.JJ 5mort Rockts. Puttlng |t All 1ogthr
9.J2 |ntroctlv 5lctlon
9.J3 Lcosystm 5lmulotlon
P,4Q'(. #T" X(:.4% X('8*.3-
J0.J Artllclol Nurol Ntworks. |ntroductlon ond Appllcotlon
J0.2 1h Prcptron
J0.3 5lmpl Pottrn Rcognltlon slng o Prcptron
J0.4 Codlng th Prcptron
J0.5 A 5trlng Prcptron
J0.6 |t`s o Ntwork," Rmmbr?
J0.7 Nurol Ntwork Llogrom
J0.8 Anlmotlng |d |orword
S:.',(. Y(49&;<
Books
Poprs ond Artlcls
C;9(O
397
399
402
409
4J3
420
425
43J
435
>>>
445
448
450
452
460
466
468
473
>N#
48J
482
>N>
1obl o Contnts
xxl
F1')*-(0'/*1 F1')*-(0'/*1
I cm tuo uith ncture.
! =001+ >??&,
Hr w or. th bglnnlng. Wll, olmost th bglnnlng. | lt`s bn o whll slnc you`v don
ony progrommlng ln Procsslng [or ony moth, or thot mottrj, thls lntroductlon wlll gt your
mlnd bock lnto computotlonol thlnklng bor w opprooch som o th mor dllcult ond
complx motrlol.
|n Choptr J, w`r golng to tolk obout th concpt o o vctor ond how lt wlll srv os th
bulldlng block or slmulotlng motlon throughout thls book. But bor w tok thot stp, lt`s
thlnk obout whot lt mons or somthlng to slmply mov oround th scrn. Lt`s bgln wlth
on o th bst-known ond slmplst slmulotlons o motlonth rondom wolk.
C"# Y4;9*E 64%3- C"# Y4;9*E 64%3-
|mogln you or stondlng ln th mlddl o o bolonc bom. Lvry tn sconds, you llp o coln.
Hods, tok o stp orword. 1olls, tok o stp bockword. 1hls ls o rondom wolko poth dlnd
os o srls o rondom stps. 5tpplng o thot bolonc bom ond onto th loor, you could
prorm o rondom wolk ln two dlmnslons by llpplng thot som coln twlc wlth th ollowlng
rsults.
1h Notur o Cod [v005j
J
G5/: ; G5/: ; G5/: < G5/: < H#8(5' H#8(5'
Hods Hods 5tp orword.
Hods 1olls 5tp rlght.
1olls Hods 5tp lt.
1olls 1olls 5tp bockword.
Ys, thls moy sm llk o portlculorly unsophlstlcotd olgorlthm. Nvrthlss, rondom
wolks con b usd to modl phnomno thot occur ln th rol world, rom th movmnts o
molculs ln o gos to th bhovlor o o gomblr spndlng o doy ot th coslno. As or us, w
bgln thls book studylng o rondom wolk wlth thr gools ln mlnd.
J. W nd to rvlw o progrommlng concpt cntrol to thls bookobjct-orlntd
progrommlng. 1h rondom wolkr wlll srv os o tmplot or how w wlll us
objct-orlntd dslgn to mok thlngs thot mov oround o Procsslng wlndow.
2. 1h rondom wolk lnstlgots th two qustlons thot w wlll osk ovr ond ovr ogoln
throughout thls book. How do w dln th ruls thot govrn th bhovlor o our
objcts?" ond thn, How do w lmplmnt ths ruls ln Procsslng?"
3. 1hroughout th book, w`ll prlodlcolly nd o boslc undrstondlng o
rondomnss, proboblllty, ond Prlln nols. 1h rondom wolk wlll ollow us to
dmonstrot o w ky polnts thot wlll com ln hondy lotr.
C"0 @,( Y4;9*E 64%3(. P%4-- C"0 @,( Y4;9*E 64%3(. P%4--
Lt`s rvlw o blt o objct-orlntd progrommlng [OOPj lrst by bulldlng o +,-.%/ objct.
1hls wlll b only o cursory rvlw. | you hov nvr workd wlth OOP bor, you moy wont
somthlng mor comprhnslv, |`d suggst stopplng hr ond rvlwlng th boslcs on th
Procsslng wbslt [http.//procsslng.org/lornlng/objcts/j bor contlnulng.
An !"#$%& !"#$%& ln Procsslng ls on ntlty thot hos both doto ond unctlonollty. W or looklng to
dslgn o +,-.%/ objct thot both kps trock o lts doto [whr lt xlsts on th scrnj ond
hos th copoblllty to prorm crtoln octlons [such os drow ltsl or tok o stpj.
A %'()) %'()) ls th tmplot or bulldlng octuol lnstoncs o objcts. 1hlnk o o closs os th
cookl cuttr, th objcts or th cookls thmslvs.
Lt`s bgln by dlnlng th +,-.%/ closswhot lt mons to b o +,-.%/ objct. 1h +,-.%/
only nds two plcs o dotoo numbr or lts x-locotlon ond on or lts y-locotlon.
0-,## +,-.%/ 1
|ntroductlon
2
Lvry closs must hov o constructor, o spclol unctlon thot ls colld whn th objct ls lrst
crotd. You con thlnk o lt os th objct`s #%23$45. 1hr, w`ll lnltlollz th +,-.%/`s stortlng
locotlon [ln thls cos, th cntr o th wlndowj.
|lnolly, ln oddltlon to doto, closss con b dlnd wlth unctlonollty. |n thls xompl, o +,-.%/
hos two unctlons. W lrst wrlt o unctlon thot ollows th objct to dlsploy ltsl [os o whlt
dotj.
1h scond unctlon dlrcts th +,-.%/ objct to tok o stp. Now, thls ls whr thlngs gt o
blt mor lntrstlng. Rmmbr thot loor on whlch w wr toklng rondom stps? Wll, now
w con us o Procsslng wlndow ln thot som copoclty. 1hr or our posslbl stps. A stp
to th rlght con b slmulotd by lncrmntlng ! [!j, to th lt by dcrmntlng ! [!66j,
orword by golng down o plxl ["((j, ond bockword by golng up o plxl ["66j. How do w plck
rom ths our cholcs? Lorllr w stotd thot w could llp two colns. |n Procsslng,
howvr, whn w wont to rondomly choos rom o llst o optlons, w con plck o rondom
numbr uslng /,7&8945.
1h obov lln o cod plcks o rondom lootlng polnt numbr btwn 0 ond 4 ond convrts lt
to on lntgr, wlth o rsult o 0, J, 2, or 3. 1chnlcolly spoklng, th hlghst numbr wlll nvr
b 4.0, but rothr 3.999999999 [wlth os mony 9s os thr or dclmol plocsj, slnc th
procss o convrtlng to on lntgr lops o th dclmol ploc, th hlghst :72 w con gt ls 3.
Nxt, w tok th opproprlot stp [lt, rlght, up, or downj dpndlng on whlch rondom
numbr wos plckd.
Objects have data. :72 !*
:72 "*
Objects have a constructor where they are
initialized.
+,-.%/45 1
! ' ;:&2<=>*
" ' <%:?<2=>*
@
Objects have functions. A8:& &:#$-,"45 1
#2/8.%4B5*
$8:724!C"5*
@
A8:& #2%$45 1
0, 1, 2, or 3 :72 0<8:0% ' :724/,7&894D55*
1h Notur o Cod [v005j
3
Now thot w`v wrlttn th closs, lt`s tlm to mok on octuol +,-.%/ objct ln th moln port
o our sktch#%23$45 ond &/,;45. Assumlng w or looklng to modl o slngl rondom
wolk, w dclor on globol vorlobl o typ +,-.%/.
1hn w crot th objct ln #%23$45 by colllng th constructor wlth th 7%; oprotor.
IJ&7:5# FK;L !)&-/'/*1&5 )&1-*7 4&53
loch t|me you see the obove lxomp|e heod|ng |n th|s boo|, |t meons thete |s o
cottespond|ng code exomp|e ovo||ob|e on G|tHub (http.//g|thub.com/sh|ttmon/7he-Notute-
ot-Code-lxomp|esI.
|lnolly, durlng och cycl through &/,;45, w osk th +,-.%/ to tok o stp ond drow o dot.
5lnc w only drow th bockground onc ln #%23$45, rothr thon clorlng lt contlnuolly
och tlm through &/,;45, w s th troll o th rondom wolk ln our Procsslng wlndow.
The random "choice determines our step. :E 40<8:0% '' B5 1
!((*
@ %-#% :E 40<8:0% '' )5 1
!66*
@ %-#% :E 40<8:0% '' >5 1
"((*
@ %-#% 1
"66*
@
@
@
A Walker object +,-.%/ ;*
A8:& #%23$45 1
#:F%4GDBCHGB5*
Create the Walker. ! " #$! %&'($)*+,
I,0.?/837&4>JJ5*
@
A8:& &/,;45 1
Call functions on the Walker. !-./$0*+,
!-12.0'&3*+,
@
|ntroductlon
4
1hr or o coupl lmprovmnts w could mok to th rondom wolkr. |or on, thls
+,-.%/`s stp cholcs or llmltd to our optlonsup, down, lt, ond rlght. But ony glvn plxl
ln th wlndow hos lght posslbl nlghbors, ond o nlnth posslblllty ls to stoy ln th som
ploc.
1o lmplmnt o +,-.%/ objct thot con stp to ony nlghborlng plxl [or stoy putj, w could
plck o numbr btwn 0 ond 8 [nln posslbl cholcsj. Howvr, o mor lclnt woy to
wrlt th cod would b to slmply plck rom thr posslbl stps olong th x-oxls [-J, 0, or Jj
ond thr posslbl stps olong th y-oxls.
1oklng thls urthr, w could us lootlng polnt numbrs [l.. dclmol numbrsj or ! ond "
lnstod ond mov occordlng to on orbltrory rondom volu btwn -J ond J.
Iiure I.:
A8:& #2%$45 1
Yields -1, 0, or 1 :72 #2%$! ' :724/,7&894H556)*
:72 #2%$" ' :724/,7&894H556)*
! (' #2%$!*
" (' #2%$"*
@
A8:& #2%$45 1
Yields any floating point number between
-1.0 and 1.0
E-8,2 #2%$! ' /,7&8946)C )5*
E-8,2 #2%$" ' /,7&8946)C )5*
1h Notur o Cod [v005j
5
All o ths vorlotlons on th trodltlonol" rondom wolk hov on thlng ln common. ot ony
momnt ln tlm, th proboblllty thot th +,-.%/ wlll tok o stp ln o glvn dlrctlon ls quol
to th proboblllty thot th +,-.%/ wlll tok o stp ln ony dlrctlon. |n othr words, l thr
or our posslbl stps, thr ls o J ln 4 [or 25j chonc th +,-.%/ wlll tok ony glvn stp.
Wlth nln posslbl stps, lt`s o J ln 9 [or JJ.Jj chonc.
Convnlntly, thls ls how th /,7&8945 unctlon works. Procsslng`s rondom numbr
gnrotor [whlch oprots bhlnd th scnsj producs whot ls known os o unlorm"
dlstrlbutlon o numbrs. W con tst thls dlstrlbutlon wlth o Procsslng sktch thot counts
och tlm o rondom numbr ls plckd ond grophs lt os th hlght o o rctongl.
IJ&7:5# FK<L H&1-*7 1(7E#) -/8')/E('/*1
! (' #2%$!*
" (' #2%$"*
@
An array to keep track of how often random
numbers are picked
:72KL /,7&89M8372#*
A8:& #%23$45 1
#:F%4GDBC>DB5*
/,7&89M8372# ' 7%; :72K>BL*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
Pick a random number and increase the
count.
:72 :7&%! ' :724/,7&894/,7&89M8372#N-%7?2<55*
/,7&89M8372#K:7&%!L((*
#2/8.%4B5*
E:--4)OJ5*
:72 ; ' ;:&2<=/,7&89M8372#N-%7?2<*
|ntroductlon
6
1h obov scrnshot shows th rsult o th sktch runnlng or o w mlnuts. Notlc how
och bor o th groph dlrs ln hlght. Our sompl slz [l.. th numbr o rondom numbrs
w`v plckdj ls rothr smoll ond thr or som occoslonol dlscrponcls, whr crtoln
numbrs or plckd mor otn. Ovr tlm, wlth o good rondom numbr gnrotor, thls would
vn out.
5-(:9*ZY4;9*E X:E)(.- 5-(:9*ZY4;9*E X:E)(.-
1h rondom numbrs w gt rom th /,7&8945 unctlon or not truly rondom,
thror thy or known os psudo-rondom." 1hy or th rsult o o mothmotlcol
unctlon thot slmulots rondomnss. 1hls unctlon would ylld o pottrn ovr tlm, but
thot tlm prlod ls so long thot or us, lt`s just os good os pur rondomnss!
Graphing the results E8/ 4:72 ! ' B* ! P /,7&89M8372#N-%7?2<* !((5 1
/%024!Q;C<%:?<26/,7&89M8372#K!LC;6)C/,7&89M8372#K!L5*
@
@
Crot o rondom wolkr thot hos o tndncy to mov down ond to th rlght. [W`ll s
th solutlon to thls ln th nxt sctlon.j
MO(.2&-( C"# MO(.2&-( C"#
C"= 5.*)4)&%&'/ 4;9 X*;Z[;&+*.E \&-'.&):'&*;- C"= 5.*)4)&%&'/ 4;9 X*;Z[;&+*.E \&-'.&):'&*;-
Rmmbr whn you lrst stortd progrommlng ln Procsslng? Prhops you wontd to drow o
lot o clrcls on th scrn. 5o you sold to yoursl. Oh, | know. |`ll drow oll ths clrcls ot
rondom locotlons, wlth rondom slzs ond rondom colors." |n o computr grophlcs systm, lt`s
otn oslst to sd o systm wlth rondomnss. |n thls book, howvr, w`r looklng to bulld
systms modld on whot w s ln notur. Loultlng to rondomnss ls not o portlculorly
thoughtul solutlon to o dslgn problmln portlculor, th klnd o problm thot lnvolvs
crotlng on orgonlc or noturol-looklng slmulotlon.
Wlth o w trlcks, w con chong th woy w us /,7&8945 to produc non-unlorm"
dlstrlbutlons o rondom numbrs. 1hls wlll com ln hondy throughout th book os w look ot o
numbr o dlrnt scnorlos. Whn w xomln gntlc olgorlthms, or xompl, w`ll nd o
mthodology or prormlng slctlon"whlch mmbrs o our populotlon should b
slctd to poss thlr LNA to th nxt gnrotlon? Rmmbr th concpt o survlvol o th
lttst? Lt`s soy w hov o populotlon o monkys volvlng. Not vry monky wlll hov o
1h Notur o Cod [v005j
7
quol chonc o rproduclng. 1o slmulot Lorwlnlon volutlon, w con`t slmply plck two
rondom monkys to b pornts. W nd th mor lt" ons to b mor llkly to b chosn.
W nd to dln th proboblllty o th lttst." |or xompl, o portlculorly ost ond strong
monky mlght hov o 90 chonc o procrotlng, whll o wokr on hos only o J0
chonc.
Lt`s pous hr ond tok o look ot proboblllty`s boslc prlnclpls. |lrst w`ll xomln slngl
vnt proboblllty, l.. th llkllhood thot o glvn vnt wlll occur.
| you hov o systm wlth o crtoln numbr o posslbl outcoms, th proboblllty o th
occurrnc o o glvn vnt quols th numbr o outcoms thot quolly os thot vnt
dlvldd by th totol numbr o oll posslbl outcoms. A coln toss ls o slmpl xompllt hos
only two posslbl outcoms, hods or tolls. 1hr ls only on woy to llp hods. 1h
proboblllty thot th coln wlll turn up hods, thror, ls on dlvldd by two. J/2 or 50.
1ok o dck o lty-two cords. 1h proboblllty o drowlng on oc rom thot dck ls.
#456$) 89 &:$. ; #456$) 89 :&)1. " < ; => " ?-?@@ " A BC
1h proboblllty o drowlng o dlomond ls.
#456$) 89 12&58#1. ; #456$) 89 :&)1. " DE ; => " ?->= " >=C
W con olso colculot th proboblllty o multlpl vnts occurrlng ln squnc. 1o do thls,
w slmply multlply th lndlvlduol probobllltls o och vnt.
1h proboblllty o o coln turnlng up hods thr tlms ln o row ls.
*D;>+ F *D;>+ F *D;>+ " D;B *8) ?-D>=+
.monlng thot o coln wlll turn up hods thr tlms ln o row on out o lght tlms [och
tlm" blng thr tosssj.
1hr or o coupl o woys ln whlch w con us th /,7&8945 unctlon wlth proboblllty ln
cod. On tchnlqu ls to lll on orroy wlth o slctlon o numbrssom o whlch or
rpotdthn choos rondom numbrs rom thot orroy ond gnrot vnts bosd on
thos cholcs.
Whot ls th proboblllty o drowlng two ocs ln o row rom o dck o lty-two cords?
MO(.2&-( C"0 MO(.2&-( C"0
:72KL #23EE ' 7%; :72KJL
1 is stored in the array twice, making it
more likely to be picked.
#23EEKBL ' )*
#23EEK)L ' )*
|ntroductlon
8
Runnlng thls cod wlll produc o 40 chonc o prlntlng th volu J, o 20 chonc o prlntlng
2, ond o 40 chonc o prlntlng 3.
W con olso osk or o rondom numbr [lt`s mok lt slmpl ond just consldr rondom lootlng
polnt volus btwn 0 ond Jj ond ollow on vnt to occur only l our rondom numbr ls wlthln
o crtoln rong. |or xompl.
1hls mthod con olso b opplld to multlpl outcoms. Lt`s soy thot Outcom A hos o 60
chonc o hoppnlng, Outcom B, o J0 chonc, ond Outcom C, o 30 chonc. W
lmplmnt thls ln cod by plcklng o rondom loot ond slng lnto whot rong lt olls.
- between 0.00 ond 0.0 (0I > Outcome A
- between 0.0 ond 0.70 (!0I > Outcome B
- between 0.70 ond !.00 (30I > Outcome C
W could us th obov mthodology to crot o rondom wolkr thot tnds to mov to th
rlght. Hr ls on xompl o o +,-.%/ wlth th ollowlng probobllltls.
- chonce ot mov|ng up. 20
#23EEK>L ' >*
#23EEKHL ' H*
#23EEKDL ' H*
Picking a random element from an array :72 :7&%! ' :724/,7&894#23EEN-%7?2<55*
A probability of 10% E-8,2 $/8I ' BN)B*
A random floating point value between 0
and 1
E-8,2 / ' /,7&894)5*
f our random number is less than 0.1, try
again!
:E 4/ P $/8I5 1
== 2/" ,?,:7S
@
E-8,2 739 ' /,7&894)5*
f random number is less than 0.6 :E 4739 P BNG5 1
$/:72-74TU32089% VT5*
Between 0.6 and 0.7 @ %-#% :E 4739 P BNO5 1
$/:72-74TU32089% WT5*
Greater than 0.7 @ %-#% 1
$/:72-74TU32089% MT5*
@
1h Notur o Cod [v005j
9
- chonce ot mov|ng down. 20
- chonce ot mov|ng |ett. 20
- chonce ot mov|ng t|ght. 40
IJ&7:5# FK=L M&53#) '"&' '#1-8 '* 7*N# '* '"# )/6"'
A8:& #2%$45 1
E-8,2 / ' /,7&894)5*
A 40% chance of moving to the right! :E 4/ P BND5 1
!((*
@ %-#% :E 4/ P BNG5 1
!66*
@ %-#% :E 4/ P BNX5 1
"((*
@ %-#% 1
"66*
@
@
Crot o rondom wolkr wlth dynomlc probobllltls. |or xompl, con you glv lt o
50 chonc o movlng ln th dlrctlon o th mous?
MO(.2&-( C"= MO(.2&-( C"=
|ntroductlon
J0
C"> ! X*.E4% \&-'.&):'&*; *+ Y4;9*E X:E)(.- C"> ! X*.E4% \&-'.&):'&*; *+ Y4;9*E X:E)(.-
Lt`s go bock to thot populotlon o slmulotd Procsslng monkys. Your progrom gnrots o
thousond Monky objcts, och wlth o hlght volu btwn 200 ond 300 [os thls ls o world
o monkys thot hov hlghts btwn 200 ond 300 plxlsj.
Los thls occurotly dplct th hlghts o rol-world blngs? 1hlnk o o crowdd sldwolk ln
Nw York Clty. Plck ony prson o th strt ond lt moy oppor thot thlr hlght ls rondom.
Nvrthlss, lt`s not th klnd o rondom thot /,7&8945 producs. Popl`s hlghts or not
unlormly dlstrlbutd, thr or o grot dol mor popl o ovrog hlght thon thr or
vry toll or vry short ons. 1o slmulot notur, w moy wont lt to b mor llkly thot our
monkys or o ovrog hlght [250 plxlsj, yt stlll ollow thm to b, on occoslon, vry short
or vry toll.
A dlstrlbutlon o volus thot clustr oround on ovrog [rrrd to os th mon"j ls known os
o normol" dlstrlbutlon. |t ls olso colld th Gousslon dlstrlbutlon [nomd or mothmotlclon
Corl |rldrlch Goussj or, l you or |rnch, th Loploclon dlstrlbutlon [nomd or Plrr-5lmon
Loplocj. Both mothmotlclons wr worklng concurrntly ln th orly nlntnth cntury on
dlnlng such o dlstrlbutlon.
Whn you groph th dlstrlbutlon, you gt somthlng thot looks llk th ollowlng, lnormolly
known os o bll curv.
1h curv ls gnrotd by o mothmotlcol unctlon thot dlns th proboblllty o ony glvn
volu occurrlng os o unctlon o th mon [otn wrlttn os , th Grk lttr muj ond
stondord dvlotlon [o, th Grk lttr s|gmoj.
1h mon ls prtty osy to undrstond. |n th cos o our hlght volus btwn 200 ond
300, you probobly hov on lntultlv sns o th mon [l.. ovrogj os 250. Howvr, whot l
| wr to soy thot th stondord dvlotlon ls 3 or J5? Whot dos thls mon or th numbrs? 1h
E-8,2 < ' /,7&894>BBCHBB5*
Iiure I.z Iiure I.
1h Notur o Cod [v005j
JJ
grophs obov should glv us o hlnt. 1h groph on th lt shows us th dlstrlbutlon wlth o
vry low stondord dvlotlon, whr th mojorlty o th volus clustr closly oround th
mon. 1h groph on th rlght shows us o hlghr stondord dvlotlon, whr th volus or
mor vnly sprod out rom th ovrog.
1h numbrs work out os ollows. Glvn o populotlon, 68 o th mmbrs o thot
populotlon wlll hov volus ln th rong o on stondord dvlotlon rom th mon, 98
wlthln two stondord dvlotlons, ond 99.7 wlthln thr stondord dvlotlons. Glvn o
stondord dvlotlon o 5 plxls, only 0.3 o th monky hlghts wlll b lss thon 235 plxls
[thr stondord dvlotlons blow th mon o 250j or grotr thon 265 plxls [thr
stondord dvlotlons obov th mon o 250j.
P4%2:%4'&;< ](4; 4;9 U'4;94.9 \(I&4'&*; P4%2:%4'&;< ](4; 4;9 U'4;94.9 \(I&4'&*;
Consldr o closs o tn studnts who rclv th ollowlng scors [out o J00j on o
tst.
85, 82, 88, 8, 85, 93, 98, 40, 73, 83
*+$ -$(. /) &+$ (0$1(2$3 4567 *+$ -$(. /) &+$ (0$1(2$3 4567
1h stondord dvlotlon ls colculotd os th squor root o th ovrog o th squors
o dvlotlons oround th mon. |n othr words, tok th dlrnc rom th mon or
och prson ond squor lt [vorloncj. Colculot th ovrog o oll ths volus ond
tok th squor root os th stondord dvlotlon.
O0*)# O0*)# ./++#)#10# +)*7 P#&1 ./++#)#10# +)*7 P#&1 Q&)/&10# Q&)/&10#
85 85-8J.3 3.7
[3.7j
2
J3.69
40 40-8J.3 -4J.3
[-4J.3j
2
J705.69
tc.
2N#)&6# Q&)/&10#L 2N#)&6# Q&)/&10#L <?>K<= <?>K<=
*+$ )&(.8(18 8$0/(&/!. /) &+$ )9:(1$ 1!!& !; &+$ (0$1(2$ 0(1/(.%$3 5<657 *+$ )&(.8(18 8$0/(&/!. /) &+$ )9:(1$ 1!!& !; &+$ (0$1(2$ 0(1/(.%$3 5<657
Lucklly or us, to us o normol dlstrlbutlon o rondom numbrs ln o Procsslng sktch, w
don`t hov to do ony o ths colculotlons ourslvs. |nstod, w con mok us o o closs
known os Y,7&89, whlch w gt or r os port o th doult Jovo llbrorls lmportd lnto
|ntroductlon
J2
Procsslng [s th JovoLocs [http.//docs.orocl.com/jovos/6/docs/opl/jovo/utll/
Rondom.htmlj or mor lnormotlonj.
1o us th Rondom closs, w must lrst dclor o vorlobl o typ Rondom ond crot th
Rondom objct ln #%23$45.
| w wont to produc o rondom numbr wlth o normol [or Gousslonj dlstrlbutlon och tlm w
run through &/,;45, lt`s os osy os colllng th unctlon 7%!2Z,3##:,745.
Hr`s th thlng. Whot or w supposd to do wlth thls volu? Whot l w wontd to us lt, or
xompl, to osslgn th x-posltlon o o shop w drow on scrn?
1h 7%!2Z,3##:,745 unctlon rturns o normol dlstrlbutlon o rondom numbrs wlth th
ollowlng poromtrs. o meon ot zeto ond o stondotd dev|ot|on ot one. Lt`s soy w wont o
mon o 320 [th cntr horlzontol plxl ln o wlndow o wldth 640j ond o stondord dvlotlon o
60 plxls. W con odjust th volu to our poromtrs by multlplylng lt by th stondord
dvlotlon ond oddlng th mon.
IJ&7:5# FK>L R&(88/&1 -/8')/E('/*1
We use the variable name "generator
because what we have here can be thought
of as a random number generator.
Y,7&89 ?%7%/,28/*
A8:& #%23$45 1
#:F%4GDBCHGB5*
?%7%/,28/ ' 7%; Y,7&8945*
@
A8:& &/,;45 1
Asking for a Gaussian random number.
(Note nextGaussian() returns a double and
must be converted to float.)
E-8,2 739 ' 4E-8,25 ?%7%/,28/N7%!2Z,3##:,745*
@
A8:& &/,;45 1
1h Notur o Cod [v005j
J3
By drowlng th lllpss on top o och othr wlth som tronsporncy, w con octuolly s
th dlstrlbutlon. 1h brlghtst spot ls nor th cntr, whr most o th volus clustr, but
vry so otn clrcls or drown orthr to th rlght or lt o th cntr.
Note that nextGaussian() returns a double. E-8,2 739 ' 4E-8,25 ?%7%/,28/N7%!2Z,3##:,745*
E-8,2 #& ' GB*
E-8,2 9%,7 ' H>B*
Multiply by the standard deviation and add
the mean.
E-8,2 ! ' #& Q 739 ( 9%,7*
78[2/8.%45*
E:--4>JJC)B5*
%--:$#%4!C)XBC)GC)G5*
@
Consldr o slmulotlon o polnt splottr drown os o collctlon o colord dots. Most o
th polnt clustrs oround o cntrol locotlon, but som dots do splottr out towords th
dgs. Con you us o normol dlstrlbutlon o rondom numbrs to gnrot th
locotlons o th dots? Con you olso us o normol dlstrlbutlon o rondom numbrs to
gnrot o color poltt?
MO(.2&-( C"> MO(.2&-( C">
A Gousslon rondom wolk ls dlnd os on ln whlch th stp slz [how or th objct
movs ln o glvn dlrctlonj ls gnrotd wlth o normol dlstrlbutlon. |mplmnt thls
vorlotlon o our rondom wolk.
MO(.2&-( C"? MO(.2&-( C"?
C"? ! P:-'*E \&-'.&):'&*; *+ Y4;9*E X:E)(.- C"? ! P:-'*E \&-'.&):'&*; *+ Y4;9*E X:E)(.-
1hr wlll com o tlm ln your ll whn you do not wont o unlorm dlstrlbutlon o rondom
volus, or o Gousslon on.Lt`s lmogln or o momnt thot you or o rondom wolkr ln
sorch o ood. Movlng rondomly oround o spoc sms llk o rosonobl strotgy or
lndlng somthlng to ot. Atr oll, you don`t know whr th ood ls, so you mlght os wll
sorch rondomly untll you lnd lt. 1h problm, os you moy hov notlcd, ls thot rondom
wolkrs rturn to prvlously vlsltd locotlons mony tlms [thls ls known os ovrsompllng."j
On strotgy to ovold such o problm ls to, vry so otn, tok o vry lorg stp. 1hls
ollows th wolkr to orog rondomly oround o spcllc locotlon whll prlodlcolly jumplng
vry or owoy to rduc th omount o ovrsompllng. 1hls vorlotlon on th rondom wolk
|ntroductlon
J4
[known os o Lvy llghtj rqulrs o custom st o probobllltls. 1hough not on xoct
lmplmntotlon o o Lvy llght, w could stot th proboblllty dlstrlbutlon os ollows. th
longr th stp, th lss llkly lt ls to b plckd, th shortr th stp, th mor llkly.
Lorllr ln thls prologu, w sow thot w could gnrot custom proboblllty dlstrlbutlons by
llllng on orroy wlth volus [som dupllcotd so thot thy would b plckd mor rquntlyj or
by tstlng th rsult o /,7&8945. W could lmplmnt o Lvy llght by soylng thot thr ls o
J chonc o th wolkr toklng o lorg stp.
Howvr, thls rducs th probobllltls to o lxd numbr o optlons. Whot l w wontd to
mok o mor gnrol rulth hlghr o numbr, th mor llkly lt ls to b plckd? 3.J45
would b mor llkly to b plckd thon 3.J44, vn l thot llkllhood ls just o tlny blt grotr. |n
othr words, l ! ls th rondom numbr, w could mop th llkllhood on th y-oxls wlth " !.
| w con lgur out how to gnrot o dlstrlbutlon o rondom numbrs occordlng to th obov
groph, thn w wlll b obl to opply th som mthodology to ony curv or whlch w hov o
ormulo.
On solutlon ls to plck two rondom numbrs lnstod o on. 1h lrst rondom numbr ls just
thot, o rondom numbr. 1h scond on, howvr, ls whot w`ll coll o quollylng rondom
volu." |t wlll tll us whthr to us th lrst on or throw lt owoy ond plck onothr on.
Numbrs thot hov on oslr tlm quollylng wlll b plckd mor otn, ond numbrs thot
rorly quolly wlll b plckd lnrquntly. Hr or th stps [or now, lt`s consldr only
rondom volus btwn 0 ond Jj.
J. Plck o rondom numbr. RJ
E-8,2 / ' /,7&894)5*
A 1% chance of taking a large step :E 4/ P BNB)5 1
!#2%$ ' /,7&8946)BBC)BB5*
"#2%$ ' /,7&8946)BBC)BB5*
@ %-#% 1
!#2%$ ' /,7&8946)C)5*
"#2%$ ' /,7&8946)C)5*
@
Iiure I.(
1h Notur o Cod [v005j
J5
2. Comput o proboblllty P thot RJ should quolly. Lt`s try. P RJ.
3. Plck onothr rondom numbr. R2
4. | R2 ls lss thon P, thn w hov ound our numbrRJ!
5. | R2 ls not lss thon P, go bock to stp J ond stort ovr.
Hr w or soylng thot th llkllhood thot o rondom volu wlll quolly ls quol to th
rondom numbr ltsl. Lt`s soy w plck 0.J or RJ. 1hls mons thot RJ wlll hov o J0 chonc
o quollylng. | w plck 0.83 or RJ thn lt wlll hov o 83 chonc o quollylng. 1h hlghr
th numbr, th grotr th llkllhood thot w wlll octuolly us lt.
Hr ls o unctlon [nomd or th Mont Corlo mthod, whlch wos nomd or th Mont
Corlo coslnoj thot lmplmnts th obov olgorlthm, rturnlng o rondom volu btwn 0 ond
J.
E-8,2 9872%0,/-845 1
We do this "forever until we find a
qualifying random value.
;<:-% 42/3%5 1
Pick a random value. E-8,2 /) ' /,7&894)5*
Assign a probability. E-8,2 $/8I,I:-:2" ' /)*
Pick a second random value. E-8,2 /> ' /,7&894)5*
Does it qualify? f so, we're done! :E 4/> P $/8I,I:-:2"5 1
/%23/7 /)*
@
@
@
|ntroductlon
J6
s o custom proboblllty dlstrlbutlon to vory th slz o o stp tokn by th rondom
wolkr. 1h stp slz con b dtrmlnd by lnlunclng th rong o volus plckd. Con
you mop th proboblllty xponntlollyl.. moklng th llkllhood thot o volu ls plckd
quol to th volu squord?
[Lotr w`ll s how to do thls mor lclntly uslng vctors.j
A uniform distribution of step sizes.
Change this!
E-8,2 #2%$#:F% ' /,7&894BC)B5*
E-8,2 #2%$! ' /,7&8946#2%$#:F%C#2%$#:F%5*
E-8,2 #2%$" ' /,7&8946#2%$#:F%C#2%$#:F%5*
! (' #2%$!*
" (' #2%$"*
MO(.2&-( C"K MO(.2&-( C"K
C"K 5(.%&; X*&-( ^! UE**',(. !QQ.*42,_ C"K 5(.%&; X*&-( ^! UE**',(. !QQ.*42,_
A good rondom numbr gnrotor producs numbrs thot hov no rlotlonshlp ond show no
dlscrnlbl pottrn. As w or bglnnlng to s, o llttl blt o rondomnss con b o good thlng
whn progrommlng orgonlc, llllk bhovlors. Howvr, rondomnss os th slngl guldlng
prlnclpl ls not ncssorlly noturol. An olgorlthm known os Prlln nols," nomd or lts
lnvntor Kn Prlln, toks thls concpt lnto occount. Prlln dvlopd th nols unctlon whll
worklng on th orlglnol 7ton movl ln th orly J980s, lt wos dslgnd to crot procdurol
txturs or computr-gnrotd cts. |n J997 Prlln won on Acodmy Aword ln tchnlcol
ochlvmnt or thls work. Prlln nols con b usd to gnrot vorlous cts wlth noturol
quolltls, such os clouds, londscops, ond pottrnd txturs llk morbl.
Prlln nols hos o mor orgonlc opporonc bcous lt producs o noturolly ordrd
[smooth"j squnc o psudo-rondom numbrs. 1h groph on th lt blow shows Prlln
nols ovr tlm, wlth th x-oxls rprsntlng tlm, not th smoothnss o th curv. 1h
groph on th rlght shows pur rondom numbrs ovr tlm. [1h cod or gnrotlng ths
grophs ls ovollobl ln th occomponylng book downloods.j
1h Notur o Cod [v005j
J7
Procsslng hos o bullt-ln lmplmntotlon o th Prlln nols olgorlthm. th unctlon 78:#%45.
1h 78:#%45 unctlon toks on, two, or thr orgumnts, os nols ls computd ln on, two,
or thr dlmnslons. Lt`s stort by looklng ot on-dlmnslonol nols.
X*&-( \('4&% X*&-( \('4&%
1h Procsslng nols rrnc [http.//procsslng.org/rrnc/nols_.htmlj tlls us
thot nols ls colculotd ovr svrol octovs." Colllng th 78:#%\%2,:-45
[http.//procsslng.org/rrnc/nolsLtoll_.htmlj unctlon wlll chong both th
numbr o octovs ond thlr lmportonc rlotlv to on onothr. 1hls ln turn chongs
how th nols unctlon bhovs.
An onlln lctur by Kn Prlln lts you lorn mor obout how nols works rom
Prlln hlmsl [http.//www.nolsmochln.com/tolkJ/j.
Consldr drowlng o clrcl ln our Procsslng wlndow ot o rondom x-locotlon.
Now, lnstod o o rondom x-locotlon, w wont o Prlln nols x-locotlon thot ls smoothr."
You mlght thlnk thot oll you nd to do ls rploc /,7&8945 wlth 78:#%45, l..
Whll concptuolly thls ls xoctly whot w wont to docolculot on x-volu thot rongs
btwn 0 ond th wldth occordlng to Prlln nolsthls ls not th corrct lmplmntotlon.
Whll th orgumnts to th /,7&8945 unctlon spcly o rong o volus btwn o
mlnlmum ond o moxlmum, 78:#%45 dos not work thls woy. |nstod, th output rong ls
Iiure I.: Noise Iiure I.: Rcndom
A random x-location E-8,2 ! ' /,7&894BC;:&2<5*
%--:$#%4!C)XBC)GC)G5*
A noise x-location? E-8,2 ! ' 78:#%4BC;:&2<5*
|ntroductlon
J8
lxdlt olwoys rturns o volu btwn 0 ond J. W`ll s ln o momnt thot w con gt
oround thls oslly wlth Procsslng`s 9,$45 unctlon, but lrst w must xomln whot xoctly
78:#%45 xpcts us to poss ln os on orgumnt.
W con thlnk o on-dlmnslonol Prlln nols os o llnor squnc o volus ovr tlm. |or
xompl.
!/7# !/7# %*/8# Q&5(# %*/8# Q&5(#
0 0.365
J 0.363
2 0.363
3 0.364
4 0.366
Now, ln ordr to occss o portlculor nols volu ln Procsslng, w hov to poss o spcllc
"momnt ln tlm" to th 78:#%45 unctlon. |or xompl.
Accordlng to th obov tobl, 78:#%4H5 wlll rturn 0.364 ot tlm quols 3. W could lmprov
thls by uslng o vorlobl or tlm ond osklng or o nols volu contlnuously ln &/,;45.
1h obov cod rsults ln th som volu prlntd ovr ond ovr. 1hls hoppns bcous w
or osklng or th rsult o th 78:#%45 unctlon ot th som polnt ln tlm3ovr ond ovr.
| w lncrmnt th tlm vorlobl 2, howvr, w`ll gt o dlrnt rsult.
E-8,2 7 ' 78:#%4H5*
E-8,2 2 ' H*
A8:& &/,;45 1
We need the noise value for a specific
moment in time.
E-8,2 7 ' 78:#%425*
$/:72-7475*
@
Typically we would start at time = 0, though
this is arbitrary.
E-8,2 2 ' B*
A8:& &/,;45 1
E-8,2 7 ' 78:#%425*
$/:72-7475*
1h Notur o Cod [v005j
J9
How qulckly w lncrmnt 2 olso octs th smoothnss o th nols. | w mok lorg
jumps ln tlm, thn w or sklpplng ohod ond th volus wlll b mor rondom.
1ry runnlng th cod svrol tlms, lncrmntlng 2 by 0.0J, 0.02, 0.05, 0.J, 0.000J, ond you
wlll s dlrnt rsults.
Now, we move forward in time! 2 (' BNB)*
@
Iiure I.;
]4QQ&;< X*&-( ]4QQ&;< X*&-(
Now w`r rody to onswr th qustlon o whot to do wlth th nols volu. Onc w hov
th volu wlth o rong btwn 0 ond J, lt`s up to us to mop thot rong to whot w wont. 1h
oslst woy to do thls ls wlth Procsslng`s 9,$45 unctlon. 1h 9,$45 unctlon toks lv
orgumnts. |lrst up ls th volu w wont to mop, ln thls cos 7. 1hn w hov to glv lt th
volu`s currnt rong [mlnlmum ond moxlmumj, ollowd by our dslrd rong.
|n thls cos, w know thot nols hos o rong btwn 0 ond J, but w`d llk to drow our
clrcl wlth o rong btwn 0 ond th wlndow`s wldth.
Iiure I.8
|ntroductlon
20
W con opply th xoct som loglc to our rondom wolkr, ond osslgn both lts x- ond y-volus
occordlng to Prlln nols.
IJ&7:5# FK?L 9#)5/1 1*/8# 4&53#)
E-8,2 2 ' B*
A8:& &/,;45 1
E-8,2 7 ' 78:#%425*
Using map() to customize the range of
Perlin noise
E-8,2 ! ' 9,$47CBC)CBC;:&2<5*
%--:$#%4!C)XBC)GC)G5*
2 (' BNB)*
@
0-,## +,-.%/ 1
E-8,2 !C"*
E-8,2 2!C2"*
+,-.%/45 1
2! ' B*
2" ' )BBBB*
@
A8:& #2%$45 1
x- and y-location mapped from noise ! ' 9,$478:#%42!5C BC )C BC ;:&2<5*
" ' 9,$478:#%42"5C BC )C BC <%:?<25*
Move forward through "time. 2! (' BNB)*
2" (' BNB)*
@
@
1h Notur o Cod [v005j
2J
Notlc how th obov xompl rqulrs on oddltlonol polr o vorlobls. 2! ond 2". 1hls ls
bcous w nd to kp trock o two tlm vorlobls, on or th x-locotlon o th +,-.%/
objct ond on or th y-locotlon. But thr ls somthlng o blt odd obout ths vorlobls.
Why dos 2! stort ot 0 ond 2" ot J0,000? Whll ths numbrs or orbltrory cholcs, w
hov vry spcllcolly lnltlollzd our two tlm vorlobls wlth dlrnt volus. 1hls ls bcous
th nols unctlon ls dtrmlnlstlc. lt glvs you th som rsult or o spcllc tlm 2 och
ond vry tlm. | w oskd or th nols volu ot th som tlm 2 or both ! ond ", thn !
ond " would olwoys b quol, monlng thot th +,-.%/ objct would only mov olong o
dlogonol. |nstod, w slmply us two dlrnt ports o th nols spoc, stortlng ot 0 or !
ond J0,000 or " so thot ! ond " con oppor to oct lndpndntly o och othr.
|n truth, thr ls no octuol concpt o tlm ot ploy hr. |t`s o usul mtophor to hlp us
undrstond how th nols unctlon works, but rolly whot w hov ls spoc, rothr thon
tlm. 1h groph obov dplcts o llnor squnc o nols volus ln o on-dlmnslonol
spoc, ond w con osk or o volu ot o spcllc x-locotlon whnvr w wont. |n xompls,
you wlll otn s o vorlobl nomd !8EE to lndlcot th x-ost olong th nols groph,
rothr thon 2 or tlm [os notd ln th dlogromj.
Iiure I.p
|n th obov rondom wolkr, th rsult o th nols unctlon ls moppd dlrctly to th
+,-.%/`s locotlon. Crot o rondom wolkr whr you lnstod mop th rsult o th
78:#%45 unctlon to o +,-.%/`s stp slz.
MO(.2&-( C"L MO(.2&-( C"L
@8*Z\&E(;-&*;4% X*&-( @8*Z\&E(;-&*;4% X*&-(
1hls ldo o nols volus llvlng ln o on-dlmnslonol spoc ls lmportont bcous lt lods us
rlght lnto o dlscusslon o two-dlmnslonol spoc. Lt`s thlnk obout thls or o momnt. Wlth
on-dlmnslonol nols, w hov o squnc o volus ln whlch ony glvn volu ls slmllor to
lts nlghbor. Bcous th volu ls ln on dlmnslon, lt only hos two nlghbors. o volu thot
coms bor lt [to th lt on th grophj ond on thot coms otr lt [to th rlghtj.
|ntroductlon
22
1wo-dlmnslonol nols works xoctly th som woy concptuolly. 1h dlrnc o cours ls
thot w orn`t looklng ot volus olong o llnor poth, but volus thot or slttlng on o grld. 1hlnk
o o plc o groph popr wlth numbrs wrlttn lnto och cll. A glvn volu wlll b slmllor to
oll o lts nlghbors. obov, blow, to th rlght, to th lt, ond olong ony dlogonol.
| you wr to vlsuollz thls groph popr wlth och volu moppd to th brlghtnss o o color,
you would gt somthlng thot looks llk clouds. Whlt slts nxt to llght groy, whlch slts nxt to
groy, whlch slts nxt to dork groy, whlch slts nxt to block, whlch slts nxt to dork groy, tc.
1hls ls why nols wos orlglnolly lnvntd. You twok th poromtrs o blt or ploy wlth color to
mok th rsultlng lmog look mor llk morbl or wood or ony othr orgonlc txtur.
Lt`s tok o qulck look ot how to lmplmnt two-dlmnslonol nols ln Procsslng. | you
wontd to color vry plxl o o wlndow rondomly, you would nd o nstd loop, on thot
occssd och plxl ond plckd o rondom brlghtnss.
Iiure I.:o: :D Noise Iiure I.::: zD Noise
-8,&]:!%-#45*
E8/ 4:72 ! ' B* ! P ;:&2<* !((5 1
E8/ 4:72 " ' B* " P <%:?<2* "((5 1
A random brightness! E-8,2 I/:?<2 ' /,7&894>JJ5*
$:!%-#K!("Q;:&2<L ' 08-8/4I/:?<25*
@
@
3$&,2%]:!%-#45*
1h Notur o Cod [v005j
23
1o color och plxl occordlng to th 78:#%45 unctlon, w`ll do xoctly th som thlng, only
lnstod o colllng /,7&8945 w`ll coll 78:#%45.
1hls ls o nlc stort concptuollylt glvs you o nols volu or vry [!,"j locotlon ln our
two-dlmnslonol spoc. 1h problm ls thot thls won`t hov th cloudy quollty w wont.
Jumplng rom plxl 200 to plxl 20J ls too lorg o o jump through nols. Rmmbr, whn
w workd wlth on-dlmnslonol nols, w lncrmntd our tlm vorlobl by 0.0J och
rom, not by J! A prtty good solutlon to thls problm ls to just us dlrnt vorlobls or
th nols orgumnts. |or xompl, w could lncrmnt o vorlobl colld !8EE och tlm w
mov horlzontolly, ond o "8EE vorlobl och tlm w mov vrtlcolly through th nstd
loops.
IJ&7:5# FK@L <. 9#)5/1 1*/8#
A Perlin noise brightness! 9'8&/ 6)2GH/ " 5&0*#82.$*IJ3+J?JDJ?J>==+,
Start xoff at 0. 9'8&/ I899 " ?-?,
E8/ 4:72 ! ' B* ! P ;:&2<* !((5 1
For every xoff, start yoff at 0. 9'8&/ 3899 " ?-?,
E8/ 4:72 " ' B* " P <%:?<2* "((5 1
Use xoff and yoff for noise(). 9'8&/ 6)2GH/ "
5&0*#82.$*I899J3899+J?JDJ?J>==+,
Use x and y for pixel location. $:!%-#K!("Q;:&2<L ' 08-8/4I/:?<25*
ncrement yoff. 3899 K" ?-?D,
@
ncrement xoff. I899 K" ?-?D,
@
Ploy wlth color, 78:#%\%2,:-45, ond th rot ot whlch !8EE ond "8EE or
lncrmntd to ochlv dlrnt vlsuol cts.
MO(.2&-( C"N MO(.2&-( C"N
|ntroductlon
24
W`v xomlnd svrol trodltlonol uss o Prlln nols ln thls sctlon. Wlth on-dlmnslonol
nols, w usd smooth volus to osslgn th locotlon o on objct to glv th opporonc o
wondrlng. Wlth two-dlmnslonol nols, w crotd o cloudy pottrn wlth smoothd volus on
o plon o plxls. |t`s lmportont to rmmbr, howvr, thot Prlln nols volus or just
thotvolus. 1hy orn`t lnhrntly tld to plxl locotlons or color. Any xompl ln thls book
thot hos o vorlobl could b controlld vlo Prlln nols. Whn w modl o wlnd orc, lts
strngth could b controlld by Prlln nols. 5om gos or th ongls btwn th bronchs
ln o roctol tr pottrn, or th spd ond dlrctlon o objcts movlng olong o grld ln o low
lld slmulotlon.
Add o thlrd orgumnt to nols thot lncrmnts onc pr cycl through &/,;45 to
onlmot th two-dlmnslonol nols.
MO(.2&-( C"W MO(.2&-( C"W
s th nols volus os th lvotlons o o londscop. 5 th scrnshot blow os o
rrnc.
MO(.2&-( C"#T MO(.2&-( C"#T
1h Notur o Cod [v005j
25
Iiure I.:z: Tree uith Perlin noise Iiure I.:: Ilou jield uith Perlin noise
C"L F;84.9 C"L F;84.9
W bgon thls choptr by tolklng obout how rondomnss con b o crutch. |n mony woys, lt`s
th most obvlous onswr to th klnds o qustlons w osk contlnuouslyhow should thls
objct mov? Whot color should lt b? 1hls obvlous onswr, howvr, con olso b o lozy
on.
As w lnlsh o th lntroductlon, lt`s olso worth notlng thot w could just os oslly oll lnto
th trop o uslng Prlln nols os o crutch. How should thls objct mov? Prlln nols! Whot
color should lt b? Prlln nols! How ost should lt grow? Prlln nols!
1h polnt o oll o thls ls not to soy thot you should or shouldn`t us rondomnss. Or thot
you should or shouldn`t us Prlln nols. 1h polnt ls thot th ruls o your systm or
dlnd by you, ond th lorgr your toolbox, th mor cholcs you`ll hov os you lmplmnt
thos ruls. 1h gool o thls book ls to lll your toolbox. | oll you know ls rondom, thn your
dslgn thlnklng ls llmltd. 5ur, Prlln nols hlps, but you`ll nd mor. A lot mor.
| thlnk w`r rody to bgln.
|ntroductlon
26
,"&:'#) ;K Q#0'*)8 ,"&:'#) ;K Q#0'*)8
Roer, Roer. Whct's our tector, Victor?
! @$34$-, AB&)2 C>-23?$,&D
1hls book ls oll obout looklng ot th world oround us ond comlng up wlth clvr woys to
slmulot thot world wlth cod. Llvldd lnto thr ports, th book wlll stort by looklng ot boslc
physlcshow on oppl olls rom o tr, o pndulum swlngs ln th olr, th orth rvolvs
oround th sun, tc. Absolutly vrythlng contolnd wlthln th lrst lv choptrs o thls book
rqulrs th us o th most boslc bulldlng block or progrommlng motlonth 0$%&!1 0$%&!1. And so
thls ls whr w bgln our story.
Now, th word vctor con mon o lot o dlrnt thlngs. Vctor ls th nom o o Nw Wov
rock bond ormd ln 5ocromnto, CA ln th orly J980s. |t`s th nom o o brokost crol
monuocturd by Kllogg`s Conodo. |n th lld o pldmlology, o vctor ls usd to dscrlb
on orgonlsm thot tronsmlts lnctlon rom on host to onothr. |n th C progrommlng
longuog, o vctor [std..vctorj ls on lmplmntotlon o o dynomlcolly rslzobl orroy doto
structur. Whll oll ths dlnltlons or lntrstlng, thy`r not whot w`r looklng or. Whot
w wont ls colld o =:%'/8$(. 0$%&!1 =:%'/8$(. 0$%&!1 [nomd or th Grk mothmotlclon Luclld ond olso
known os o gomtrlc vctorj. Whn you s th trm vctor" ln thls book, you con ossum lt
rrs to o Luclldon vctor, dlnd os on ent|ty thot hos both mogn|tude ond d|tect|on.
A vctor ls typlcolly drown os o orrow, th dlrctlon ls lndlcotd by whr th orrow ls
polntlng, ond th mognltud by th lngth o th orrow ltsl.
1h Notur o Cod [v005j
27
|n th obov lllustrotlon, th vctor ls drown os on orrow rom polnt A to polnt B ond srvs
os on lnstructlon or how to trovl rom A to B.
Iiure :.:: A tector (drcun cs cn crrou) hcs mcnitude (lenth oj crrou) cnd direction (uhich uc
it is pointin).
#"# R(2'*.-` a*: P*EQ%('( ]( #"# R(2'*.-` a*: P*EQ%('( ](
Bor w dlv lnto mor o th dtolls obout vctors, lt`s look ot o boslc Procsslng
xompl thot dmonstrots why w should cor obout vctors ln th lrst ploc. | you`v
rod ony o th lntroductory Procsslng txtbooks or tokn o closs on progrommlng wlth
Procsslng [ond hopully you`v don on o ths thlngs to hlp prpor you or thls
bookj, you probobly, ot on polnt or onothr, lornd how to wrlt o slmpl bounclng boll
sktch.
Ij ou cre recdin this bool cs c PDI or in print, then ou uill onl see screenshots oj the code.
Motion, oj course, is c le element oj our discussion, so to the extent possible, the stctic screenshots
uill include trcils to ite c sense oj the behctior. Ior more cbout hou to drcu trcils, see the code
excmples ctcilcble jor dounlocd.
Choptr J. Vctors
28
Locotlon Locotlon x ond y
5pd 5pd xspeed ond yspeed
IJ&7:5# ;K;L S*(10/16 E&55 4/'" 1* N#0'*)8
|n th obov xompl, w hov o vry slmpl worldo blonk convos wlth o clrculor shop [o
boll"j trovllng oround. 1hls boll hos som proprtls, whlch or rprsntd ln th cod os
vorlobls.
|n o mor odvoncd sktch, w could lmogln hovlng mony mor vorlobls.
Variables for location and speed of ball. E-8,2 ! ' )BB*
E-8,2 " ' )BB*
E-8,2 !#$%%& ' )*
E-8,2 "#$%%& ' HNH*
Remember how Processing works? setup()
is executed once when the sketch starts
and draw() loops forever and ever (until you
quit).
A8:& #%23$45 1
#:F%4>BBC>BB5*
#9882<45*
I,0.?/837&4>JJ5*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
Move the ball according to its speed. ! ' ! ( !#$%%&*
" ' " ( "#$%%&*
Check for bouncing. :E 44! ^ ;:&2<5 __ 4! P B55 1
!#$%%& ' !#$%%& Q 6)*
@
:E 44" ^ <%:?<25 __ 4" P B55 1
"#$%%& ' "#$%%& Q 6)*
@
#2/8.%4B5*
E:--4)OJ5*
Display the ball at the location (x,y). %--:$#%4!C"C)GC)G5*
@
1h Notur o Cod [v005j
29
Acclrotlon Acclrotlon xocce|etot|on ond yocce|etot|on
1orgt locotlon 1orgt locotlon xtotget ond ytotget
Wlnd Wlnd xw|nd ond yw|nd
|rlctlon |rlctlon xtt|ct|on ond ytt|ct|on
|t`s bcomlng clorr thot or vry concpt ln thls world [wlnd, locotlon, occlrotlon, tc.j,
w`ll nd two vorlobls. And thls ls only o two-dlmnslonol world. |n o 3L world, w`ll nd
!, ", F, !#$%%&, "#$%%&, F#$%%&, ond so on.
Wouldn`t lt b nlc l w could slmplly our cod ond us wr vorlobls?
|nstod o.
W could slmply hov.
1oklng thls lrst stp ln uslng vctors won`t ollow us to do onythlng nw. Just oddlng vctors
won`t moglcolly mok your Procsslng sktchs slmulot physlcs. Howvr, thy wlll
slmplly your cod ond provld o st o unctlons or common mothmotlcol oprotlons thot
hoppn ovr ond ovr ond ovr ogoln whll progrommlng motlon.
As on lntroductlon to vctors, w`r golng to llv ln two dlmnslons or qult som tlm [ot
lost untll w gt through th lrst svrol choptrsj. All o ths xompls con b olrly
oslly xtndd to thr dlmnslons [ond th closs w wlll us]`%028/ollows or thr
dlmnslons.j Howvr, lt`s oslr to stort wlth just two.
E-8,2 !*
E-8,2 "*
E-8,2 !#$%%&*
E-8,2 "#$%%&*
`%028/ -80,2:87*
`%028/ #$%%&*
#"0 R(2'*.- +*. 5.*2(--&;< 5.*<.4EE(.- #"0 R(2'*.- +*. 5.*2(--&;< 5.*<.4EE(.-
On woy to thlnk o o vctor ls th dlrnc btwn two polnts. Consldr how you mlght
go obout provldlng lnstructlons to wolk rom on polnt to onothr.
Hr or som vctors ond posslbl tronslotlons.
Choptr J. Vctors
30
[-J5, 3j [-J5, 3j o|| t|tteen steps west, tutn ond wo|| thtee steps notth.
[3, 4j [3, 4j o|| thtee steps eost, tutn ond wo|| t|ve steps notth.
[2, -Jj [2, -Jj o|| two steps eost, tutn ond wo|| one step south.
You`v probobly don thls bor whn progrommlng motlon. |or vry rom o onlmotlon
[l.. o slngl cycl through Procsslng`s &/,;45 loopj, you lnstruct och objct on th scrn
to mov o crtoln numbr o plxls horlzontolly ond o crtoln numbr o plxls vrtlcolly.
|or vry rom.
.$> '!%(&/!. ? 0$'!%/&@ (AA'/$8 &! %:11$.& '!%(&/!. .$> '!%(&/!. ? 0$'!%/&@ (AA'/$8 &! %:11$.& '!%(&/!.
| vloclty ls o vctor [th dlrnc btwn two polntsj, whot ls locotlon? |s lt o vctor too?
1chnlcolly, on mlght orgu thot locotlon ls not o vctor, slnc lt`s not dscrlblng how to
mov rom on polnt to onothrlt`s slmply dscrlblng o slngulor polnt ln spoc.
Iiure :.z
Iiure :.
1h Notur o Cod [v005j
3J
locotlon locotlon x,y
vloclty vloclty xspeed,yspeed
Nvrthlss, onothr woy to dscrlb o locotlon ls th poth tokn rom th orlgln to roch
thot locotlon. Hnc, o locotlon con b th vctor rprsntlng th dlrnc btwn
locotlon ond orlgln.
Lt`s xomln th undrlylng doto or both locotlon ond vloclty. |n th bounclng boll
xompl, w hod th ollowlng.
Notlc how w or storlng th som doto or bothtwo lootlng polnt numbrs, on ! ond o ".
| w wr to wrlt o vctor closs ourslvs, w`d stort wlth somthlng rothr boslc.
At lts cor, o ]`%028/ ls just o convnlnt woy to stor two volus [or thr, os w`ll s ln
3L xomplsj.
And so thls .
Iiure :.(
0-,## ]`%028/ 1
E-8,2 !*
E-8,2 "*
]`%028/4E-8,2 !aC E-8,2 "a5 1
! ' !a*
" ' "a*
@
@
Choptr J. Vctors
32
bcoms .
Now thot w hov two vctor objcts [locotlon ond vlocltyj, w`r rody to lmplmnt th
olgorlthm or motlon'!%(&/!. ? '!%(&/!. B 0$'!%/&@ '!%(&/!. ? '!%(&/!. B 0$'!%/&@. |n Lxompl J.J, wlthout vctors, w hod.
|n on ldol world, w would b obl to rwrlt th obov os.
Howvr, ln Procsslng, th oddltlon oprotor ls rsrvd or prlmltlv volus [lntgrs,
loots, tc.j only. Procsslng dosn`t know how to odd two ]`%028/ objcts togthr ony mor
thon lt knows how to odd two ]b872 objcts or ]c9,?% objcts. |ortunotly or us, th
]`%028/ closs lncluds unctlons or common mothmotlcol oprotlons.
E-8,2 ! ' )BB*
E-8,2 " ' )BB*
E-8,2 !#$%%& ' )*
E-8,2 "#$%%& ' HNH*
]`%028/ -80,2:87 ' 7%; ]`%028/4)BBC)BB5*
]`%028/ A%-80:2" ' 7%; ]`%028/4)CHNH5*
Add each speed to each location. ! ' ! ( !#$%%&*
" ' " ( "#$%%&*
Add the velocity vector to the location
vector.
-80,2:87 ' -80,2:87 ( A%-80:2"*
#"= R(2'*. !99&'&*; #"= R(2'*. !99&'&*;
Bor w contlnu looklng ot th ]`%028/ closs ond lts ,&&45 mthod [purly or th sok o
lornlng slnc lt`s olrody lmplmntd or us ln Procsslng ltslj, lt`s xomln vctor
oddltlon uslng th nototlon ound ln moth ond physlcs txtbooks.
Vctors or typlcolly wrlttn lthr ln boldoc typ or wlth on orrow on top. |or th purposs
o thls book, to dlstlngulsh o 0$%&!1 0$%&!1 rom o )%('(1 )%('(1 [sco|ot rrs to o slngl volu, such os on
lntgr or o lootlng polnt numbrj, w`ll us th orrow nototlon.
- Vctor. !

- 5color. "
Lt`s soy | hov th ollowlng two vctors.
1h Notur o Cod [v005j
33
Loch vctor hos two componnts, on ! ond o ". 1o odd two vctors togthr, w slmply odd
both !`s ond both "`s.
|n othr words.
#

con b wrlttn os.


#
"
!
"
$
"
#
%
!
%
$
%
1hn, rploclng 3 ond A wlth thlr volus rom |lgur J.6, w gt.
#
"
5 3
whlch mons thot.
|lnolly, w wrlt thot os o vctor.
#

(8, 6)
Iiure :.
Iiure :.
Choptr J. Vctors
34
Now thot w undrstond how to odd two vctors togthr, w con look ot how oddltlon ls
lmplmntd ln th ]`%028/ closs ltsl. Lt`s wrlt o unctlon colld ,&&45 thot toks onothr
]`%028/ objct os lts orgumnt.
Now thot w s how ,&&45 ls wrlttn lnsld o ]`%028/, w con rturn to our bounclng boll
xompl wlth lts '!%(&/!. B 0$'!%/&@ '!%(&/!. B 0$'!%/&@ olgorlthm ond lmplmnt vctor oddltlon.
And hr w or, rody to rwrlt th bounclng boll xompl uslng ]`%028/.
IJ&7:5# ;K<L S*(10/16 E&55 4/'" 9Q#0'*)8T
0-,## ]`%028/ 1
E-8,2 !*
E-8,2 "*
]`%028/4E-8,2 !aC E-8,2 "a5 1
! ' !a*
" ' "a*
@
New! A function to add another PVector to
this PVector. Simply add the x components
and the y components together.
L821 &11*MN$:/8) L+ O
3 " 3 K L-3,
I " I K L-I,
P
@
Add the current velocity to the location. -80,2:87 ' -80,2:87 ( A%-80:2"*
-80,2:87N,&&4A%-80:2"5*
nstead of a bunch of floats, we now just
have two PVector variables.
MN$:/8) '8:&/28#,
MN$:/8) L$'8:2/3,
A8:& #%23$45 1
#:F%4>BBC>BB5*
#9882<45*
'8:&/28# " #$! MN$:/8)*D??JD??+,
L$'8:2/3 " #$! MN$:/8)*>-=J=+,
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
'8:&/28#-&11*L$'8:2/3+,
1h Notur o Cod [v005j
35
Now, you mlght l somwhot dlsoppolntd. Atr oll, thls moy lnltlolly oppor to hov
mod th cod mor compllcotd thon th orlglnol vrslon. Whll thls ls o prctly
rosonobl ond volld crltlqu, lt`s lmportont to undrstond thot w hovn`t ully rollzd th
powr o progrommlng wlth vctors just yt. Looklng ot o slmpl bounclng boll ond only
lmplmntlng vctor oddltlon ls just th lrst stp. As w mov orword lnto o mor complx
world o multlpl objcts ond multlpl ;!1%$) ;!1%$) [whlch w`ll lntroduc ln Choptr 2j, th
bnlts o ]`%028/ wlll bcom mor oppornt.
W should, howvr, not on lmportont ospct o th obov tronsltlon to progrommlng wlth
vctors. Lvn though w or uslng ]`%028/ objcts to dscrlb two volusth ! ond " o
locotlon ond th ! ond " o vlocltyw stlll otn nd to rr to th x ond y componnts
o och ]`%028/ lndlvlduolly. Whn w go to drow on objct ln Procsslng, thr`s no
mons or us to soy.
1h %--:$#%45 unctlon dos not ollow or o ]`%028/ os on orgumnt. An lllps con only
b drown wlth two scolor volus, on !-coordlnot ond o "-coordlnot. And so w must dlg
lnto th ]`%028/ objct ond pull out th x ond y componnts uslng objct-orlntd dot
syntox.
1h som lssu orlss whn tstlng l th clrcl hos rochd th dg o th wlndow, ond
w nd to occss th lndlvlduol componnts o both vctors. -80,2:87 ond A%-80:2".
We still sometimes need to refer to the
individual components of a PVector and
can do so using the dot syntax: location.x,
velocity.y, etc.
29 **'8:&/28#-I Q !21/H+ RR *'8:&/28#-I S ?++ O
L$'8:2/3-I " L$'8:2/3-I F TD,
P
29 **'8:&/28#-3 Q H$2GH/+ RR *'8:&/28#-3 S ?++ O
L$'8:2/3-3 " L$'8:2/3-3 F TD,
P
#2/8.%4B5*
E:--4)OJ5*
$''20.$*'8:&/28#-IJ'8:&/28#-3JDUJDU+,
@
%--:$#%4-80,2:87C)GC)G5*
%--:$#%4-80,2:87N!C-80,2:87N"C)GC)G5*
:E 44-80,2:87N! ^ ;:&2<5 __ 4-80,2:87N! P B55 1
A%-80:2"N! ' A%-80:2"N! Q 6)*
@
Choptr J. Vctors
36
|lnd somthlng you`v prvlously mod ln Procsslng uslng sporot ! ond " vorlobls
ond us ]`%028/s lnstod.
MO(.2&-( #"# MO(.2&-( #"#
1ok on o th wolkr xompls rom th lntroductlon ond convrt lt to us ]`%028/s.
MO(.2&-( #"0 MO(.2&-( #"0
Lxtnd th bounclng boll wlth vctors xompl lnto 3L. Con you gt o sphr to bounc
oround o box?
MO(.2&-( #"= MO(.2&-( #"=
#"> ]*.( R(2'*. ]4', #"> ]*.( R(2'*. ]4',
Addltlon wos rolly just th lrst stp. 1hr or mony mothmotlcol oprotlons thot or
commonly usd wlth vctors. Blow ls o comprhnslv llst o th oprotlons ovollobl os
unctlons ln th ]`%028/ closs. W`ll go through o w o th ky ons now. As our xompls
gt mor sophlstlcotd ln lotr choptrs, w`ll contlnu to rvol th dtolls o mor unctlons.
- ,&&45 odd vctors
- #3I45 subtroct vctors
- 93-245 scol th vctor wlth multlpllcotlon
- &:A45 scol th vctor wlth dlvlslon
- 9,?45 colculot th mognltud o o vctor
- #%2d,?45 - st th mognltud o o vctor
- 78/9,-:F%45 normollz th vctor to o unlt lngth o J
- -:9:245 llmlt th mognltud o o vctor
- <%,&:7?>\45 th hodlng o o vctor xprssd os on ongl
- /82,2%45 rotot o 2L vctor by on ongl
1h Notur o Cod [v005j
37
- -%/$45 llnor lntrpolot to onothr vctor
- &:#245 th Luclldon dlstonc btwn two vctors [consldrd os polntsj
- ,7?-%W%2;%%745 lnd th ongl btwn two vctors
- &8245 th dot product o two vctors
- 0/8##45 th cross product o two vctors [only rlvont ln thr dlmnslonsj
- /,7&89>\45 - mok o rondom 2L vctor
- /,7&89H\45 - mok o rondom 3L vctor
Hovlng olrody covrd oddltlon, lt`s stort wlth subtroctlon. 1hls on`s not so bod, just tok
th plus slgn ond rploc lt wlth o mlnus!
R(2'*. -:)'.42'&*; R(2'*. -:)'.42'&*;
#

con b wrlttn os.


#
"
!
"
$
"
#
%
!
%
$
%
ond so th unctlon lnsld ]`%028/ looks llk.
1h ollowlng xompl dmonstrots vctor subtroctlon by toklng th dlrnc btwn
two polntsth mous locotlon ond th cntr o th wlndow.
Iiure :.;: Vector Subtrcction
A8:& #3I4]`%028/ A5 1
! ' ! 6 AN!*
" ' " 6 AN"*
@
Choptr J. Vctors
38
IJ&7:5# ;K=L Q#0'*) 8(E')&0'/*1
b4-&2 X:E)(. 5.*Q(.'&(- 8&', R(2'*.- b4-&2 X:E)(. 5.*Q(.'&(- 8&', R(2'*.-
Both oddltlon ond subtroctlon wlth vctors ollow th som olgbrolc ruls os wlth rol
numbrs.
*+$ %!--:&(&/0$ 1:'$3 *+$ %!--:&(&/0$ 1:'$3 !

*+$ ())!%/(&/0$ 1:'$3 *+$ ())!%/(&/0$ 1:'$3 !

( $

) ( !

) #

|oncy trmlnology ond symbols osld, thls ls rolly qult o slmpl concpt. W`r just
soylng thot common sns proprtls o oddltlon opply to vctors os wll.
3 2 2 3
(3 2) 1 3 (2 1)
A8:& #%23$45 1
#:F%4>BBC>BB5*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
Two PVectors, one for the mouse location
and one for the center of the window
]`%028/ 983#% ' 7%; ]`%028/4983#%eC983#%f5*
]`%028/ 0%72%/ ' 7%; ]`%028/4;:&2<=>C<%:?<2=>5*
PVector subtraction! 983#%N#3I40%72%/5*
Draw a line to represent the vector. 2/,7#-,2%4;:&2<=>C<%:?<2=>5*
-:7%4BCBC983#%N!C983#%N"5*
@
1h Notur o Cod [v005j
39
R(2'*. E:%'&Q%&24'&*; R(2'*. E:%'&Q%&24'&*;
Movlng on to multlpllcotlon, w hov to thlnk o llttl blt dlrntly. Whn w tolk obout
multlplylng o vctor, whot w typlcolly mon ls )%('/.2 )%('/.2 o vctor. | w wontd to scol o
vctor to twlc lts slz or on-thlrd o lts slz [lovlng lts dlrctlon th somj, w would soy.
Multlply th vctor by 2" or Multlply th vctor by J/3." Not thot w or multlplylng o
vctor by o scolor, o slngl numbr, not onothr vctor.
1o scol o vctor, w multlply och componnt [! ond "j by o scolor.
#

* &
con b wrlttn os.
#
"
!
"
* &
#
%
!
%
* &
Lt`s look ot on xompl wlth vctor
nototlon.
!

(3, 7)
& 3
#

* &
#
"
3 * 3
#
%
7 * 3
#

(9, 21)
1hror, th unctlon lnsld th ]`%028/
closs ls wrlttn os.
And lmplmntlng multlpllcotlon ln cod ls os slmpl os.
Iiure :.8: Scclin c tector
A8:& 93-24E-8,2 75 1
With multiplication, the components of the
vector are multiplied by a number.
! ' ! Q 7*
" ' " Q 7*
@
]`%028/ 3 ' 7%; ]`%028/46HCO5*
This PVector is now three times the size
and is equal to (-9,21).
3N93-24H5*
Choptr J. Vctors
40
IJ&7:5# ;K>L P(5'/:5U/16 & N#0'*)
Llvlslon works just llk multlpllcotlonw
slmply rploc th multlpllcotlon slgn
[ostrlskj wlth th dlvlslon slgn [orword
sloshj.
A8:& #%23$45 1
#:F%4>BBC>BB5*
#9882<45*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
]`%028/ 983#% ' 7%; ]`%028/4983#%eC983#%f5*
]`%028/ 0%72%/ ' 7%; ]`%028/4;:&2<=>C<%:?<2=>5*
983#%N#3I40%72%/5*
Multiplying a vector! The vector is now half
its original size (multiplied by 0.5).
983#%N93-24BNJ5*
2/,7#-,2%4;:&2<=>C<%:?<2=>5*
-:7%4BCBC983#%N!C983#%N"5*
@
Iiure :.p
A8:& &:A4E-8,2 75 1
! ' ! = 7*
" ' " = 7*
@
]`%028/ 3 ' 7%; ]`%028/4XC6D5*
1h Notur o Cod [v005j
4J
]*.( X:E)(. 5.*Q(.'&(- 8&', R(2'*.- ]*.( X:E)(. 5.*Q(.'&(- 8&', R(2'*.-
As wlth oddltlon, boslc olgbrolc ruls o multlpllcotlon ond dlvlslon opply to vctors.
1h ossoclotlv rul. (& * ') * $

& * ('* $

)
1h dlstrlbutlv rul wlth 2 scolors, J vctor. (& * ') * $

& * $

'* $

1h dlstrlbutlv rul wlth 2 vctors, J scolor. ( !

) * & !

* & $

* &
Dividing a vector! The vector is now half its
original size (divided by 2).
3N&:A4>5*
#"? R(2'*. ]4<;&':9( #"? R(2'*. ]4<;&':9(
Multlpllcotlon ond dlvlslon, os w just sow, or mons by whlch th lngth o th vctor con
b chongd wlthout octlng dlrctlon. Prhops you`r wondrlng. OK, so how do | know
whot th lngth o o vctor ls? | know th componnts [! ond "j, but how long [ln plxlsj ls
th octuol orrow?" ndrstondlng how to colculot th lngth [olso known os -(2./&:8$ -(2./&:8$j o
o vctor ls lncrdlbly usul ond lmportont.
Notlc ln th obov dlogrom how th
vctor, drown os on orrow ond two
componnts [! ond "j, crots o rlght
trlongl. 1h slds or th componnts ond
th hypotnus ls th orrow ltsl. W`r
vry lucky to hov thls rlght trlongl,
bcous onc upon o tlm, o Grk
mothmotlclon nomd Pythogoros
dvlopd o lovly ormulo to dscrlb th
rlotlonshlp btwn th slds ond
hypotnus o o rlght trlongl.
1h Pythogoron thorm ls o squord
plus b squord quols c squord.
Armd wlth thls ormulo, w con now
comput th mognltud o $

os ollows.
! $

! $
"
* $
"
$
%
* $
%
or ln ]`%028/.
Iiure :.:o: The lenth or mcnitude oj c
tector t( is ojten uritten cs: !t(!
Iiure :.::: The Pthcorecn Theorem
Choptr J. Vctors
42
IJ&7:5# ;K?L Q#0'*) 7&61/'(-#
E-8,2 9,?45 1
/%23/7 #g/24!Q! ( "Q"5*
@
A8:& #%23$45 1
#:F%4>BBC>BB5*
#9882<45*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
]`%028/ 983#% ' 7%; ]`%028/4983#%eC983#%f5*
]`%028/ 0%72%/ ' 7%; ]`%028/4;:&2<=>C<%:?<2=>5*
983#%N#3I40%72%/5*
The magnitude (i.e. length) of a vector can
be accessed via the mag() function. Here it
is used as the width of a rectangle drawn at
the top of the window.
E-8,2 9 ' 983#%N9,?45*
E:--4B5*
/%024BCBC9C)B5*
2/,7#-,2%4;:&2<=>C<%:?<2=>5*
-:7%4BCBC983#%N!C983#%N"5*
@
#"K X*.E4%&c&;< R(2'*.- #"K X*.E4%&c&;< R(2'*.-
Colculotlng th mognltud o o vctor ls only th bglnnlng. 1h mognltud unctlon opns
th door to mony posslbllltls, th lrst o whlch ls .!1-('/C(&/!. .!1-('/C(&/!.. Normollzlng rrs to th
procss o moklng somthlng stondord" or, wll, normol." |n th cos o vctors, lt`s
ossum or th momnt thot o stondord vctor hos o lngth o J. 1o normollz o vctor,
1h Notur o Cod [v005j
43
thror, ls to tok o vctor o ony lngth ond, kplng lt polntlng ln th som dlrctlon,
chong lts lngth to J, turnlng lt lnto whot ls colld o :./& 0$%&!1 :./& 0$%&!1.
5lnc lt dscrlbs o vctor`s dlrctlon
wlthout rgord to lts lngth, lt`s usul to
hov th unlt vctor rodlly occsslbl.
W`ll s thls com ln hondy onc w stort
to work wlth orcs ln Choptr 2.
|or ony glvn vctor !

, lts unlt vctor


[wrlttn os !
"
j ls colculotd os ollows.
!
"

!

! !

!
|n othr words, to normollz o vctor, slmply dlvld och componnt by lts mognltud. 1hls
ls prtty lntultlv. 5oy o vctor ls o lngth 5. Wll, 5 dlvldd by 5 ls J. 5o, looklng ot our
rlght trlongl, w thn nd to scol th hypotnus down by dlvldlng by 5. |n thot procss
th slds shrlnk, dlvldd by 5 os wll.
|n th ]`%028/ closs, w thror wrlt
our normollzotlon unctlon os ollows.
O cours, thr`s on smoll lssu. Whot l th mognltud o th vctor ls 0? W con`t dlvld
by 0! 5om qulck rror chcklng wlll lx thot rlght up.
Iiure :.:z
Iiure :.:
A8:& 78/9,-:F%45 1
E-8,2 9 ' 9,?45*
&:A495*
@
A8:& 78/9,-:F%45 1
E-8,2 9 ' 9,?45*
:E 49 S' B5 1
&:A495*
@
@
Choptr J. Vctors
44
IJ&7:5# ;K@L %*)7&5/V/16 & N#0'*)
A8:& &/,;45 1
I,0.?/837&4>JJ5*
]`%028/ 983#% ' 7%; ]`%028/4983#%eC983#%f5*
]`%028/ 0%72%/ ' 7%; ]`%028/4;:&2<=>C<%:?<2=>5*
983#%N#3I40%72%/5*
n this example, after the vector is
normalized, it is multiplied by 50 so that it is
viewable onscreen. Note that no matter
where the mouse is, the vector will have the
same length (50) due to the normalization
process.
983#%N78/9,-:F%45*
983#%N93-24JB5*
2/,7#-,2%4;:&2<=>C<%:?<2=>5*
-:7%4BCBC983#%N!C983#%N"5*
@
#"L R(2'*. ]*'&*;D R(%*2&'/ #"L R(2'*. ]*'&*;D R(%*2&'/
All thls vctor moth stu sounds llk somthlng w should know obout, but why? How wlll lt
octuolly hlp us wrlt cod? 1h truth o th mottr ls thot w nd to hov som potlnc. |t
wlll tok som tlm bor th owsomnss o uslng th ]`%028/ closs ully coms to llght.
1hls ls octuolly o common occurrnc whn lrst lornlng o nw doto structur. |or xompl,
whn you lrst lorn obout on orroy, lt mlght sm llk much mor work to us on orroy thon to
just hov svrol vorlobls stond or multlpl thlngs. But thot plon qulckly broks down whn
you nd o hundrd, or o thousond, or tn thousond thlngs. 1h som con b tru or
]`%028/. Whot mlght sm llk mor work now wlll poy o lotr, ond poy o qult nlcly. And
you don`t hov to wolt too long, os your rword wlll com ln th nxt choptr.
|or now, howvr, w wont to ocus on slmpllclty. Whot dos lt mon to progrom motlon uslng
vctors? W`v sn th bglnnlng o thls ln Lxompl J.2 [s pog 35j. th bounclng boll. An
objct on scrn hos o locotlon [whr lt ls ot ony glvn momntj os wll os o vloclty
[lnstructlons or how lt should mov rom on momnt to th nxtj. Vloclty ls oddd to
locotlon.
1h Notur o Cod [v005j
45
And thn w drow th objct ot thot locotlon.
1hls ls Motlon J0J.
J. D88 0$'!%/&@ &! '!%(&/!. D88 0$'!%/&@ &! '!%(&/!.
2. E1(> !"#$%& (& '!%(&/!. E1(> !"#$%& (& '!%(&/!.
|n th bounclng boll xompl, oll o thls cod hoppnd ln Procsslng`s moln tob, wlthln
#%23$45 ond &/,;45. Whot w wont to do now ls mov towords ncopsulotlng oll o th
loglc or motlon lnsld o o %'()) %'()). 1hls woy, w con crot o oundotlon or progrommlng
movlng objcts ln Procsslng. |n sctlon |.2 o th lntroductlon [s pog 2j, 1h Rondom
Wolkr Closs," w brlly rvlwd th boslcs o objct-orlntd-progrommlng [OOP"j.
Byond thot short lntroductlon, thls book ossums xprlnc wlth objcts ond closss ln
Procsslng. | you nd o rrshr, | ncourog you to chck out th Procsslng objcts
tutorlol [http.//procsslng.org/lornlng/objcts/j.
|n thls cos, w`r golng to crot o gnrlc d8A%/ closs thot wlll dscrlb o thlng movlng
oround th scrn. And so w must consldr th ollowlng two qustlons.
J. F+(& 8(&( 8!$) ( -!0$1 +(0$G F+(& 8(&( 8!$) ( -!0$1 +(0$G
2. F+(& ;:.%&/!.('/&@ 8!$) ( -!0$1 +(0$G F+(& ;:.%&/!.('/&@ 8!$) ( -!0$1 +(0$G
Our Motlon J0J olgorlthm tlls us th onswrs to ths qustlons. A d8A%/ objct hos two
plcs o doto. -80,2:87 ond A%-80:2", whlch or both ]`%028/ objcts.
|ts unctlonollty ls just obout os slmpl. 1h d8A%/ nds to mov ond lt nds to b sn.
W`ll lmplmnt ths nds os unctlons nomd 3$&,2%45 ond &:#$-,"45. W`ll put oll o
our motlon loglc cod ln 3$&,2%45 ond drow th objct ln &:#$-,"45.
-80,2:87N,&&4A%-80:2"5*
%--:$#%4-80,2:87N!C-80,2:87N"C)GC)G5*
0-,## d8A%/ 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
A8:& 3$&,2%45 1
The Mover moves. -80,2:87N,&&4A%-80:2"5*
@
A8:& &:#$-,"45 1
#2/8.%4B5*
E:--4)OJ5*
Choptr J. Vctors
46
W`v orgottn on cruclol ltm, howvr. th objct`s %!.)&1:%&!1 %!.)&1:%&!1. 1h constructor ls o
spclol unctlon lnsld o o closs thot crots th lnstonc o th objct ltsl. |t ls whr you
glv lnstructlons on how to st up th objct. |t olwoys hos th som nom os th closs ond ls
colld by lnvoklng th .$> .$> oprotor.
|n our cos, lt`s orbltrorlly dcld to lnltlollz our d8A%/ objct by glvlng lt o rondom locotlon
ond o rondom vloclty.
| objct-orlntd progrommlng ls ot oll nw to you, on ospct hr moy sm o blt
conuslng. Atr oll, w spnt th bglnnlng o thls choptr dlscusslng th ]`%028/ closs. 1h
]`%028/ closs ls th tmplot or moklng th -80,2:87 objct ond th A%-80:2" objct. 5o
whot or thy dolng lnsld o yt onothr objct, th d8A%/ objct? |n oct, thls ls just obout
th most normol thlng vr. An objct ls slmply somthlng thot holds doto [ond unctlonolltyj.
1hot doto con b numbrs [lntgrs, loots, tc.j or othr objcts! W`ll s thls ovr ond ovr
ogoln ln thls book. |or xompl, ln Choptr 4 [s pog J44j w`ll wrlt o closs to dscrlb o
systm o portlcls. 1hot ],/2:0-%["#2%9 objct wlll hov os lts doto o llst o ],/2:0-%
objcts.ond och ],/2:0-% objct wlll hov os lts doto svrol ]`%028/ objcts!
Lt`s lnlsh o th d8A%/ closs by lncorporotlng o unctlon to dtrmln whot th objct should
do whn lt rochs th dg o th wlndow. |or now lt`s do somthlng slmpl, ond just hov
lt wrop oround th dgs.
The Mover is displayed. %--:$#%4-80,2:87N!C-80,2:87N"C)GC)G5*
@
@
d8A%/ 9 ' 7%; d8A%/45*
d8A%/45 1
-80,2:87 ' 7%; ]`%028/4/,7&894;:&2<5C/,7&894<%:?<255*
A%-80:2" ' 7%; ]`%028/4/,7&8946>C>5C/,7&8946>C>55*
@
A8:& 0<%0.h&?%#45 1
When it reaches one edge, set location to
the other.
:E 4-80,2:87N! ^ ;:&2<5 1
-80,2:87N! ' B*
@ %-#% :E 4-80,2:87N! P B5 1
-80,2:87N! ' ;:&2<*
@
:E 4-80,2:87N" ^ <%:?<25 1
-80,2:87N" ' B*
@ %-#% :E 4-80,2:87N" P B5 1
-80,2:87N" ' <%:?<2*
@
1h Notur o Cod [v005j
47
Now thot th d8A%/ closs ls lnlshd, w con look ot whot w nd to do ln our moln
progrom. W lrst dclor o d8A%/ objct.
1hn lnltlollz th movr ln #%23$45.
ond coll th opproprlot unctlons ln &/,;45.
Hr ls th ntlr xompl or rrnc.
IJ&7:5# ;KAL P*'/*1 ;D; WN#5*0/'UX
@
d8A%/ 98A%/*
98A%/ ' 7%; d8A%/45*
98A%/N3$&,2%45*
98A%/N0<%0.h&?%#45*
98A%/N&:#$-,"45*
Declare Mover object. d8A%/ 98A%/*
A8:& #%23$45 1
#:F%4>BBC>BB5*
#9882<45*
Create Mover object. 98A%/ ' 7%; d8A%/45*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
Choptr J. Vctors
48
Call functions on Mover object. 98A%/N3$&,2%45*
98A%/N0<%0.h&?%#45*
98A%/N&:#$-,"45*
@
0-,## d8A%/ 1
Our object has two PVectors: location and
velocity.
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
d8A%/45 1
-80,2:87 ' 7%; ]`%028/4/,7&894;:&2<5C/,7&894<%:?<255*
A%-80:2" ' 7%; ]`%028/4/,7&8946>C>5C/,7&8946>C>55*
@
A8:& 3$&,2%45 1
Motion 101: Location changes by velocity. -80,2:87N,&&4A%-80:2"5*
@
A8:& &:#$-,"45 1
#2/8.%4B5*
E:--4)OJ5*
%--:$#%4-80,2:87N!C-80,2:87N"C)GC)G5*
@
A8:& 0<%0.h&?%#45 1
:E 4-80,2:87N! ^ ;:&2<5 1
-80,2:87N! ' B*
@ %-#% :E 4-80,2:87N! P B5 1
-80,2:87N! ' ;:&2<*
@
:E 4-80,2:87N" ^ <%:?<25 1
-80,2:87N" ' B*
@ %-#% :E 4-80,2:87N" P B5 1
-80,2:87N" ' <%:?<2*
@
@
@
#"N R(2'*. ]*'&*;D !22(%(.4'&*; #"N R(2'*. ]*'&*;D !22(%(.4'&*;
OK. At thls polnt, w should l comortobl wlth two thlngs. [Jj whot o ]`%028/ ls ond [2j how
w us ]`%028/s lnsld o on objct to kp trock o lts locotlon ond movmnt. 1hls ls on
xcllnt lrst stp ond dsrvs o mlld round o opplous. Bor stondlng ovotlons ond
scromlng ons, howvr, w nd to mok on mor, somwhot blggr stp orword. Atr
oll, wotchlng th Motlon J0J xompl ls olrly borlngth clrcl nvr spds up, nvr slows
1h Notur o Cod [v005j
49
down, ond nvr turns. |or mor lntrstlng motlon, or motlon thot oppors ln th rol
world oround us, w nd to odd on mor ]`%028/ to our closs,00%-%/,2:87.
1h strlct dlnltlon o (%%$'$1(&/!. (%%$'$1(&/!. w`r uslng hr ls. the tote ot chonge ot ve|oc|ty. Lt`s
thlnk obout thot dlnltlon or o momnt. |s thls o nw concpt? Not rolly. Vloclty ls
dlnd os the tote ot chonge ot |ocot|on. |n ssnc, w or dvloplng o trlckl-down"
ct. Acclrotlon octs vloclty, whlch ln turn octs locotlon [or som brl
orshodowlng, thls polnt wlll bcom vn mor cruclol ln th nxt choptr, whn w s
how orcs oct occlrotlon, whlch octs vloclty, whlch octs locotlonj. |n cod, thls
rods.
As on xrcls, rom thls polnt orword, lt`s mok o rul or ourslvs. Lt`s wrlt vry
xompl ln th rst o thls book wlthout vr touchlng th volu o vloclty ond locotlon
[xcpt to lnltlollz thmj. |n othr words, our gool now or progrommlng motlon ls. Com up
wlth on olgorlthm or how w colculot occlrotlon ond lt th trlckl-down ct work lts
moglc. [|n truth, you`ll lnd rosons to brok thls rul, but lt`s lmportont to lllustrot th
prlnclpls bhlnd our motlon olgorlthm.j And so w nd to com up wlth som woys to
colculot occlrotlon.
A%-80:2"N,&&4,00%-%/,2:875*
-80,2:87N,&&4A%-80:2"5*
!22(%(.4'&*; !%<*.&',E-J !22(%(.4'&*; !%<*.&',E-J
J. A constont occe|etot|on
2. A toto||y tondom occe|etot|on
3. Acce|etot|on towotds the mouse
Algorlthm #J, o constont occe|etot|on, ls not portlculorly lntrstlng, but lt ls th slmplst
ond wlll hlp us bgln lncorporotlng occlrotlon lnto our cod. 1h lrst thlng w nd to
do ls odd onothr ]`%028/ to th d8A%/ closs.
And lncorporot occlrotlon lnto th 3$&,2%45 unctlon.
0-,## d8A%/ 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
A new PVector for acceleration MN$:/8) &::$'$)&/28#,
A8:& 3$&,2%45 1
Our motion algorithm is now two lines of
code!
L$'8:2/3-&11*&::$'$)&/28#+,
-80,2:87N,&&4A%-80:2"5*
@
Choptr J. Vctors
50
W`r olmost don. 1h only mlsslng plc ls lnltlollzotlon ln th constructor.
Lt`s stort th d8A%/ objct ln th mlddl o th wlndow.
.wlth on lnltlol vloclty o zro.
1hls mons thot whn th sktch storts, th objct ls ot rst. W don`t hov to worry obout
vloclty onymor, os w or controlllng th objct`s motlon ntlrly wlth occlrotlon.
5poklng o whlch, occordlng to Algorlthm #J, our lrst sktch lnvolvs constont occlrotlon.
5o lt`s plck o volu.
Moyb you`r thlnklng, Gosh, thos volus sm owully smoll!" 1hot`s rlght, thy or qult
tlny. |t`s lmportont to rollz thot our occlrotlon volus [mosurd ln plxlsj occumulot ovr
tlm ln th vloclty, obout thlrty tlms pr scond dpndlng on our sktch`s rom rot. And
so to kp th mognltud o th vloclty vctor wlthln o rosonobl rong, our occlrotlon
volus should rmoln qult smoll. W con olso hlp thls cous by lncorporotlng th ]`%028/
unctlon -:9:245.
1hls tronslots to th ollowlng.
hot |s the mogn|tude ot ve|oc|ty? lt |ts |ess thon !0, no wott|es, ust |eove |t os |s. lt |ts mote
thon !0, howevet, teduce |t to !0|
d8A%/45 1
-80,2:87 ' 7%; ]`%028/4;:&2<=>C<%:?<2=>5*
A%-80:2" ' 7%; ]`%028/4BCB5*
,00%-%/,2:87 ' 7%; ]`%028/46BNBB)CBNB)5*
@
The limit() function constrains the magnitude
of a vector.
A%-80:2"N-:9:24)B5*
1h Notur o Cod [v005j
5J
Lt`s tok o look ot th chongs to th d8A%/ closs, complt wlth ,00%-%/,2:87 ond
-:9:245.
IJ&7:5# ;KBL P*'/*1 ;D; WN#5*0/'U &1- 0*18'&1' &00#5#)&'/*1X
Wrlt th -:9:245 unctlon or th ]`%028/ closs.
A8:& -:9:24E-8,2 9,!5 1
:E 4aaaaaaa ^ aaaaaaa5 1
aaaaaaaaa45*
aaaa49,!5*
@
@
MO(.2&-( #"> MO(.2&-( #">
0-,## d8A%/ 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
Acceleration is the key! ]`%028/ ,00%-%/,2:87*
The variable topspeed will limit the
magnitude of velocity.
E-8,2 28$#$%%&*
d8A%/45 1
-80,2:87 ' 7%; ]`%028/4;:&2<=>C<%:?<2=>5*
A%-80:2" ' 7%; ]`%028/4BCB5*
,00%-%/,2:87 ' 7%; ]`%028/46BNBB)CBNB)5*
28$#$%%& ' )B*
@
A8:& 3$&,2%45 1
Velocity changes by acceleration and is
limited by topspeed.
A%-80:2"N,&&4,00%-%/,2:875*
A%-80:2"N-:9:2428$#$%%&5*
Choptr J. Vctors
52
Now on to Algorlthm #2, o toto||y tondom occe|etot|on. |n thls cos, lnstod o lnltlollzlng
occlrotlon ln th objct`s constructor, w wont to plck o nw occlrotlon och cycl, l..
och tlm 3$&,2%45 ls colld.
IJ&7:5# ;KCL P*'/*1 ;D; WN#5*0/'U &1- )&1-*7 &00#5#)&'/*1X
Bcous th rondom vctor ls o normollzd on, w con try scollng lt.
[oj scollng th occlrotlon to o constont volu
-80,2:87N,&&4A%-80:2"5*
@
display() is the same. A8:& &:#$-,"45 1@
checkEdges() is the same. A8:& 0<%0.h&?%#45 1@
@
Crot o slmulotlon o o cor [or runnrj thot occlrots whn you prss th up ky ond
broks whn you prss th down ky.
MO(.2&-( #"? MO(.2&-( #"?
A8:& 3$&,2%45 1
The random2D() function will give us a
PVector of length 1 pointing in a random
direction.
,00%-%/,2:87 ' ]`%028/N/,7&89>\45*
A%-80:2"N,&&4,00%-%/,2:875*
A%-80:2"N-:9:2428$#$%%&5*
-80,2:87N,&&4A%-80:2"5*
@
,00%-%/,2:87 ' ]`%028/N/,7&89>\45*
1h Notur o Cod [v005j
53
[bj scollng th occlrotlon to o rondom volu
Whll thls moy sm llk on obvlous polnt, lt`s cruclol to undrstond thot occlrotlon dos
not mrly rr to th speed|ng up or s|ow|ng down o o movlng objct, but rothr ony
chonge ln vloclty ln lthr mognltud or dlrctlon. Acclrotlon ls usd to str on objct,
ond w`ll s thls ogoln ond ogoln ln utur choptrs os w bgln to progrom objcts thot
mok dclslons obout how to mov obout th scrn.
Constant &::$'$)&/28#-54'/*?-=+,
,00%-%/,2:87 ' ]`%028/N/,7&89>\45*
Random &::$'$)&/28#-54'/*)&#185*>++,
Rrrlng bock to th |ntroductlon [s pog J7j, lmplmnt occlrotlon occordlng to
Prlln nols.
MO(.2&-( #"K MO(.2&-( #"K
#"W U'4'&2 I-" X*;ZU'4'&2 S:;2'&*;- #"W U'4'&2 I-" X*;ZU'4'&2 S:;2'&*;-
Bor w gt to Algorlthm #3 [occe|etote towotds the mousej, w nd to covr on mor
rothr lmportont ospct o worklng wlth vctors ond th ]`%028/ closs. th dlrnc
btwn uslng )&(&/% )&(&/% mthods ond .!.H)&(&/% .!.H)&(&/% mthods.
|orgttlng obout vctors or o momnt, tok o look ot th ollowlng cod.
Prtty slmpl, rlght? ! hos th volu o 0, w odd " to lt, ond now ! ls quol to 5. W could
wrlt th corrspondlng cod prtty oslly bosd on whot w`v lornd obout ]`%028/.
1h vctor A hos th volu o [0,0j, w odd 3 to lt, ond now A ls quol to [4,5j. Losy, rlght?
Lt`s tok o look ot onothr xompl o som slmpl lootlng polnt moth.
E-8,2 ! ' B*
E-8,2 " ' J*
! ' ! ( "*
]`%028/ A ' 7%; ]`%028/4BCB5*
]`%028/ 3 ' 7%; ]`%028/4DCJ5*
AN,&&435*
Choptr J. Vctors
54
! hos th volu o 0, w odd " to lt, ond stor th rsult ln o nw vorlobl F. 1h volu o !
dos not chong ln thls xompl [nlthr dos "j! 1hls moy sm llk o trlvlol polnt, ond on
thot ls qult lntultlv whn lt coms to mothmotlcol oprotlons wlth loots. Howvr, lt`s not
so obvlous wlth mothmotlcol oprotlons ln ]`%028/. Lt`s try to wrlt th cod bosd on whot
w know so or.
1h obov mlght sm llk o good guss, but lt`s just not th woy th ]`%028/ closs works. |
w look ot th dlnltlon o ,&&45 . . .
w s thot thls cod dos not occompllsh our gool. |lrst, lt dos not rturn o nw ]`%028/
[th rturn typ ls vold"j ond scond, lt chongs th volu o th ]`%028/ upon whlch lt ls
colld. |n ordr to odd two ]`%028/ objcts togthr ond rturn th rsult os o nw ]`%028/,
w must us th stotlc ,&&45 unctlon.
|unctlons thot w coll rom th closs nom ltsl [rothr thon rom o spclnc objct lnstoncj
or known os )&(&/% ;:.%&/!.) )&(&/% ;:.%&/!.). Hr or two xompls o unctlon colls thot ossum two
]`%028/ objcts, A ond 3.
5lnc you con`t wrlt stotlc unctlons yoursl ln Procsslng, you mlght not hov ncountrd
thm bor. ]`%028/'s stotlc unctlons ollow us to prorm gnrlc mothmotlcol oprotlons
on ]`%028/ objcts wlthout hovlng to odjust th volu o on o th lnput ]`%028/s. Lt`s look
ot how w mlght wrlt th stotlc vrslon o ,&&45.
E-8,2 ! ' B*
E-8,2 " ' J*
E-8,2 F ' ! ( "*
]`%028/ A ' 7%; ]`%028/4BCB5*
]`%028/ 3 ' 7%; ]`%028/4DCJ5*
Don't be fooled; this is incorrect!!! ]`%028/ ; ' AN,&&435*
A8:& ,&&4]`%028/ A5 1
! ' ! ( AN!*
" ' " ( AN"*
@
Static: called from the class name. ]`%028/N,&&4AC35*
Not static: called from an object instance. AN,&&435*
1h Notur o Cod [v005j
55
1hr or svrol dlrncs hr.
- 1h unctlon ls lobld os )&(&/% )&(&/%.
- 1h unctlon dos not hov o 0!/8 0!/8 rturn typ, but rothr rturns o ]`%028/.
- 1h unctlon crots o nw ]`%028/ [AHj ond rturns th sum o th componnts
o A) ond A> ln thot nw ]`%028/.
Whn you coll o stotlc unctlon, lnstod o rrnclng on octuol objct lnstonc, you slmply
rrnc th nom o th closs ltsl.
1h ]`%028/ closs hos stotlc vrslons o ,&&45, #3I45, 93-245, ond &:A45.
The static version of add allows us to add
two PVectors together and assign the
result to a new PVector while leaving the
original PVectors (v and u above) intact.
#2,2:0 ]`%028/ ,&&4]`%028/ A)C ]`%028/ A>5 1
]`%028/ AH ' 7%; ]`%028/4A)N! ( A>N!C A)N" ( A>N"5*
/%23/7 AH*
@
]`%028/ A ' 7%; ]`%028/4BCB5*
]`%028/ 3 ' 7%; ]`%028/4DCJ5*
]`%028/ ; ' AN,&&435*
MN$:/8) ! " MN$:/8)-&11*LJ4+,
1ronslot th ollowlng psudocod to cod uslng stotlc or non-stotlc unctlons whr
opproprlot.
- 1h ]`%028/ A quols [J,5j.
- 1h ]`%028/ 3 quols A multlplld by 2.
- 1h ]`%028/ ; quols A mlnus 3.
- Llvld th ]`%028/ w by 3.
]`%028/ A ' 7%; ]`%028/4)CJ5*
]`%028/ 3 ' aaaaaaaaNaaaaa4aaCaa5*
]`%028/ ; ' aaaaaaaaNaaaaa4aaCaa5*
aaaaaaaaaaa*
MO(.2&-( #"L MO(.2&-( #"L
Choptr J. Vctors
56
#"#T C;'(.42'&I&'/ 8&', !22(%(.4'&*; #"#T C;'(.42'&I&'/ 8&', !22(%(.4'&*;
1o lnlsh out thls choptr, lt`s try somthlng
o blt mor complx ond o grot dol mor
usul. W`ll dynomlcolly colculot on
objct`s occlrotlon occordlng to o rul
stotd ln Algorlthm #3 the obect
occe|etotes towotds the mouse.
Anytlm w wont to colculot o vctor bosd
on o rul or o ormulo, w nd to comput
two thlngs. -(2./&:8$ -(2./&:8$ ond 8/1$%&/!. 8/1$%&/!.. Lt`s stort wlth dlrctlon. W know th occlrotlon
vctor should polnt rom th objct`s locotlon towords th mous locotlon. Lt`s soy th objct
ls locotd ot th polnt [!,"j ond th mous ot [983#%e,983#%fj.
|n |lgur J.J5, w s thot w con gt o
vctor [&!,&"j by subtroctlng th objct`s
locotlon rom th mous`s locotlon.
- 1I " 584.$V T I
- 13 " 584.$W T 3
Lt`s rwrlt th obov uslng ]`%028/
syntox. Assumlng w or ln th d8A%/ closs
ond thus hov occss to th objct`s ]`%028/ -80,2:87, w thn hov.
W now hov o ]`%028/ thot polnts rom th movr`s locotlon oll th woy to th mous. | th
objct wr to octuolly occlrot uslng thot vctor, lt would oppor lnstontonously ot th
mous locotlon. 1hls dos not mok or good onlmotlon, o cours, ond whot w wont to do
now ls dcld how qulckly thot objct should occlrot toword th mous.
|n ordr to st th mognltud [whotvr lt moy bj o our occlrotlon ]`%028/, w must lrst
___ thot dlrctlon vctor. 1hot`s rlght, you sold lt. Notmo||ze. | w con shrlnk th vctor down
to lts unlt vctor [o lngth onj thn w hov o vctor thot tlls us th dlrctlon ond con oslly
b scold to ony volu. On multlplld by onythlng quols onythlng.
Iiure :.:(
Iiure :.:
]`%028/ 983#% ' 7%; ]`%028/4983#%eC983#%f5*
Look! We're using the static reference to
sub() because we want a new PVector
pointing from one point to another.
]`%028/ &:/ ' ]`%028/N#3I4983#%C-80,2:875*
E-8,2 ,7"2<:7? ' iiiii
&:/N78/9,-:F%45*
&:/N93-24,7"2<:7?5*
1h Notur o Cod [v005j
57
1o summorlz, w tok th ollowlng stps.
J. Colculot o vctor thot polnts rom th objct to th torgt locotlon [mousj
2. Normollz thot vctor [rduclng lts lngth to Jj
3. 5col thot vctor to on opproprlot volu [by multlplylng lt by som voluj
4. Asslgn thot vctor to occlrotlon
And hr or thos stps ln th 3$&,2%45 unctlon ltsl.
IJ&7:5# ;K;DL 200#5#)&'/16 '*4&)-8 '"# 7*(8#
You moy b wondrlng why th clrcl dosn`t stop whn lt rochs th torgt. |t`s lmportont
to not thot th objct movlng hos no knowldg obout trylng to stop ot o dstlnotlon, lt
only knows whr th dstlnotlon ls ond trls to go thr os qulckly os posslbl. Golng os
A8:& 3$&,2%45 1
]`%028/ 983#% ' 7%; ]`%028/4983#%eC983#%f5*
Step 1: Compute direction ]`%028/ &:/ ' ]`%028/N#3I4983#%C-80,2:875*
Step 2: Normalize &:/N78/9,-:F%45*
Step 3: Scale &:/N93-24BNJ5*
Step 4: Accelerate ,00%-%/,2:87 ' &:/*
A%-80:2"N,&&4,00%-%/,2:875*
A%-80:2"N-:9:2428$#$%%&5*
-80,2:87N,&&4A%-80:2"5*
@
Choptr J. Vctors
58
qulckly os posslbl mons lt wlll lnvltobly ovrshoot th locotlon ond hov to turn oround,
ogoln golng os qulckly os posslbl towords th dstlnotlon, ovrshootlng lt ogoln, ond so on
ond so orth. 5toy tund, ln lotr choptrs w`ll lorn how to progrom on objct to (11/0$ (11/0$ ot o
locotlon [slow down on opproochj.
1hls xompl ls rmorkobly clos to th concpt o grovltotlonol ottroctlon [ln whlch th objct
ls ottroctd to th mous locotlonj. Grovltotlonol ottroctlon wlll b covrd ln mor dtoll ln th
nxt choptr. Howvr, on thlng mlsslng hr ls thot th strngth o grovlty [mognltud o
occlrotlonj ls lnvrsly proportlonol to dlstonc. 1hls mons thot th closr th objct ls to
th mous, th ostr lt occlrots.
Lt`s s whot thls xompl would look llk wlth on orroy o movrs [rothr thon just onj.
IJ&7:5# ;K;;L 2))&U *+ 7*N#)8 &00#5#)&'/16 '*4&)-8 '"# 7*(8#
1ry lmplmntlng th obov xompl wlth o vorlobl mognltud o occlrotlon,
strongr whn lt ls lthr closr or orthr owoy.
MO(.2&-( #"N MO(.2&-( #"N
An array of objects d8A%/KL 98A%/# ' 7%; d8A%/K>BL*
A8:& #%23$45 1
#:F%4>BBC>BB5*
#9882<45*
I,0.?/837&4>JJ5*
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
1h Notur o Cod [v005j
59
nitialize each object in the array. 98A%/#K:L ' 7%; d8A%/45*
@
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
Calling functions on all the objects in the
array
98A%/#K:LN3$&,2%45*
98A%/#K:LN0<%0.h&?%#45*
98A%/#K:LN&:#$-,"45*
@
@
0-,## d8A%/ 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
E-8,2 28$#$%%&*
d8A%/45 1
-80,2:87 ' 7%; ]`%028/4/,7&894;:&2<5C/,7&894<%:?<255*
A%-80:2" ' 7%; ]`%028/4BCB5*
28$#$%%& ' D*
@
A8:& 3$&,2%45 1
Our aIgorithm for caIcuIating
acceIeration:
Find the vector pointing towards the
mouse.
]`%028/ 983#% ' 7%; ]`%028/4983#%eC983#%f5*
]`%028/ &:/ ' ]`%028/N#3I4983#%C-80,2:875*
Normalize. &:/N78/9,-:F%45*
Scale. &:/N93-24BNJ5*
Set to acceleration. ,00%-%/,2:87 ' &:/*
Motion 101! Velocity changes by
acceleration. Location changes by velocity.
A%-80:2"N,&&4,00%-%/,2:875*
A%-80:2"N-:9:2428$#$%%&5*
-80,2:87N,&&4A%-80:2"5*
@
Choptr J. Vctors
60
Display the Mover A8:& &:#$-,"45 1
#2/8.%4B5*
E:--4)OJ5*
%--:$#%4-80,2:87N!C-80,2:87N"C)GC)G5*
@
What to do at the edges A8:& 0<%0.h&?%#45 1
:E 4-80,2:87N! ^ ;:&2<5 1
-80,2:87N! ' B*
@ %-#% :E 4-80,2:87N! P B5 1
-80,2:87N! ' ;:&2<*
@
:E 4-80,2:87N" ^ <%:?<25 1
-80,2:87N" ' B*
@ %-#% :E 4-80,2:87N" P B5 1
-80,2:87N" ' <%:?<2*
@
@
@
1h Notur o Cod [v005j
6J
@,( M2*-/-'(E 5.*G(2' @,( M2*-/-'(E 5.*G(2'
As ment|oned |n the ptetoce, one woy to use th|s boo| |s to bu||d o s|ng|e ptoect
ovet the coutse ot teod|ng |t, |ncotpotot|ng e|ements ttom eoch choptet one step
ot o t|me. e|| to||ow the deve|opment ot on exomp|e ptoect thtoughout th|s
boo|o s|mu|ot|on ot on ecosystem. lmog|ne o popu|ot|on ot computot|ono|
cteotutes sw|mm|ng otound o d|g|to| pond, |ntetoct|ng w|th eoch othet occotd|ng
to vot|ous tu|es.
U'(Q # MO(.2&-(D
\(I(%*Q 4 -(' *+ .:%(- +*. -&E:%4'&;< ',( .(4%Z8*.%9 )(,4I&*. *+ 4 2.(4':.(` -:2, 4-
4 ;(.I*:- +%/` -8&EE&;< +&-,` ,*QQ&;< ):;;/` -%&',(.&;< -;43(` ('2" P4; /*:
2*;'.*% ',( *)G(2'H- E*'&*; )/ *;%/ E4;&Q:%4'&;< ',( 422(%(.4'&*;7 @./ '* <&I( ',(
2.(4':.( 4 Q(.-*;4%&'/ ',.*:<, &'- )(,4I&*. ^.4',(. ',4; ',.*:<, &'- I&-:4% 9(-&<;_"
Iiure :.:: The Ecosstem Project
Choptr J. Vctors
62
,"&:'#) <K G*)0#8 ,"&:'#) <K G*)0#8
Don't underestimcte the Iorce.
! *$24E F$1&2
|n th lnol xompl o Choptr J, w sow how w could colculot o dynomlc occlrotlon
bosd on o vctor polntlng rom o clrcl on th scrn to th mous locotlon. 1h rsultlng
motlon rsmbld o mogntlc ottroctlon btwn clrcl ond mous, os l som totce wr
pulllng th clrcl ln towords th mous. |n thls choptr w wlll ormollz our undrstondlng o
th concpt o o orc ond lts rlotlonshlp to occlrotlon. Our gool, by th nd o thls choptr,
ls to undrstond how to mok multlpl objcts mov oround th scrn ond rspond to o
vorlty o nvlronmntol orcs.
0"# S*.2(- 4;9 X(8'*;H- V48- *+ ]*'&*; 0"# S*.2(- 4;9 X(8'*;H- V48- *+ ]*'&*;
Bor w bgln xomlnlng th proctlcol rolltls o slmulotlng orcs ln cod, lt`s tok o
concptuol look ot whot lt mons to b o orc ln th rol world. Just llk th word vctor,"
orc" ls otn usd to mon o vorlty o thlngs. |t con lndlcot o powrul lntnslty, os ln 5h
pushd th bouldr wlth grot orc" or H spok orcully." 1h dlnltlon o ;!1%$ ;!1%$ thot w
cor obout ls much mor ormol ond coms rom |sooc Nwton`s lows o motlon.
A orc ls o vctor thot couss on objct wlth moss to occlrot.
1h Notur o Cod [v005j
63
1h good nws hr ls thot w rcognlz th lrst port o th dlnltlon. o totce |s o vectot.
1honk goodnss w just spnt o whol choptr lornlng whot o vctor ls ond how to
progrom wlth ]`%028/s!
Lt`s look ot Nwton`s thr lows o motlon ln rlotlon to th concpt o o orc.
X(8'*;H- S&.-' V48 X(8'*;H- S&.-' V48
Nwton`s lrst low ls commonly stotd os.
An objct ot rst stoys ot rst ond on objct ln motlon stoys ln motlon.
Howvr, thls ls mlsslng on lmportont lmnt rlotd to orcs. W could xpond lt by
stotlng.
An objct ot rst stoys ot rst ond on objct ln motlon stoys ln motlon ot o
constont spd ond dlrctlon unlss octd upon by on unboloncd orc.
By th tlm Nwton com olong, th prvolllng thory o motlonormulotd by
Arlstotlwos norly two thousond yors old. |t stotd thot l on objct ls movlng, som sort
o orc ls rqulrd to kp lt movlng. nlss thot movlng thlng ls blng pushd or pulld, lt
wlll slmply slow down or stop. Rlght?
1hls, o cours, ls not tru. |n th obsnc o ony orcs, no orc ls rqulrd to kp on
objct movlng. An objct [such os o bollj tossd ln th orth`s otmosphr slows down
bcous o olr rslstonc [o orcj. An objct`s vloclty wlll only rmoln constont ln th
obsnc o ony orcs or l th orcs thot oct on lt concl och othr out, l.. th nt orc
odds up to zro. 1hls ls otn rrrd to os $9:/'/"1/:- $9:/'/"1/:-. 1h olllng boll wlll roch o trmlnol
vloclty [thot stoys constontj onc th orc o olr rslstonc quols th orc o grovlty.
Iiure z.:: The pendulum doesn't mote beccuse cll the jorces ccncel ecch other out (cdd up to c net
jorce oj zero).
Choptr 2. |orcs
64
|n our Procsslng world, w could rstot Nwton`s lrst low os ollows.
An objct`s PVctor vloclty wlll rmoln constont l lt ls ln o stot o
qulllbrlum.
5klpplng Nwton`s scond low [orguobly th most lmportont low or our purpossj or o
momnt, lt`s mov on to th thlrd low.
X(8'*;H- @,&.9 V48 X(8'*;H- @,&.9 V48
1hls low ls otn stotd os.
|or vry octlon thr ls on quol ond opposlt roctlon.
1hls low rquntly couss som conuslon ln th woy thot lt ls stotd. |or on, lt sounds llk
on orc couss onothr. Ys, l you push somon, thot somon moy oct|ve|y dcld to
push you bock. But thls ls not th octlon ond roctlon w or tolklng obout wlth Nwton`s thlrd
low.
Lt`s soy you push ogolnst o woll. 1h woll dosn`t octlvly dcld to push bock on you. 1hr
ls no orlgln" orc. Your push slmply lncluds both orcs, rrrd to os on octlon/roctlon
polr."
A bttr woy o stotlng th low mlght b.
|orcs olwoys occur ln polrs. 1h two orcs or o quol strngth, but ln
opposlt dlrctlons.
Now, thls stlll couss conuslon bcous lt sounds llk ths orcs would olwoys concl och
othr out. 1hls ls not th cos. Rmmbr, th orcs oct on dlrnt objcts. And just
bcous th two orcs or quol, lt dosn`t mon thot th movmnts or quol [or thot th
objcts wlll stop movlngj.
1ry pushlng on o stotlonory truck. Although th truck ls or mor powrul thon you, unllk o
movlng on, o stotlonory truck wlll nvr ovrpowr you ond snd you lylng bockwords. 1h
orc you xrt on lt ls quol ond opposlt to th orc xrtd on your honds. 1h outcom
dpnds on o vorlty o othr octors. | th truck ls o smoll truck on on lcy downhlll, you`ll
1h Notur o Cod [v005j
65
probobly b obl to gt lt to mov. On th othr hond, l lt`s o vry lorg truck on o dlrt rood
ond you push hord nough [moyb vn tok o runnlng stortj, you could lnjur your hond.
And l you or worlng rollr skots whn you push on thot truck?
You`ll occlrot owoy rom th truck, slldlng olong th rood whll th truck stoys put. Why
do you slld but not th truck? |or on, th truck hos o much lorgr moss [whlch w`ll gt
lnto wlth Nwton`s scond lowj. 1hr or othr orcs ot work too, nomly th rlctlon o
th truck`s tlrs ond your rollr skots ogolnst th rood.
Iiure z.z
X(8'*;H- @,&.9 V48 ^4- -((; ',.*:<, ',( (/(- *+ 5.*2(--&;<_ X(8'*;H- @,&.9 V48 ^4- -((; ',.*:<, ',( (/(- *+ 5.*2(--&;<_
| w colculot o PVctor thot ls o orc o objct A on objct B, w must
olso opply th orcPVctor.mult[,-Jj,thot B xrts on objct A.
W`ll s thot ln th world o Procsslng progrommlng, w don`t olwoys hov to stoy tru to
th obov. 5omtlms, such os ln th cos o s grovltotlonol ottroctlon btwn bodls
[s pog 94j, w`ll wont to modl quol ond opposlt orcs. Othr tlms, such os whn
w`r slmply soylng, Hy, thr`s som wlnd ln th nvlronmnt," w`r not golng to bothr
to modl th orc thot o body xrts bock on th olr. |n oct, w`r not modllng th olr ot
oll! Rmmbr, w or slmply toklng lnsplrotlon rom th physlcs o th noturol world, not
slmulotlng vrythlng wlth prct prclslon.
Choptr 2. |orcs
66
0"0 S*.2(- 4;9 5.*2(--&;<dX(8'*;H- U(2*;9 V48 0"0 S*.2(- 4;9 5.*2(--&;<dX(8'*;H- U(2*;9 V48
4- 4 S:;2'&*; 4- 4 S:;2'&*;
And hr w or ot th most lmportont low or th Procsslng progrommr.
X(8'*;H- U(2*;9 V48 X(8'*;H- U(2*;9 V48
1hls low ls stotd os.
|orc quols moss tlms occlrotlon.
Or.
)

* +

Why ls thls th most lmportont low or us? Wll, lt`s wrlt lt o dlrnt woy.
+

/ *
Acclrotlon ls dlrctly proportlonol to orc ond lnvrsly proportlonol to moss. 1hls mons
thot l you gt pushd, th hordr you or pushd, th ostr you`ll mov [occlrotj. 1h
blggr you or, th slowr you`ll mov.
6(&<,' I-" ]4-- 6(&<,' I-" ]4--
- 1h -()) -()) o on objct ls o mosur o th omount o mottr ln th objct
[mosurd ln kllogromsj.
- F$/2+& F$/2+&, though otn mlstokn or moss, ls tchnlcolly th orc o grovlty on
on objct. |rom Nwton`s scond low, w con colculot lt os moss tlms th
occlrotlon o grovlty [; 9 ' ?j. Wlght ls mosurd ln nwtons.
- E$.)/&@ E$.)/&@ ls dlnd os th omount o moss pr unlt o volum [groms pr cublc
cntlmtr, or xomplj.
Not thot on objct thot hos o moss o on kllogrom on orth would hov o moss o on
kllogrom on th moon. Howvr, lt would wlgh only on-slxth os much.
Now, ln th world o Procsslng, whot ls moss onywoy? Arn`t w dollng wlth plxls? 1o stort
ln o slmplr ploc, lt`s soy thot ln our prtnd plxl world, oll o our objcts hov o moss
quol to J. b/ J b. And so.
1h Notur o Cod [v005j
67
+

1h occlrotlon o on objct ls quol to orc. 1hls ls grot nws. Atr oll, w sow ln
Choptr J thot occlrotlon wos th ky to controlllng th movmnt o our objcts on
scrn. Locotlon ls odjustd by vloclty, ond vloclty by occlrotlon. Acclrotlon wos
whr lt oll bgon. Now w lorn thot totce ls truly whr lt oll bglns.
Lt`s tok our d8A%/ closs, wlth locotlon, vloclty, ond occlrotlon.
Now our gool ls to b obl to odd orcs to thls objct, prhops soylng.
or.
whr wlnd ond grovlty or ]`%028/s. Accordlng to Nwton`s scond low, w could
lmplmnt thls unctlon os ollows.
0-,## d8A%/ 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
@
98A%/N,$$-"b8/0%4;:7&5*
98A%/N,$$-"b8/0%4?/,A:2"5*
A8:& ,$$-"b8/0%4]`%028/ E8/0%5 1
Newton's second law at its simplest. ,00%-%/,2:87 ' E8/0%*
@
0"= S*.2( !22:E:%4'&*; 0"= S*.2( !22:E:%4'&*;
1hls looks prtty good. Atr oll, occe|etot|on totce ls o lltrol tronslotlon o Nwton`s
scond low [wlthout mossj. Nvrthlss, thr`s o prtty blg problm hr. Lt`s rturn to
whot w or trylng to occompllsh. crotlng o movlng objct on th scrn thot rsponds to
wlnd ond grovlty.
Ok, lt`s be th computr or o momnt. |lrst, w coll ,$$-"b8/0%45 wlth wlnd. And so th
d8A%/ objct`s occlrotlon ls now osslgnd th ]`%028/ ;:7&. 5cond, w coll
98A%/N,$$-"b8/0%4;:7&5*
98A%/N,$$-"b8/0%4?/,A:2"5*
98A%/N3$&,2%45*
98A%/N&:#$-,"45*
Choptr 2. |orcs
68
,$$-"b8/0%45 wlth grovlty. Now th d8A%/ objct`s occlrotlon ls st to th grovlty ]`%028/.
1hlrd, w coll 3$&,2%45. Whot hoppns ln 3$&,2%45? Acclrotlon ls oddd to vloclty.
W`r not golng to s ony rror ln Procsslng, but zolnks! W`v got o mojor problm. Whot
ls th volu o occlrotlon whn lt ls oddd to vloclty? |t ls quol to th grovlty orc. Wlnd
hos bn lt out! | w coll ,$$-"b8/0%45 mor thon onc, lt ovrrlds och prvlous coll.
How or w golng to hondl mor thon on orc?
1h truth o th mottr hr ls thot w stortd wlth o slmpllld stotmnt o Nwton`s scond
low. Hr`s o mor occurot woy to put lt.
Nt |orc quols moss tlms occlrotlon.
Or, occlrotlon ls quol to th sum ot o|| totces dlvldd by moss. 1hls moks prct sns.
Atr oll, os w sow ln Nwton`s lrst low, l oll th orcs odd up to zro, on objct
xprlncs on qulllbrlum stot [l.. no occlrotlonj. Our lmplmntotlon o thls ls through o
procss known os ;!1%$ (%%:-:'(&/!. ;!1%$ (%%:-:'(&/!.. |t`s octuolly vry slmpl, oll w nd to do ls odd oll o
th orcs togthr. At ony glvn momnt, thr mlght b J, 2, 6, J2, or 303 orcs. As long os
our objct knows how to occumulot thm, lt dosn`t mottr how mony orcs oct on lt.
Now, w`r not lnlshd just yt. |orc occumulotlon hos on mor plc. 5lnc w`r oddlng
oll th orcs togthr ot ony glvn momnt, w hov to mok sur thot w clor occlrotlon
[l.. st lt to zroj bor och tlm 3$&,2%45 ls colld. Lt`s thlnk obout wlnd or o momnt.
5omtlms th wlnd ls vry strong, somtlms lt`s wok, ond somtlms thr`s no wlnd ot oll.
At ony glvn momnt, thr mlght b o hug gust o wlnd, soy, whn th usr holds down th
mous.
Whn th usr rloss th mous, th wlnd wlll stop, ond occordlng to Nwton`s lrst low, th
objct wlll contlnu to mov ot o constont vloclty. Howvr, l w hod orgottn to rst
occlrotlon to zro, th gust o wlnd would stlll b ln ct. Lvn wors, lt would odd onto
ltsl rom th prvlous rom, slnc w or occumulotlng orcs! Acclrotlon, ln our
slmulotlon, hos no mmory, lt ls slmply colculotd bosd on th nvlronmntol orcs prsnt
A%-80:2"N,&&4,00%-%/,2:875*
A8:& ,$$-"b8/0%4]`%028/ E8/0%5 1
Newton's second law, but with force
accumulation. We now add each force to
acceleration, one at a time.
,00%-%/,2:87N,&&4E8/0%5*
@
:E 4983#%]/%##%&5 1
]`%028/ ;:7& ' 7%; ]`%028/4BNJCB5*
98A%/N,$$-"b8/0%4;:7&5*
@
1h Notur o Cod [v005j
69
ot o momnt ln tlm. 1hls ls dlrnt thon, soy, locotlon, whlch must rmmbr whr th
objct wos ln th prvlous rom ln ordr to mov proprly to th nxt.
1h oslst woy to lmplmnt clorlng th occlrotlon or och rom ls to multlply th
]`%028/ by 0 ot th nd o 3$&,2%45.
A8:& 3$&,2%45 1
A%-80:2"N,&&4,00%-%/,2:875*
-80,2:87N,&&4A%-80:2"5*
,00%-%/,2:87N93-24B5*
@
slng orcs, slmulot o hllum-llld bolloon lootlng upword ond bounclng o th
top o o wlndow. Con you odd o wlnd orc thot chongs ovr tlm, prhops
occordlng to Prlln nols?
MO(.2&-( 0"# MO(.2&-( 0"#
0"> \(4%&;< 8&', ]4-- 0"> \(4%&;< 8&', ]4--
OK. W`v got on tlny llttl oddltlon to mok bor w or don wlth lntgrotlng orcs
lnto our d8A%/ closs ond or rody to look ot xompls. Atr oll, Nwton`s scond low ls
rolly )

* +

, not +

. |ncorporotlng moss ls os osy os oddlng on lnstonc vorlobl to


our closs, but w nd to spnd o llttl mor tlm hr bcous o sllght compllcotlon wlll
mrg.
|lrst w just nd to odd moss.
0-,## d8A%/ 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
Adding mass as a float E-8,2 9,##*
Choptr 2. |orcs
70
[;&'- *+ ](4-:.(E(;' [;&'- *+ ](4-:.(E(;'
Now thot w or lntroduclng moss, lt`s lmportont to mok o qulck not obout unlts o
mosurmnt. |n th rol world, thlngs or mosurd ln spcllc unlts. W soy thot two
objcts or 3 mtrs oport, th bosboll ls movlng ot o rot o 90 mlls pr hour, or thls
bowllng boll hos o moss o 6 kllogroms. As w`ll s lotr ln thls book, somtlms w
wlll wont to tok rol-world unlts lnto consldrotlon. Howvr, ln thls choptr, w`r
golng to lgnor thm or th most port. Our unlts o mosurmnt or ln plxls [1hs
two clrcls or J00 plxls oport"j ond roms o onlmotlon [1hls clrcl ls movlng ot o
rot o 2 plxls pr rom"j. |n th cos o moss, thr lsn`t ony unlt o mosurmnt or
us to us. W`r just golng to mok somthlng up. |n thls xompl, w`r orbltrorlly
plcklng th numbr J0. 1hr ls no unlt o mosurmnt, though you mlght njoy
lnvntlng o unlt o your own, llk J moog" or J yurkl." |t should olso b notd thot, or
dmonstrotlon purposs, w`ll tl moss to plxls [drowlng, soy, o clrcl wlth o rodlus o
J0j. 1hls wlll ollow us to vlsuollz th moss o on objct. |n th rol world, howvr, slz
dos not dlnltly lndlcot moss. A smoll mtol boll could hov o much hlghr moss
thon o lorg bolloon du to lts hlghr dnslty.
Moss ls o scolor [lootj, not o vctor, os lt`s just on numbr dscrlblng th omount o mottr ln
on objct. W could b oncy obout thlngs ond comput th oro o o shop os lts moss, but
lt`s slmplr to bgln by soylng, Hy, th moss o thls objct ls.um, | dunno.how obout J0?"
1hls lsn`t so grot slnc thlngs only bcom lntrstlng onc w hov objcts wlth vorylng
moss, but lt`ll gt us stortd. Whr dos moss com ln? W us lt whll opplylng Nwton`s
scond low to our objct.
Yt ogoln, vn though our cod looks qult rosonobl, w hov o olrly mojor problm hr.
Consldr th ollowlng scnorlo wlth two d8A%/ objcts, both blng blown owoy by o wlnd
orc.
d8A%/45 1
-80,2:87 ' 7%; ]`%028/4/,7&894;:&2<5C/,7&894<%:?<255*
A%-80:2" ' 7%; ]`%028/4BCB5*
,00%-%/,2:87 ' 7%; ]`%028/4BCB5*
9,## ' )BNB*
@
A8:& ,$$-"b8/0%4]`%028/ E8/0%5 1
Newton's second law (with force
accumulation and mass)
E8/0%N&:A49,##5*
,00%-%/,2:87N,&&4E8/0%5*
@
1h Notur o Cod [v005j
7J
Agoln, lt`s be th computr. Objct 9) rclvs th wlnd orc[J,0jdlvlds lt by moss
[J0j, ond odds lt to occlrotlon.
5D $X4&'. !2#1 98):$Y *DJ?+
Z2L21$1 63 5&.. 89 D?Y *?-DJ?+
OK. Movlng on to objct 9>. |t olso rclvs th wlnd orc[J,0j. Wolt. Hold on o scond.
Whot ls th volu o th wlnd orc? 1oklng o closr look, th wlnd orc ls octuolly
now[0.J,0j!! Lo you rmmbr thls llttl tldblt obout worklng wlth objcts? Whn you poss
on objct [ln thls cos o ]`%028/j lnto o unctlon, you or posslng o rrnc to thot objct.
|t`s not o copy! 5o l o unctlon moks o chong to thot objct [whlch, ln thls cos, lt dos by
dlvldlng by mossj thn thot objct ls prmonntly chongd! But w don`t wont 9> to rclv
o orc dlvldd by th moss o objct 9). W wont lt to rclv thot orc ln lts orlglnol
stot[J,0j. And so w must protct ourslvs ond mok o copy o th ]`%028/ bor
dlvldlng lt by moss. |ortunotly, th ]`%028/ closs hos o convnlnt mthod or moklng o
copy?%245. ?%245 rturns o nw ]`%028/ objct wlth th som doto. And so w con
rvls ,$$-"b8/0%45 os ollows.
1hr`s onothr woy w could wrlt th obov unctlon, uslng th stotlc mthod &:A45. |or
hlp wlth thls xrcls, rvlw stotlc mthods ln Choptr J [s pog 54j.
d8A%/ 9) ' 7%; d8A%/45*
d8A%/ 9> ' 7%; d8A%/45*
]`%028/ ;:7& ' 7%; ]`%028/4)CB5*
9)N,$$-"b8/0%4;:7&5*
9>N,$$-"b8/0%4;:7&5*
A8:& ,$$-"b8/0%4]`%028/ E8/0%5 1
Making a copy of the PVector before using
it!
]`%028/ E ' E8/0%N?%245*
EN&:A49,##5*
,00%-%/,2:87N,&&4E5*
@
Rwrlt th ,$$-"b8/0%45 mthod uslng th stotlc mthod &:A45 lnstod o ?%245.
A8:& ,$$-"b8/0%4]`%028/ E8/0%5 1
]`%028/ E ' aaaaaaaNaaa4aaaaaCaaaa5*
,00%-%/,2:87N,&&4E5*
@
MO(.2&-( 0"0 MO(.2&-( 0"0
Choptr 2. |orcs
72
0"? P.(4'&;< S*.2(- 0"? P.(4'&;< S*.2(-
Lt`s tok o momnt to rmlnd ourslvs whr w or. W know whot o orc ls [o vctorj,
ond w know how to opply o orc to on objct [dlvld lt by moss ond odd lt to th objct`s
occlrotlon vctorj. Whot or w mlsslng? Wll, w hov yt to lgur out how w gt o orc
ln th lrst ploc. Whr do orcs com rom?
|n thls choptr, w`ll look ot two mthods or crotlng orcs ln our Procsslng world.
J. P&3# (: & +*)0#T P&3# (: & +*)0#T Atr oll, you or th progrommr, th crotor o your world.
1hr`s no roson why you con`t just mok up o orc ond opply lt.
2. P*-#5 & +*)0#T P*-#5 & +*)0#T Ys, orcs xlst ln th rol world. And physlcs txtbooks otn
contoln ormulos or ths orcs. W con tok ths ormulos, tronslot thm lnto
sourc cod, ond modl rol-world orcs ln Procsslng.
1h oslst woy to mok up o orc ls to just plck o numbr. Lt`s stort wlth th ldo o
slmulotlng wlnd. How obout o wlnd orc thot polnts to th rlght ond ls olrly wok? Assumlng
o d8A%/ objct m, our cod would look llk.
1h rsult lsn`t trrlbly lntrstlng, but lt ls o good ploc to stort. W crot o ]`%028/ objct,
lnltlollz lt, ond poss lt lnto on objct [whlch ln turn wlll opply lt to lts own occlrotlonj. | w
wontd to hov two orcs, prhops wlnd ond grovlty [o blt strongr, polntlng downj, w mlght
wrlt th ollowlng.
IJ&7:5# <K;
]`%028/ ;:7& ' 7%; ]`%028/4BNB)CB5*
9N,$$-"b8/0%4;:7&5*
]`%028/ ;:7& ' 7%; ]`%028/4BNB)CB5*
]`%028/ ?/,A:2" ' 7%; ]`%028/4BCBN)5*
9N,$$-"b8/0%4;:7&5*
9N,$$-"b8/0%4?/,A:2"5*
1h Notur o Cod [v005j
73
Now w hov two orcs, polntlng ln dlrnt dlrctlons wlth dlrnt mognltuds, both
opplld to objct 9. W`r bglnnlng to gt somwhr. W`v now bullt o world or our
objcts ln Procsslng, on nvlronmnt to whlch thy con octuolly rspond.
Lt`s look ot how w could mok thls xompl o blt mor xcltlng wlth mony objcts o
vorylng moss. 1o do thls, w`ll nd o qulck rvlw o objct-orlntd progrommlng. Agoln,
w`r not covrlng oll th boslcs o progrommlng hr [or thot you con chck out ony o th
lntro Procsslng books llstd ln th lntroductlonj. Howvr, slnc th ldo o crotlng o
world llld wlth objcts ls prtty undomntol to oll th xompls ln thls book, lt`s worth
toklng o momnt to wolk through th stps o golng rom on objct to mony.
1hls ls whr w or wlth th d8A%/ closs os o whol. Notlc how lt ls ldntlcol to th d8A%/
closs crotd ln Choptr J, wlth two oddltlons9,## ond o nw ,$$-"b8/0%45 unctlon.
0-,## d8A%/ 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
The object now has mass! E-8,2 9,##*
d8A%/45 1
And for now, we'll just set the mass equal
to 1 for simplicity.
9,## ' )*
-80,2:87 ' 7%; ]`%028/4HBCHB5*
A%-80:2" ' 7%; ]`%028/4BCB5*
,00%-%/,2:87 ' 7%; ]`%028/4BCB5*
@
Newton's second law. A8:& ,$$-"b8/0%4]`%028/ E8/0%5 1
Receive a force, divide by mass, and add
to acceleration.
]`%028/ E ' ]`%028/N&:A4E8/0%C9,##5*
,00%-%/,2:87N,&&4E5*
@
A8:& 3$&,2%45 1
Motion 101 from Chapter 1 A%-80:2"N,&&4,00%-%/,2:875*
-80,2:87N,&&4A%-80:2"5*
Now add clearing the acceleration each
time!
,00%-%/,2:87N93-24B5*
@
A8:& &:#$-,"45 1
#2/8.%4B5*
E:--4)OJ5*
%--:$#%4-80,2:87N!C-80,2:87N"C9,##Q)GC9,##Q)G5*
@ Scaling the size according to mass.
Choptr 2. |orcs
74
Now thot our closs ls st, w con choos to crot, soy, on hundrd d8A%/ objcts wlth on
orroy.
And thn w con lnltlollz oll o thos d8A%/ objcts ln #%23$45 wlth o loop.
But now w hov o smoll lssu. | w rr bock to th d8A%/ objct`s constructor.
.w dlscovr thot vry d8A%/ objct ls mod xoctly th som woy. Whot w wont or d8A%/
objcts o vorylng moss thot stort ot vorylng locotlons. Hr ls whr w nd to lncros th
sophlstlcotlon o our constructor by oddlng orgumnts.
Somewhat arbitrarily, we are deciding that
an object bounces when it hits the edges of
a window.
A8:& 0<%0.h&?%#45 1
:E 4-80,2:87N! ^ ;:&2<5 1
-80,2:87N! ' ;:&2<*
A%-80:2"N! Q' 6)*
@ %-#% :E 4-80,2:87N! P B5 1
A%-80:2"N! Q' 6)*
-80,2:87N! ' B*
@
:E 4-80,2:87N" ^ <%:?<25 1
Even though we said we shouldn't touch
location and velocity directly, there are some
exceptions. Here we are doing so as a quick
and easy way to reverse the direction of our
object when it reaches the edge.
A%-80:2"N" Q' 6)*
-80,2:87N" ' <%:?<2*
@
@
@
d8A%/KL 98A%/# ' 7%; d8A%/K)BBL*
A8:& #%23$45 1
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
98A%/#K:L ' 7%; d8A%/45*
@
@
d8A%/45 1
Every object has a mass of 1 and a location
of (30,30).
9,## ' )*
-80,2:87 ' 7%; ]`%028/4HBCHB5*
A%-80:2" ' 7%; ]`%028/4BCB5*
,00%-%/,2:87 ' 7%; ]`%028/4BCB5*
@
d8A%/4E-8,2 9C E-8,2 ! C E-8,2 "5 1
Now setting these variables with arguments 9,## ' 9*
-80,2:87 ' 7%; ]`%028/4!C"5*
1h Notur o Cod [v005j
75
Notlc how th moss ond locotlon or no longr st to hordcodd numbrs, but rothr
lnltlollzd vlo orgumnts possd through th constructor. 1hls mons w con crot o
vorlty o d8A%/ objcts. blg ons, smoll ons, ons thot stort on th lt sld o th scrn,
ons thot stort on th rlght, tc.
Wlth on orroy, howvr, w wont to lnltlollz oll o th objcts wlth o loop.
|or och movr crotd, th moss ls st to o rondom volu btwn 0.J ond 5, th stortlng
x-locotlon ls st to 0, ond th stortlng y-locotlon ls st to 0. Crtolnly, thr or oll sorts o
woys w mlght choos to lnltlollz th objcts, thls ls just o dmonstrotlon o on posslblllty.
Onc th orroy o objcts ls dclord, crotd, ond lnltlollzd, th rst o th cod ls slmpl.
W run through vry objct, hond thm och th orcs ln th nvlronmnt, ond njoy th
show.
A%-80:2" ' 7%; ]`%028/4BCB5*
,00%-%/,2:87 ' 7%; ]`%028/4BCB5*
@
A big Mover on the left side of the window d8A%/ 9) ' 7%; d8A%/4)BCBC<%:?<2=>5*
A small Mover on the right side of the
window
d8A%/ 9) ' 7%; d8A%/4BN)C;:&2<C<%:?<2=>5*
A8:& #%23$45 1
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
nitializing many Mover objects, all with
random mass (and all starting at 0,0)
98A%/#K:L ' 7%; d8A%/4/,7&894BN)CJ5CBCB5*
@
@
Choptr 2. |orcs
76
IJ&7:5# <K<
Not how ln th obov lmog, th smollr clrcls roch th rlght o th wlndow ostr thon th
lorgr ons. 1hls ls bcous o our ormulo. occe|etot|on totce d|v|ded by moss. 1h lorgr
th moss, th smollr th occlrotlon.
A8:& &/,;45 1
I,0.?/837&4>JJ5*
]`%028/ ;:7& ' 7%; ]`%028/4BNB)CB5*
Make up two forces. ]`%028/ ?/,A:2" ' 7%; ]`%028/4BCBN)5*
Loop through all objects and apply both
forces to each object.
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
98A%/#K:LN,$$-"b8/0%4;:7&5*
98A%/#K:LN,$$-"b8/0%4?/,A:2"5*
98A%/#K:LN3$&,2%45*
98A%/#K:LN&:#$-,"45*
98A%/#K:LN0<%0.h&?%#45*
@
@
|nstod o objcts bounclng o th dg o th woll, crot on xompl ln whlch on
lnvlslbl orc pushs bock on th objcts to kp thm ln th wlndow. Con you wlght
th orc occordlng to how or th objct ls rom on dgl.., th closr lt ls, th
strongr th orc?
MO(.2&-( 0"= MO(.2&-( 0"=
0"K e.4I&'/ *; M4.', 4;9 ]*9(%&;< 4 S*.2( 0"K e.4I&'/ *; M4.', 4;9 ]*9(%&;< 4 S*.2(
You moy hov notlcd somthlng woully lnoccurot obout thls lost xompl. 1h smollr th
clrcl, th ostr lt olls. 1hr ls o loglc to thls, otr oll, w just stotd [occordlng to Nwton`s
scond lowj thot th smollr th moss, th hlghr th occlrotlon. But thls ls not whot
hoppns ln th rol world. | you wr to cllmb to th top o th Lonlng 1owr o Plso ond
drop two bolls o dlrnt mosss, whlch on wlll hlt th ground lrst? Accordlng to lgnd,
Golllo prormd thls xoct tst ln J589, dlscovrlng thot thy ll wlth th som occlrotlon,
hlttlng th ground ot th som tlm. Why ls thls? As w wlll s lotr ln thls choptr, th orc
o grovlty ls colculotd rlotlv to on objct`s moss. 1h blggr th objct, th strongr th
orc. 5o l th orc ls scold occordlng to moss, lt ls concld out whn occlrotlon ls
dlvldd by moss. W con lmplmnt thls ln our sktch rothr oslly by multlplylng our mod-up
grovlty orc by moss.
1h Notur o Cod [v005j
77
IJ&7:5# <K=
Whll th objcts now oll ot th som rot, bcous th strngth o th wlnd orc ls
lndpndnt o moss, th smollr objcts stlll occlrot to th rlght mor qulckly.
Moklng up orcs wlll octuolly gt us qult or. 1h world o Procsslng ls o prtnd world o
plxls ond you or lts mostr. 5o whotvr you dm opproprlot to b o orc, wll by
golly, thot`s th orc lt should b. Nvrthlss, thr moy com o tlm whr you lnd
yoursl wondrlng. But how dos lt rolly oll work?"
Opn up ony hlgh school physlcs txtbook ond you wlll lnd som dlogroms ond ormulos
dscrlblng mony dlrnt orcsgrovlty, lctromogntlsm, rlctlon, tnslon, lostlclty, ond
mor. |n thls choptr w`r golng to look ot two orcsrlctlon ond grovlty. 1h polnt w`r
moklng hr ls not thot rlctlon ond grovlty or undomntol orcs thot you olwoys nd to
hov ln your Procsslng sktchs. Rothr, w wont to voluot ths two orcs os cos
studls or th ollowlng procss.
- ndrstondlng th concpt bhlnd o orc
- Lconstructlng th orc`s ormulo lnto two ports.
How do w comput th orc`s dlrctlon?
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
]`%028/ ;:7& ' 7%; ]`%028/4BNBB)CB5*
E-8,2 9 ' 98A%/#K:LN9,##*
Scaling gravity by mass to be more
accurate
]`%028/ ?/,A:2" ' 7%; ]`%028/4BCBN)Q95*
98A%/#K:LN,$$-"b8/0%4;:7&5*
98A%/#K:LN,$$-"b8/0%4?/,A:2"5*
98A%/#K:LN3$&,2%45*
98A%/#K:LN&:#$-,"45*
98A%/#K:LN0<%0.h&?%#45*
@
Choptr 2. |orcs
78
How do w comput th orc`s mognltud?
- 1ronslotlng thot ormulo lnto Procsslng cod thot colculots o ]`%028/ to b snt
through our d8A%/'s ,$$-"b8/0%45 unctlon
| w con ollow th obov stps wlth two orcs, thn hopully l you vr lnd yoursl
Googllng otomlc nucll wok nuclor orc" ot 3 o.m., you wlll hov th skllls to tok whot you
lnd ond odopt lt or Procsslng.
\(4%&;< 8&', +*.E:%4( \(4%&;< 8&', +*.E:%4(
OK, ln o momnt w`r golng to wrlt out th ormulo or rlctlon. 1hls lsn`t th lrst tlm
w`v sn o ormulo ln thls book, w just lnlshd up our dlscusslon o Nwton`s
scond low, )

* +

[or orc moss ' occlrotlonj. W dldn`t spnd o lot o tlm


worrylng obout thls ormulo bcous lt`s o nlc ond slmpl on. Nvrthlss, lt`s o
scory world out thr. Just tok o look ot th quotlon or o normol" dlstrlbutlon, whlch
w covrd [wlthout looklng ot th ormuloj ln th |ntroductlon [s pog J0j.
, ("; -, .
2
)
1
. 2/
0
("-)
2
2.
2
Whot w`r slng hr ls thot ormulos llk to us o lot o symbols [qult otn lttrs
rom th Grk olphobtj. Lt`s tok o look ot th ormulo or rlctlon.
)123425&

-6$
"
| lt`s bn o whll slnc you`v lookd ot o ormulo rom o moth or physlcs txtbook,
thr or thr ky polnts thot or lmportont to covr bor w mov on.
- =0(':(&$ &+$ 1/2+& )/8$I ())/2. &! &+$ '$;& )/8$6 =0(':(&$ &+$ 1/2+& )/8$I ())/2. &! &+$ '$;& )/8$6 1hls ls just llk ln cod! Whot
w`r dolng hr ls voluotlng th rlght sld o th quotlon ond osslgnlng lt
to th lt. |n th cos obov, w wont to colculot th orc o rlctlonth
lt sld tlls us whot w wont to colculot ond th rlght sld tlls us how to
do lt.
- D1$ >$ &('J/.2 ("!:& ( 0$%&!1 !1 ( )%('(1G D1$ >$ &('J/.2 ("!:& ( 0$%&!1 !1 ( )%('(1G |t`s lmportont or us to rollz thot
ln som coss, w`ll b looklng ot o vctor, ln othrs, o scolor. |or xompl, ln
thls cos th orc o rlctlon ls o vctor. W con s thot by th orrow obov
th word rlctlon." |t hos o mognltud ond dlrctlon. 1h rlght sld o th
quotlon olso hos o vctor, os lndlcotd by th symbol $
"
, whlch ln thls cos
stonds or th vloclty unlt vctor.
- F+$. )@-"!') (1$ A'(%$8 .$K& &! $(%+ !&+$1I >$ -$(. ;!1 &+$- &! "$ F+$. )@-"!') (1$ A'(%$8 .$K& &! $(%+ !&+$1I >$ -$(. ;!1 &+$- &! "$
-:'&/A'/$86 -:'&/A'/$86 1h ormulo obov octuolly hos our lmnts. -J, , N, ond $
"
. W
wont to multlply thm togthr ond rod th ormulo os. )123425&

1 * -* 6 * $
"
1h Notur o Cod [v005j
79
0"L S.&2'&*; 0"L S.&2'&*;
Lt`s bgln wlth rlctlon ond ollow our stps.
|rlctlon ls o 8/))/A(&/0$ ;!1%$ 8/))/A(&/0$ ;!1%$. A dlsslpotlv orc ls on ln whlch th totol nrgy o o
systm dcross whn on objct ls ln motlon. Lt`s soy you or drlvlng o cor. Whn you
prss your oot down on th brok pdol, th cor`s broks us rlctlon to slow down th
motlon o th tlrs. Klntlc nrgy [motlonj ls convrtd lnto thrmol nrgy [hotj.
Whnvr two surocs com lnto contoct, thy xprlnc rlctlon. A complt modl o
rlctlon would lnclud sporot coss or stotlc rlctlon [o body ot rst ogolnst o surocj ond
klntlc rlctlon [o body ln motlon ogolnst o surocj, but or our purposs, w or only golng
to look ot th klntlc cos.
Hr`s th ormulo or rlctlon.
|t`s now up to us to sporot thls ormulo lnto two componnts thot dtrmln th dlrctlon
o rlctlon os wll os th mognltud. Bosd on th dlogrom obov, w con s thot tt|ct|on
po|nts |n the oppos|te d|tect|on ot ve|oc|ty. |n oct, thot`s th port o th ormulo thot soys -J '
$
"
, or -J tlms th vloclty unlt vctor. |n Procsslng, thls would mon toklng th vloclty
vctor, normollzlng lt, ond multlplylng by -J.
Notlc two oddltlonol stps hr. |lrst, lt`s lmportont to mok o copy o th vloclty vctor,
os w don`t wont to rvrs th objct`s dlrctlon by occldnt. 5cond, w normollz th
vctor. 1hls ls bcous th mognltud o rlctlon ls not ossoclotd wlth how ost lt ls movlng,
ond w wont to stort wlth o rlctlon vctor o mognltud J so thot lt con oslly b scold.
Iiure z.
]`%028/ E/:02:87 ' A%-80:2"N?%245*
E/:02:87N78/9,-:F%45*
Let's figure out the direction of the friction
force (a unit vector in the opposite direction
of velocity).
E/:02:87N93-246)5*
Choptr 2. |orcs
80
Accordlng to th ormulo, th mognltud ls j ' k. j, th Grk lttr mu [pronouncd mw"j,
ls usd hr to dscrlb th %!$;;/%/$.& !; ;1/%&/!. %!$;;/%/$.& !; ;1/%&/!.. 1h colclnt o rlctlon stobllshs th
strngth o o rlctlon orc or o portlculor suroc. 1h hlghr lt ls, th strongr th rlctlon, th
lowr, th wokr. A block o lc, or xompl, wlll hov o much lowr colclnt o rlctlon
thon, soy, sondpopr. 5lnc w`r ln o prtnd Procsslng world, w con orbltrorlly st th
colclnt bosd on how much rlctlon w wont to slmulot.
Now or th scond port. k. k rrs to th .!1-(' ;!1%$ .!1-(' ;!1%$, th orc prpndlculor to th
objct`s motlon olong o suroc. 1hlnk o o vhlcl drlvlng olong o rood. 1h vhlcl pushs
down ogolnst th rood wlth grovlty, ond Nwton`s thlrd low tlls us thot th rood ln turn
pushs bock ogolnst th vhlcl. 1hot`s th normol orc. 1h grotr th grovltotlonol orc,
th grotr th normol orc. As w`ll s ln th nxt sctlon, grovlty ls ossoclotd wlth moss,
ond so o llghtwlght sports cor would xprlnc lss rlctlon thon o mosslv troctor trollr
truck. Wlth th dlogrom obov, howvr, whr th objct ls movlng olong o suroc ot on
ongl, computlng th normol orc ls o blt mor compllcotd bcous lt dosn`t polnt ln th
som dlrctlon os grovlty. W`ll nd to know somthlng obout ongls ond trlgonomtry.
All o ths spcllcs or lmportont, howvr, ln Procsslng, o good nough" slmulotlon con
b ochlvd wlthout thm. W con, or xompl, mok rlctlon work wlth th ossumptlon thot
th normol orc wlll olwoys hov o mognltud o J. Whn w gt lnto trlgonomtry ln th nxt
choptr, w`ll rmmbr to rturn to thls qustlon ond mok our rlctlon xompl o blt mor
sophlstlcotd. 1hror.
Now thot w hov both th mognltud ond dlrctlon or rlctlon, w con put lt oll togthr.
.ond odd lt to our orcs" xompl, whr mony objcts xprlnc wlnd, grovlty, ond now
rlctlon.
E-8,2 0 ' BNB)*
E-8,2 78/9,- ' )*
E-8,2 0 ' BNB)*
E-8,2 78/9,- ' )*
Let's figure out the magnitude of friction
(really just an arbitrary constant).
E-8,2 E/:02:87d,? ' 0Q78/9,-*
]`%028/ E/:02:87 ' A%-80:2"N?%245*
E/:02:87N93-246)5*
E/:02:87N78/9,-:F%45*
Take the unit vector and multiply it by
magnitude and we have our force vector!
E/:02:87N93-24E/:02:87d,?5*
1h Notur o Cod [v005j
8J
IJ&7:5# <K>L F105(-/16 +)/0'/*1
Runnlng thls xompl, you`ll notlc thot th clrcls don`t vn mok lt to th rlght sld o th
wlndow. 5lnc rlctlon contlnuously pushs ogolnst th objct ln th opposlt dlrctlon o lts
movmnt, th objct contlnuously slows down. 1hls con b o usul tchnlqu or o
problm dpndlng on th gools o your vlsuollzotlon.
No jriction With jriction
A8:& &/,;45 1
I,0.?/837&4>JJ5*
]`%028/ ;:7& ' 7%; ]`%028/4BNBB)CB5*
We could scale by mass to be more
accurate.
]`%028/ ?/,A:2" ' 7%; ]`%028/4BCBN)5*
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
9'8&/ : " ?-?D,
MN$:/8) 9)2:/28# " 58L$).[2\-L$'8:2/3-G$/*+,
9)2:/28#-54'/*TD+,
9)2:/28#-#8)5&'2]$*+,
9)2:/28#-54'/*:+,
Apply the friction force vector to the object. 58L$).[2\-&00'3^8):$*9)2:/28#+,
98A%/#K:LN,$$-"b8/0%4;:7&5*
98A%/#K:LN,$$-"b8/0%4?/,A:2"5*
98A%/#K:LN3$&,2%45*
98A%/#K:LN&:#$-,"45*
98A%/#K:LN0<%0.h&?%#45*
@
@
Choptr 2. |orcs
82
Crot pockts o rlctlon ln o Procsslng sktch so thot objcts only xprlnc rlctlon
whn crosslng ovr thos pockts. Whot l you vory th strngth [rlctlon colclntj o
och oro? Whot l you mok som pockts otur th opposlt o rlctlonl.., whn
you ntr o glvn pockt you octuolly spd up lnstod o slowlng down?
MO(.2&-( 0"> MO(.2&-( 0">
0"N !&. 4;9 S%:&9 Y(-&-'4;2( 0"N !&. 4;9 S%:&9 Y(-&-'4;2(
|rlctlon olso occurs whn o body posss through o llquld or gos. 1hls orc hos mony dlrnt
noms, oll rolly monlng th som thlng. v|scous totce, dtog totce, t|u|d tes|stonce. Whll th
rsult ls ultlmotly th som os our prvlous rlctlon xompls [th objct slows downj, th
woy ln whlch w colculot o drog orc wlll b sllghtly dlrnt. Lt`s look ot th ormulo.
)
7

1
2
8$
2
+9
7
$
"
Now lt`s brok thls down ond s whot w rolly nd or on ctlv slmulotlon ln
Procsslng, moklng ourslvs o much slmplr ormulo ln th procss.
-
)
7 rrs to dtog totce, th vctor w ultlmotly wont to comput ond poss lnto our
,$$-"b8/0%45 unctlon.
- - J/2 ls o constont. -0.5. 1hls ls olrly lrrlvont ln trms o our Procsslng world, os
w wlll b moklng up volus or othr constonts onywoy. Howvr, th oct thot lt ls
ngotlv ls lmportont, os lt tlls us thot th orc ls ln th opposlt dlrctlon o
vloclty [just os wlth rlctlonj.
Iiure z.(
1h Notur o Cod [v005j
83
- 8 ls th Grk lttr tho, ond rrs to th dnslty o th llquld, somthlng w
don`t nd to worry obout. W con slmplly th problm ond consldr thls to hov
o constont volu o J.
- $ rrs to th spd o th objct movlng. OK, w`v got thls on! 1h objct`s
spd ls th mognltud o th vloclty vctor. A%-80:2"N9,?7:23&%45. And $
2
just
mons $ squord or $ ' $.
- + rrs to th rontol oro o th objct thot ls pushlng through th llquld [or gosj.
An orodynomlc Lomborghlnl, or xompl, wlll xprlnc lss olr rslstonc thon
o boxy Volvo. Nvrthlss, or o boslc slmulotlon, w con consldr our objct to
b sphrlcol ond lgnor thls lmnt.
-
9
7 ls th colclnt o drog, xoctly th som os th colclnt o rlctlon [ 8j. 1hls
ls o constont w`ll dtrmln bosd on whthr w wont th drog orc to b
strong or wok.
- $
"
Look omlllor? |t should. 1hls rrs to th vloclty unlt vctor, l..
A%-80:2"N78/9,-:F%45. Just llk wlth rlctlon, drog ls o orc thot polnts ln th
opposlt dlrctlon o vloclty.
Now thot w`v onolyzd och o ths componnts ond dtrmlnd whot w nd or o
slmpl slmulotlon, w con rduc our ormulo to.
or.
Lt`s lmplmnt thls orc ln our d8A%/ closs xompl wlth on oddltlon. Whn w wrot our
rlctlon xompl, th orc o rlctlon wos olwoys prsnt. Whnvr on objct wos movlng,
rlctlon would slow lt down. Hr, lt`s lntroduc on lmnt to th nvlronmnto llquld"
thot th d8A%/ objcts poss through. 1h l:g3:& objct wlll b o rctongl ond wlll know
Iiure z.: Dur simplijied drc jorce jormulc
E-8,2 0 ' BN)*
E-8,2 #$%%& ' AN9,?45*
Part 1 of our formula (magnitude): Cd * v2 E-8,2 &/,?d,?7:23&% ' 0 Q #$%%& Q #$%%&*
]`%028/ &/,? ' A%-80:2"N?%245*
Part 2 of our formula (direction): -1 *
velocity
&/,?N93-246)5*
&/,?N78/9,-:F%45*
Magnitude and direction together! &/,?N93-24&/,?d,?7:23&%5*
Choptr 2. |orcs
84
obout lts locotlon, wldth, hlght, ond colclnt o drog"l.., ls lt osy or objcts to mov
through lt [llk olrj or dllcult [llk molosssj? |n oddltlon, lt should lnclud o unctlon to drow
ltsl on th scrn [ond two mor unctlons, whlch w`ll s ln o momntj.
1h moln progrom wlll now lnclud o l:g3:& objct rrnc os wll os o lln o cod thot
lnltlollzs thot objct.
Now coms on lntrstlng qustlon. how do w gt th d8A%/ objct to tolk to th l:g3:&
objct? |n othr words, w wont to xcut th ollowlng.
hen o movet posses thtough o ||qu|d |t expet|ences o dtog totce.
.or ln objct-orlntd spok [ossumlng w or looplng through on orroy o d8A%/ objcts wlth
lndx lj.
0-,## l:g3:& 1
The liquid object includes a variable defining
its coefficient of drag.
E-8,2 !C"C;C<*
E-8,2 0*
l:g3:&4E-8,2 !aC E-8,2 "aC E-8,2 ;aC E-8,2 <aC E-8,2 0a5 1
! ' !a*
" ' "a*
; ' ;a*
< ' <a*
0 ' 0a*
@
A8:& &:#$-,"45 1
78[2/8.%45*
E:--4)OJ5*
/%024!C"C;C<5*
@
@
l:g3:& -:g3:&*
A8:& #%23$45 1
-:g3:& ' 7%; l:g3:&4BC <%:?<2=>C ;:&2<C <%:?<2=>C BN)5*
@
nitialize a Liquid object. Note the coefficient
is low (0.1), otherwise the object would
come to a halt fairly quickly (which may
someday be the effect you want).
:E 498A%/#K:LN:#c7#:&%4-:g3:&55 1
f a Mover is inside a Liquid, apply the drag
force.
98A%/#K:LN&/,?4-:g3:&5*
@
1h Notur o Cod [v005j
85
1h obov cod tlls us thot w nd to odd two unctlons to th d8A%/ closs. [Jj o unctlon
thot dtrmlns l o d8A%/ objct ls lnsld th l:g3:& objct, ond [2j o unctlon thot
computs ond opplls o drog orc on th d8A%/ objct.
1h lrst ls osy, w con slmply us o condltlonol stotmnt to dtrmln l th locotlon
vctor rsts lnsld th rctongl dlnd by th llquld.
1h &/,?45 unctlon ls o blt mor compllcotd, howvr, w`v wrlttn th cod or lt
olrody. 1hls ls slmply on lmplmntotlon o our ormulo. 1h drog orc ls quol to the
coett|c|ent ot dtog mu|t|p||ed by the speed ot the d8A%/ squoted |n the oppos|te d|tect|on ot
ve|oc|ty|
And wlth ths two unctlons oddd to th d8A%/ closs, w`r rody to put lt oll togthr ln
th moln tob.
I88-%,7 :#c7#:&%4l:g3:& -5 1
:E 4-80,2:87N!^-N! mm -80,2:87N!P-N!(-N; mm -80,2:87N"^-N" mm -80,2:87N"P-N"(-N<5
1
/%23/7 2/3%*
@ %-#% 1
/%23/7 E,-#%*
@
@
This conditional statement determines if
the PVector location is inside the rectangle
defined by the Liquid class.
A8:& &/,?4l:g3:& -5 1
E-8,2 #$%%& ' A%-80:2"N9,?45*
The force's magnitude: Cd * v~2~ E-8,2 &/,?d,?7:23&% ' -N0 Q #$%%& Q #$%%&*
]`%028/ &/,? ' A%-80:2"N?%245*
&/,?N93-246)5*
The force's direction: -1 * velocity &/,?N78/9,-:F%45*
Finalize the force: magnitude and direction
together.
&/,?N93-24&/,?d,?7:23&%5*
Apply the force. ,$$-"b8/0%4&/,?5*
@
Choptr 2. |orcs
86
IJ&7:5# <K?L G5(/- H#8/8'&10#
Runnlng th xompl, you should notlc thot w or slmulotlng bolls olllng lnto wotr. 1h
objcts only slow down whn crosslng through th groy oro ot th bottom o th wlndow
[rprsntlng th llquldj. You`ll olso notlc thot th smollr objcts slow down o grot dol
d8A%/KL 98A%/# ' 7%; d8A%/K)BBL*
l:g3:& -:g3:&*
A8:& #%23$45 1
#:F%4HGBC GDB5*
#9882<45*
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
98A%/#K:L ' 7%; d8A%/4/,7&894BN)CJ5CBCB5*
@
-:g3:& ' 7%; l:g3:&4BC <%:?<2=>C ;:&2<C <%:?<2=>C BN)5*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
-:g3:&N&:#$-,"45*
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
:E 498A%/#K:LN:#c7#:&%4-:g3:&55 1
98A%/#K:LN&/,?4-:g3:&5*
@
E-8,2 9 ' BN)Q98A%/#K:LN9,##*
Note that we are scaling gravity according to
mass.
]`%028/ ?/,A:2" ' 7%; ]`%028/4BC 95*
98A%/#K:LN,$$-"b8/0%4?/,A:2"5*
98A%/#K:LN3$&,2%45*
98A%/#K:LN&:#$-,"45*
98A%/#K:LN0<%0.h&?%#45*
@
@
1h Notur o Cod [v005j
87
mor thon th lorgr objcts. Rmmbr Nwton`s scond low? V b / d. Acclrotlon
quols orc d|v|ded by moss. A mosslv objct wlll occlrot lss. A smollr objct wlll
occlrot mor. |n thls cos, th occlrotlon w`r tolklng obout ls th slowlng down"
du to drog. 1h smollr objcts wlll slow down ot o grotr rot thon th lorgr ons.
1ok o look ot our ormulo or drog ogoln. 81(2 ;!1%$ ? %!$;;/%/$.& L )A$$8 L )A$$8 81(2 ;!1%$ ? %!$;;/%/$.& L )A$$8 L )A$$8.
1h ostr on objct movs, th grotr th drog orc ogolnst lt. |n oct, on objct not
movlng ln wotr xprlncs no drog ot oll. Lxpond th xompl to drop th bolls
rom dlrnt hlghts. How dos thls oct th drog os thy hlt th wotr?
MO(.2&-( 0"? MO(.2&-( 0"?
1h ormulo or drog olso lncludd suroc oro. Con you crot o slmulotlon o boxs
olllng lnto wotr wlth o drog orc dpndnt on th lngth o th sld hlttlng th
wotr?
MO(.2&-( 0"K MO(.2&-( 0"K
|luld rslstonc dos not only work opposlt to th vloclty vctor, but olso
prpndlculor to lt. 1hls ls known os llt-lnducd drog" ond wlll cous on olrplon
wlth on ongld wlng to rls ln oltltud. 1ry crotlng o slmulotlon o llt.
MO(.2&-( 0"L MO(.2&-( 0"L
0"W e.4I&'4'&*;4% !''.42'&*; 0"W e.4I&'4'&*;4% !''.42'&*;
Probobly th most omous orc o oll ls
grovlty. W humons on orth thlnk o
grovlty os on oppl hlttlng |sooc Nwton on
th hod. Grovlty mons thot stu olls
down. But thls ls only out xprlnc o
grovlty. |n truth, just os th orth pulls th
oppl towords lt du to o grovltotlonol
orc, th oppl pulls th orth os wll. 1h
thlng ls, th orth ls just so roklng blg
thot lt ovrwhlms oll th othr grovlty
lntroctlons. Lvry objct wlth moss xrts
o grovltotlonol orc on vry othr objct.
Iiure z.
Choptr 2. |orcs
88
And thr ls o ormulo or colculotlng th strngths o ths orcs, os dplctd ln |lgur 2.6.
Lt`s xomln thls ormulo o blt mor closly.
- b rrs to th grovltotlonol orc, th vctor w ultlmotly wont to comput ond poss
lnto our ,$$-"b8/0%45 unctlon.
- Z ls th un|vetso| gtov|tot|ono| constont, whlch ln our world quols 6.67428 x J0
-JJ
mtrs cubd pr kllogrom pr scond squord. 1hls ls o prtty lmportont numbr l
your nom ls |sooc Nwton or Albrt Llnstln. |t`s not on lmportont numbr l you or
o Procsslng progrommr. Agoln, lt`s o constont thot w con us to mok th orcs
ln our world wokr or strongr. Just moklng lt quol to on ond lgnorlng lt lsn`t such
o trrlbl cholc lthr.
- 9
)
ond 9
>
or th mosss o objcts J ond 2. As w sow wlth Nwton`s scond low [
)

* +

j, moss ls olso somthlng w could choos to lgnor. Atr oll, shops drown
on th scrn don`t octuolly hov o physlcol moss. Howvr, l w kp ths
volus, w con crot mor lntrstlng slmulotlons ln whlch blggr" objcts xrt o
strongr grovltotlonol orc thon smollr ons.
- 1
"
rrs to th unlt vctor polntlng rom objct J to objct 2. As w`ll s ln o
momnt, w con comput thls dlrctlon vctor by subtroctlng th locotlon o on
objct rom th othr.
- /
2
rrs to th dlstonc btwn th two objcts squord. Lt`s tok o momnt to
thlnk obout thls o blt mor. Wlth vrythlng on th top o th ormuloZ, 9
)
, 9
>
th
blggr lts volu, th strongr th orc. Blg moss, blg orc. Blg Z, blg orc. Now,
whn w dlvld by somthlng, w hov th opposlt. 1h strngth o th orc ls
lnvrsly proportlonol to th dlstonc squord. 1h totthet owoy on objct ls, th
weo|et th orc, th c|oset, th sttonget.
Hopully by now th ormulo moks som sns to us. W`v lookd ot o dlogrom ond
dlssctd th lndlvlduol componnts o th ormulo. Now lt`s tlm to lgur out how w
tronslot th moth lnto Procsslng cod. Lt`s mok th ollowlng ossumptlons.
W hov two objcts, ond.
J. Loch objct hos o locotlon. ]`%028/ -80,2:87) ond ]`%028/ -80,2:87>.
2. Loch objct hos o moss. E-8,2 9,##) ond E-8,2 9,##>.
3. 1hr ls o vorlobl E-8,2 Z or th unlvrsol grovltotlonol constont.
Glvn ths ossumptlons, w wont to comput ]`%028/ E8/0%, th orc o grovlty. W`ll do lt
ln two ports. |lrst, w`ll comput th dlrctlon o th orc 1
"
ln th ormulo obov. 5cond,
w`ll colculot th strngth o th orc occordlng to th mosss ond dlstonc.
1h Notur o Cod [v005j
89
Rmmbr ln Choptr J [s pog 56j,
whn w lgurd out how to hov on objct
occlrot towords th mous? [5 |lgur
2.7.j
A vctor ls th dlrnc btwn two
polnts. 1o mok o vctor thot polnts rom
th clrcl to th mous, w slmply subtroct
on polnt rom onothr.
|n our cos, th dlrctlon o th ottroctlon orc thot objct J xrts on objct 2 ls quol to.
Lon`t orgt thot slnc w wont o unlt vctor, o vctor thot tlls us obout dlrctlon only, w`ll
nd to notmo||ze th vctor otr subtroctlng th locotlons.
OK, w`v got th dlrctlon o th orc. Now w just nd to comput th mognltud ond
scol th vctor occordlngly.
1h only problm ls thot w don`t know th
dlstonc. Z, 9,##), ond 9,##> wr oll
glvns, but w`ll nd to octuolly comput
dlstonc bor th obov cod wlll work.
Lldn`t w just mok o vctor thot polnts oll
th woy rom on locotlon to onothr?
Wouldn`t th lngth o thot vctor b th
dlstonc btwn two objcts?
Wll, l w odd just on lln o cod ond
grob th mognltud o thot vctor bor
normollzlng lt, thn w`ll hov th dlstonc.
Iiure z.;
]`%028/ &:/ ' ]`%028/N#3I4983#%C-80,2:875*
]`%028/ &:/ ' ]`%028/N#3I4-80,2:87)C-80,2:87>5*
&:/N78/9,-:F%45*
E-8,2 9 ' 4Z Q 9,##) Q 9,##>5 = 4&:#2,70% Q &:#2,70%5*
&:/N93-2495*
Iiure z.8
The vector that points from one object to
another
]`%028/ E8/0% ' ]`%028/N#3I4-80,2:87)C-80,2:87>5*
The length (magnitude) of that vector is the
distance between the two objects.
E-8,2 &:#2,70% ' E8/0%N9,?7:23&%45*
Use the formula for gravity to compute the
strength of the force.
E-8,2 9 ' 4Z Q 9,##) Q 9,##>5 = 4&:#2,70% Q
&:#2,70%5*
Choptr 2. |orcs
90
Not thot | olso rnomd th ]`%028/ dlr" os orc." Atr oll, whn w`r lnlshd wlth th
colculotlons, th ]`%028/ w stortd wlth nds up blng th octuol orc vctor w wontd oll
olong.
Now thot w`v workd out th moth ond th cod or colculotlng on ottroctlv orc
[mulotlng grovltyj, w nd to turn our ottntlon to opplylng thls tchnlqu ln th contxt o
on octuol Procsslng sktch. |n Lxompl 2.J, you moy rcoll how w crotd o slmpl d8A%/
objcto closs wlth ]`%028/`s locotlon, vloclty, ond occlrotlon os wll os on
,$$-"b8/0%45. Lt`s tok thls xoct closs ond put lt ln o sktch wlth.
- A slngl d8A%/ objct.
- A slngl V22/,028/ objct [o nw
closs thot wlll hov o lxd
locotlonj.
1h d8A%/ objct wlll xprlnc o
grovltotlonol pull towords th V22/,028/
objct, os lllustrotd ln |lgur 2.9.
W con stort by moklng th nw V22/,028/
closs vry slmplglvlng lt o locotlon ond o
moss, olong wlth o unctlon to dlsploy ltsl
[tylng moss to slzj.
And ln our moln progrom, w con odd on lnstonc o th V22/,028/ closs.
Normalize and scale the force vector to the
appropriate magnitude.
E8/0%N78/9,-:F%45*
E8/0%N93-2495*
Iiure z.p
0-,## V22/,028/ 1
Our Attractor is a simple object that doesn't
move. We just need a mass and a location.
E-8,2 9,##*
]`%028/ -80,2:87*
V22/,028/45 1
-80,2:87 ' 7%; ]`%028/4;:&2<=>C<%:?<2=>5*
9,## ' >B*
@
A8:& &:#$-,"45 1
#2/8.%4B5*
E:--4)OJC>BB5*
%--:$#%4-80,2:87N!C-80,2:87N"C9,##Q>C9,##Q>5*
@
@
1h Notur o Cod [v005j
9J
1hls ls o good structur. o moln progrom wlth o d8A%/ ond on V22/,028/ objct, ond o closs
to hondl th vorlobls ond bhovlors o movrs ond ottroctors. 1h lost plc o th puzzl
ls how to gt on objct to ottroct th othr. How do w gt ths two objcts to tolk to
och othr?
1hr or o numbr o woys w could do thls. Hr or just o w posslbllltls.
!&83 !&83 G(10'/*1 G(10'/*1
J. A unctlon thot rclvs both on Attroctor ond o Movr. ,22/,02:874,C95*
2. A unctlon ln th Attroctor closs thot rclvs o Movr. ,N,22/,02495*
3. A unctlon ln th Movr closs thot rclvs on Attroctor. 9N,22/,02%&n84,5*
4. A unctlon ln th Attroctor closs thot rclvs o Movr
ond rturns o PVctor, whlch ls th ottroctlon orc. 1hot
ottroctlon orc ls thn possd lnto th Movr's
opply|orc[j unctlon.
]`%028/ E ' ,N,22/,02495*
9N,$$-"b8/0%4E5*
ond so on. . .
|t`s good to look ot o rong o optlons or moklng objcts tolk to och othr, ond you could
probobly mok orgumnts or och o th obov posslbllltls. |`d llk to ot lost dlscord th
lrst on, slnc on objct-orlntd opprooch ls rolly o much bttr cholc ovr on orbltrory
unctlon not tld to lthr th d8A%/ or V22/,028/ closs. Whthr you plck optlon 2 or
optlon 3 ls th dlrnc btwn soylng 1h ottroctor ottrocts th movr" or 1h movr
ls ottroctd to th ottroctor." Numbr 4 ls rolly my ovorlt, ot lost ln trms o whr w
d8A%/ 9*
V22/,028/ ,*
A8:& #%23$45 1
#:F%4>BBC>BB5*
9 ' 7%; d8A%/45*
nitialize Attractor object. , ' 7%; V22/,028/45*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
Display Attractor object. ,N&:#$-,"45*
9N3$&,2%45*
9N&:#$-,"45*
@
Choptr 2. |orcs
92
or ln thls book. Atr oll, w spnt o lot o tlm worklng out th ,$$-"b8/0%45 unctlon, ond |
thlnk our xompls wlll b clorr l w contlnu wlth th som mthodology.
|n othr words, whr w onc hod.
W now hov.
And so our &/,;45 unctlon con now b wrlttn os.
W`r olmost thr. 5lnc w dcldd to put th ,22/,0245 unctlon lnsld o th V22/,028/
closs, w`ll nd to octuolly wrlt thot unctlon. 1h unctlon nds to rclv o d8A%/ objct
ond rturn o ]`%028/, l...
And whot gos lnsld thot unctlon? All o thot nlc moth w workd out or grovltotlonol
ottroctlon!
Made-up force ]`%028/ E ' 7%; ]`%028/4BN)CB5*
9N,$$-"b8/0%4E5*
Attraction force between two objects MN$:/8) 9 " &-&//)&:/*5+,
9N,$$-"b8/0%4E5*
A8:& &/,;45 1
I,0.?/837&4>JJ5*
Calculate attraction force and apply it. MN$:/8) 9 " &-&//)&:/*5+,
5-&00'3^8):$*9+,
9N3$&,2%45*
,N&:#$-,"45*
9N&:#$-,"45*
@
]`%028/ ,22/,024d8A%/ 95 1
@
]`%028/ ,22/,024d8A%/ 95 1
What's the force's direction? ]`%028/ E8/0% ' ]`%028/N#3I4-80,2:87C9N-80,2:875*
E-8,2 &:#2,70% ' E8/0%N9,?45*
E8/0%N78/9,-:F%45*
1h Notur o Cod [v005j
93
And w`r don. 5ort o. Almost. 1hr`s on smoll klnk w nd to work out. Lt`s look ot
th obov cod ogoln. 5 thot symbol or dlvld, th slosh? Whnvr w hov on o
ths, w nd to osk ourslvs th qustlon. Whot would hoppn l th dlstonc hoppnd
to b o rolly, rolly smoll numbr or [vn wors!j zro??! Wll, w know w con`t dlvld o
numbr by 0, ond l w wr to dlvld o numbr by somthlng llk 0.000J, thot ls th
qulvolnt o multlplylng thot numbr by J0,000! Ys, thls ls th rol-world ormulo or th
strngth o grovlty, but w don`t llv ln th rol world. W llv ln th ltocess|ng world. And
ln th Procsslng world, th movr could nd up blng vry, vry clos to th ottroctor ond
th orc could bcom so strong th movr would just ly woy o th scrn. And so wlth
thls ormulo, lt`s good or us to b proctlcol ond constroln th rong o whot &:#2,70% con
octuolly b. Moyb, no mottr whr th d8A%/ octuolly ls, w should nvr consldr lt lss
thon 5 plxls or mor thon 25 plxls owoy rom th ottroctor.
|or th som roson thot w nd to constroln th mlnlmum dlstonc, lt`s usul or us to do
th som wlth th moxlmum. Atr oll, l th movr wr to b, soy, 500 plxls rom th
ottroctor [not unrosonoblj, w`d b dlvldlng th orc by 250,000. 1hot orc mlght nd
up blng so wok thot lt`s olmost os l w`r not opplylng lt ot oll.
Now, lt`s rolly up to you to dcld whot bhovlors you wont. But ln th cos o, | wont
rosonobl-looklng ottroctlon thot ls nvr obsurdly wok or strong," thn constrolnlng th
dlstonc ls o good tchnlqu.
Our d8A%/ closs hosn`t chongd ot oll, so lt`s just look ot th moln progrom ond th
V22/,028/ closs os o whol, oddlng o vorlobl Z or th unlvrsol grovltotlonol constont. [On
th wbslt, you`ll lnd thot thls xompl olso hos cod thot ollows you to mov th
V22/,028/ objct wlth th mous.j
E-8,2 #2/%7?2< ' 4Z Q 9,## Q 9N9,##5 = 4&:#2,70% Q &:#2,70%5*
E8/0%N93-24#2/%7?2<5* What's the force's magnitude?
Return the force so that it can be applied! /%23/7 E8/0%*
@
&:#2,70% ' 087#2/,:74&:#2,70%CJC>J5*
Choptr 2. |orcs
94
IJ&7:5# <K@L 2'')&0'/*1
A Mover and an Attractor d8A%/ 9*
V22/,028/ ,*
A8:& #%23$45 1
#:F%4>BBC>BB5*
9 ' 7%; d8A%/45*
, ' 7%; V22/,028/45*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
Apply the attraction force from the Attractor
on the Mover.
]`%028/ E8/0% ' ,N,22/,02495*
9N,$$-"b8/0%4E8/0%5*
9N3$&,2%45*
,N&:#$-,"45*
9N&:#$-,"45*
@
0-,## V22/,028/ 1
E-8,2 9,##*
]`%028/ -80,2:87*
E-8,2 Z*
V22/,028/45 1
-80,2:87 ' 7%; ]`%028/4;:&2<=>C<%:?<2=>5*
9,## ' >B*
Z ' BND*
@
]`%028/ ,22/,024d8A%/ 95 1
]`%028/ E8/0% ' ]`%028/N#3I4-80,2:87C9N-80,2:875*
E-8,2 &:#2,70% ' E8/0%N9,?45*
Remember, we need to constrain the
distance so that our circle doesn't spin out of
control.
&:#2,70% ' 087#2/,:74&:#2,70%CJNBC>JNB5*
E8/0%N78/9,-:F%45*
E-8,2 #2/%7?2< ' 4Z Q 9,## Q 9N9,##5 = 4&:#2,70% Q &:#2,70%5*
E8/0%N93-24#2/%7?2<5*
/%23/7 E8/0%*
@
A8:& &:#$-,"45 1
#2/8.%4B5*
E:--4)OJC>BB5*
%--:$#%4-80,2:87N!C-80,2:87N"C9,##Q>C9,##Q>5*
@
@
1h Notur o Cod [v005j
95
And w could, o cours, xpond thls xompl uslng on orroy to lnclud mony d8A%/
objcts, just os w dld wlth rlctlon ond drog.
IJ&7:5# <KAL 2'')&0'/*1 4/'" 7&1U P*N#)8
Now we have 10 Movers! d8A%/KL 98A%/# ' 7%; d8A%/K)BL*
V22/,028/ ,*
A8:& #%23$45 1
#:F%4DBBCDBB5*
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
98A%/#K:L ' 7%; d8A%/4/,7&894BN)C>5C/,7&894;:&2<5C/,7&894<%:?<255*
@
, ' 7%; V22/,028/45*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
,N&:#$-,"45*
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
Each Mover is initialized randomly.
We calculate an attraction force for each
Mover object.
]`%028/ E8/0% ' ,N,22/,02498A%/#K:L5*
98A%/#K:LN,$$-"b8/0%4E8/0%5*
98A%/#K:LN3$&,2%45*
98A%/#K:LN&:#$-,"45*
@
@
Choptr 2. |orcs
96
|n th xompl obov, w hov o systm [l.. orroyj o d8A%/ objcts ond on
V22/,028/ objct. Bulld on xompl thot hos systms o both movrs ond ottroctors.
Whot l you mok th ottroctors lnvlslbl? Con you crot o pottrn/dslgn rom th
trolls o objcts movlng oround ottroctors? 5 th Mtropop Lnlm projct by Cloyton
Cubltt ond 1om Cordn [http.//procsslng.org/xhlbltlon/works/mtropop/j or on
xompl.
MO(.2&-( 0"N MO(.2&-( 0"N
|t`s worth notlng thot grovltotlonol ottroctlon ls o modl w con ollow to dvlop our
own orcs. 1hls choptr lsn`t suggstlng thot you should xcluslvly crot sktchs
thot us grovltotlonol ottroctlon. Rothr, you should b thlnklng crotlvly obout how to
dslgn your own ruls to drlv th bhovlor o objcts. |or xompl, whot hoppns l
you dslgn o orc thot ls wokr th closr lt gts ond strongr th orthr lt gts? Or
whot l you dslgn your ottroctor to ottroct orowoy objcts, but rpl clos ons?
MO(.2&-( 0"W MO(.2&-( 0"W
0"#T MI(./',&;< !''.42'- ^*. Y(Q(%-_ MI(./',&;< 0"#T MI(./',&;< !''.42'- ^*. Y(Q(%-_ MI(./',&;<
Hopully, you ound lt hlpul thot w stortd wlth o slmpl scnorloone obect otttocts
onothet obectond movd on to one obect otttocts mony obects. Howvr, lt`s llkly thot
you or golng to lnd yoursl ln o sllghtly mor complx sltuotlon. mony obects otttoct eoch
othet. |n othr words, vry objct ln o glvn systm ottrocts vry othr objct ln thot systm
[xcpt or ltslj.
W`v rolly don olmost oll o th work or thls olrody. Lt`s consldr o Procsslng sktch
wlth on orroy o d8A%/ objcts.
1h Notur o Cod [v005j
97
1h &/,;45 unctlon ls whr w nd to work som moglc. Currntly, w`r soylng. or
vry movr :, updot ond dlsploy yoursl." Now whot w nd to soy ls. or vry movr
:, b ottroctd to vry othr movr o, ond updot ond dlsploy yoursl."
1o do thls, w nd to nst o scond loop.
|n th prvlous xompl, w hod on V22/,028/ objct wlth o unctlon nomd ,22/,0245.
Now, slnc w hov movrs ottroctlng movrs, oll w nd to do ls copy th ,22/,0245
unctlon lnto th d8A%/ closs.
d8A%/KL 98A%/# ' 7%; d8A%/K)BL*
A8:& #%23$45 1
#:F%4DBBCDBB5*
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
98A%/#K:L ' 7%; d8A%/4/,7&894BN)C>5C/,7&894;:&2<5C/,7&894<%:?<255*
@
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
98A%/#K:LN3$&,2%45*
98A%/#K:LN&:#$-,"45*
@
@
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
For every Mover, check every Mover! E8/ 4:72 o ' B* o P 98A%/#N-%7?2<* o((5 1
]`%028/ E8/0% ' 98A%/#KoLN,22/,02498A%/#K:L5*
98A%/#K:LN,$$-"b8/0%4E8/0%5*
@
98A%/#K:LN3$&,2%45*
98A%/#K:LN&:#$-,"45*
@
0-,## d8A%/ 1
== V-- 2<% 82<%/ #23EE ;% <,& I%E8/% $-3#N N N
Choptr 2. |orcs
98
O cours, thr`s on smoll problm. Whn w or looklng ot vry movr : ond vry movr
o, or w OK wlth th tlms thot : quols o? |or xompl, should movr #3 ottroct movr #3?
1h onswr, o cours, ls no. | thr or lv objcts, w only wont movr #3 to ottroct 0, J, 2,
ond 4, sklpplng ltsl. And so, w lnlsh thls xompl by oddlng o slmpl condltlonol stotmnt
to sklp opplylng th orc whn l quols j.
IJ&7:5# <KBL P('(&5 &'')&0'/*1
The Mover now knows how to attract
another Mover.
]`%028/ ,22/,024d8A%/ 95 1
]`%028/ E8/0% ' ]`%028/N#3I4-80,2:87C9N-80,2:875*
E-8,2 &:#2,70% ' E8/0%N9,?45*
&:#2,70% ' 087#2/,:74&:#2,70%CJNBC>JNB5*
E8/0%N78/9,-:F%45*
E-8,2 #2/%7?2< ' 4Z Q 9,## Q 9N9,##5 = 4&:#2,70% Q &:#2,70%5*
E8/0%N93-24#2/%7?2<5*
/%23/7 E8/0%*
@
@
d8A%/KL 98A%/# ' 7%; d8A%/K>BL*
E-8,2 ? ' BND*
A8:& #%23$45 1
#:F%4DBBCDBB5*
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
98A%/#K:L ' 7%; d8A%/4/,7&894BN)C>5C/,7&894;:&2<5C/,7&894<%:?<255*
@
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
E8/ 4:72 : ' B* : P 98A%/#N-%7?2<* :((5 1
E8/ 4:72 o ' B* o P 98A%/#N-%7?2<* o((5 1
1h Notur o Cod [v005j
99
@,( M2*-/-'(E 5.*G(2' @,( M2*-/-'(E 5.*G(2'
U'(Q 0 MO(.2&-(D
C;2*.Q*.4'( ',( 2*;2(Q' *+ +*.2(- &;'* /*:. (2*-/-'(E" @./ &;'.*9:2&;< *',(.
(%(E(;'- &;'* ',( (;I&.*;E(;' ^+**9` 4 Q.(94'*._ +*. ',( 2.(4':.( '* &;'(.42' 8&',"
\*(- ',( 2.(4':.( (OQ(.&(;2( 4''.42'&*; *. .(Q:%-&*; '* ',&;<- &; &'- 8*.%97 P4;
/*: ',&;3 E*.( 4)-'.42'%/ 4;9 9(-&<; +*.2(- )4-(9 *; ',( 2.(4':.(H- 9(-&.(- *.
<*4%-7
Don't attract yourself! :E 4: S' o5 1
]`%028/ E8/0% ' 98A%/#KoLN,22/,02498A%/#K:L5*
98A%/#K:LN,$$-"b8/0%4E8/0%5*
@
@
98A%/#K:LN3$&,2%45*
98A%/#K:LN&:#$-,"45*
@
@
Chong th ottroctlon orc ln Lxompl 2.8 to o rpulslon orc. Con you crot on
xompl ln whlch oll o th d8A%/ objcts or ottroctd to th mous, but rpl och
othr? 1hlnk obout how you nd to bolonc th rlotlv strngth o th orcs ond
how to most ctlvly us dlstonc ln your orc colculotlons.
MO(.2&-( 0"#T MO(.2&-( 0"#T
Choptr 2. |orcs
J00
,"&:'#) =K Y80/55&'/*1 ,"&:'#) =K Y80/55&'/*1
Trionometr is c sine oj the times.
! >,0,+%0)'
|n Choptrs J ond 2, w corully workd out on objct-orlntd structur to mok somthlng
mov on th scrn, uslng th concpt o o vctor to rprsnt locotlon, vloclty, ond
occlrotlon drlvn by orcs ln th nvlronmnt. W could mov strolght rom hr lnto
toplcs such os portlcl systms, strlng orcs, group bhovlors, tc. | w dld thot, howvr,
w`d sklp on lmportont oro o mothmotlcs thot w`r golng to nd. &1/2!.!-$&1@ &1/2!.!-$&1@, or th
mothmotlcs o trlongls, spcllcolly rlght trlongls.
1rlgonomtry ls golng to glv us o lot o tools. W`ll gt to thlnk obout ongls ond ongulor
vloclty ond occlrotlon. 1rlg wlll toch us obout th sln ond cosln unctlons, whlch whn
usd proprly con ylld on nlc os-ln, os-out wov pottrn. |t`s golng to ollow us to
colculot mor complx orcs ln on nvlronmnt thot lnvolvs ongls, such os o pndulum
swlnglng or o box slldlng down on lnclln.
5o thls choptr ls o blt o o mlshmosh. W`ll stort wlth th boslcs o ongls ln Procsslng ond
covr mony trlgonomtrlc toplcs, tylng lt oll lnto orcs ot th nd. And by toklng thls brok
now, w`ll olso pov th woy or mor odvoncd xompls thot rqulr trlg lotr ln thls book.
="# !;<%(- ="# !;<%(-
OK. Bor w con do ony o thls stu, w nd to mok sur w undrstond whot lt mons to
b on ongl ln Procsslng. | you hov xprlnc wlth Procsslng, you`v undoubtdly
ncountrd thls lssu whll uslng th /82,2%45 unctlon to rotot ond spln objcts.
1h Notur o Cod [v005j
J0J
1h lrst ordr o buslnss ls to covr 1(8/(.) 1(8/(.) ond 8$21$$) 8$21$$). You`r probobly omlllor wlth
th concpt o on ongl ln 8$21$$) 8$21$$). A ull rototlon gos rom 0 to 360 dgrs. 90 dgrs
[o rlght onglj ls J/4th o 360, shown blow os two prpndlculor llns.
|t`s olrly lntultlv or us to thlnk o ongls ln trms o dgrs. |or xompl, th squor ln
|lgur 3.2 ls rototd 45 dgrs oround lts cntr.
Procsslng, howvr, rqulrs ongls to b spclld ln 1(8/(.) 1(8/(.). A rodlon ls o unlt o
mosurmnt or ongls dlnd by th rotlo o th lngth o th orc o o clrcl to th rodlus
o thot clrcl. On rodlon ls th ongl ot whlch thot rotlo quols on [s |lgur 3.Jj. J80
dgrs P| rodlons, 360 dgrs 2'P| rodlons, 90 dgrs P|/2 rodlons, tc.
Iiure .:
Iiure .
Choptr 3. Osclllotlon
J02
1h ormulo to convrt rom dgrs to rodlons ls.
rodlons 2 ' P| ' [dgrs / 360j
1honkully, l w prr to thlnk ln dgrs but cod wlth rodlons, Procsslng moks thls osy.
1h /,&:,7#45 unctlon wlll outomotlcolly convrt volus rom dgrs to rodlons, ond th
constonts ]c ond n+Ua]c provld convnlnt occss to ths commonly usd numbrs
[qulvolnt to J80 ond 360 dgrs, rspctlvlyj. 1h ollowlng cod, or xompl, wlll rotot
shops by 60 dgrs.
| you or not omlllor wlth how rototlon ls lmplmntd ln Procsslng, | would suggst thls
tutorlol. Procsslng - 1ronsorm 2L [http.//www.procsslng.org/lornlng/tronsorm2d/j.
6,4' &- 5C7 6,4' &- 5C7
1h mothmotlcol constont pl [or nj ls o rol numbr dlnd os th rotlo o o clrcl`s
clrcumrnc [th dlstonc oround th prlmtrj to lts dlomtr [o strolght lln thot
posss through th clrcl`s cntrj. |t ls quol to opproxlmotly 3.J4J59 ond con b
occssd ln Procsslng wlth th bullt-ln vorlobl ]c.
Iiure .
E-8,2 ,7?-% ' /,&:,7#4GB5*
/82,2%4,7?-%5*
1h Notur o Cod [v005j
J03
Rotot o boton-llk objct [s blowj oround lts cntr uslng 2/,7#-,2%45 ond
/82,2%45.
MO(.2&-( ="# MO(.2&-( ="#
="0 !;<:%4. ]*'&*; ="0 !;<:%4. ]*'&*;
Rmmbr oll thls stu?
'8:&/28# " '8:&/28# K L$'8:2/3
L$'8:2/3 " L$'8:2/3 K &::$'$)&/28#
1h stu w ddlcotd olmost oll o Choptrs J ond 2 to? Wll, w con opply xoctly th
som loglc to o rototlng objct.
&#G'$ " &#G'$ K &#G4'&) L$'8:2/3
&#G4'&) L$'8:2/3 " &#G4'&) L$'8:2/3 K &#G4'&) &::$'$)&/28#
|n oct, th obov ls octuolly slmplr thon whot w stortd wlth bcous on ongl ls o sco|ot
quontltyo slngl numbr, not o vctor!
slng th onswr rom Lxrcls 3.J obov, lt`s soy w wontd to rotot o boton ln
Procsslng by som ongl. W would hov cod llk.
Addlng ln our prlnclpls o motlon brlngs us to th ollowlng xompl.
2/,7#-,2%4;:&2<=>C<%:?<2=>5*
/82,2%4,7?-%5*
-:7%46JBCBCJBCB5*
%--:$#%4JBCBCXCX5*
%--:$#%46JBCBCXCX5*
Choptr 3. Osclllotlon
J04
IJ&7:5# =K;L 216(5&) 7*'/*1 (8/16 )*'&'#WX
1h boton storts onscrn wlth no rototlon ond thn splns ostr ond ostr os th ongl o
rototlon occlrots.
1hls ldo con b lncorporotd lnto our d8A%/ objct. |or xompl, w con odd th vorlobls
rlotd to ongulor motlon to our d8A%/.
Location E-8,2 ,7?-% ' B*
Velocity E-8,2 ,`%-80:2" ' B*
Acceleration E-8,2 ,V00%-%/,2:87 ' BNBB)*
A8:& #%23$45 1
#:F%4>BBC>BB5*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
E:--4)OJ5*
#2/8.%4B5*
/%02d8&%4MhknhY5*
2/,7#-,2%4;:&2<=>C<%:?<2=>5*
/82,2%4,7?-%5*
-:7%46JBCBCJBCB5*
%--:$#%4JBCBCXCX5*
%--:$#%46JBCBCXCX5*
Angular equivalent of
velocity.add(acceleration);
,`%-80:2" (' ,V00%-%/,2:87*
Angular equivalent of location.add(velocity); ,7?-% (' ,`%-80:2"*
@
1h Notur o Cod [v005j
J05
And thn ln 3$&,2%45, w updot both locotlon ond ongl occordlng to th som olgorlthm!
O cours, or ony o thls to mottr, w olso would nd to rotot th objct whn dlsploylng
lt.
Now, l w wr to octuolly go ohod ond run th obov cod, w wouldn`t s onythlng
nw. 1hls ls bcous th ongulor occlrotlon [E-8,2 ,V00%-%/,2:87 ' B*j ls lnltlollzd to
zro. |or th objct to rotot, w nd to glv lt on occlrotlon! Crtolnly, w could hord-
cod ln o dlrnt numbr.
0-,## d8A%/ 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
E-8,2 9,##*
E-8,2 ,7?-% ' B*
E-8,2 ,`%-80:2" ' B*
E-8,2 ,V00%-%/,2:87 ' B*
A8:& 3$&,2%45 1
Regular old-fashioned motion A%-80:2"N,&&4,00%-%/,2:875*
-80,2:87N,&&4A%-80:2"5*
Newfangled angular motion ,`%-80:2" (' ,V00%-%/,2:87*
,7?-% (' ,`%-80:2"*
,00%-%/,2:87N93-24B5*
@
A8:& &:#$-,"45 1
#2/8.%4B5*
E:--4)OJC>BB5*
/%02d8&%4MhknhY5*
pushMatrix() and popMatrix() are
necessary so that the rotation of this shape
doesn't affect the rest of our world.
$3#<d,2/:!45*
Set the origin at the shape's location. 2/,7#-,2%4-80,2:87N!C-80,2:87N"5*
Rotate by the angle. /82,2%4,7?-%5*
/%024BCBC9,##Q)GC9,##Q)G5*
$8$d,2/:!45*
@
E-8,2 ,V00%-%/,2:87 ' BNB)*
Choptr 3. Osclllotlon
J06
Howvr, w con produc o mor lntrstlng rsult by dynomlcolly osslgnlng on ongulor
occlrotlon occordlng to orcs ln th nvlronmnt. Now, w could hod or down thls rood,
trylng to modl th physlcs o ongulor occlrotlon uslng th concpts o torqu
[http.//n.wlklpdlo.org/wlkl/1orquj ond momnt o lnrtlo [http.//n.wlklpdlo.org/wlkl/
Momnt_o_lnrtloj. Nvrthlss, thls lvl o slmulotlon ls byond th scop o thls book.
[W wlll s mor obout modllng ongulor occlrotlon wlth o pndulum lotr ln thls choptr,
os wll os look ot how Box2L rollstlcolly modls rototlonol motlon ln Choptr 5.j
|or now, o qulck ond dlrty solutlon wlll do. W con produc rosonobl rsults by slmply
colculotlng ongulor occlrotlon os o unctlon o th objct`s occlrotlon vctor. Hr`s on
such xompl.
Ys, thls ls compltly orbltrory. But lt dos do somthlng. | th objct ls occlrotlng to th
rlght, lts ongulor rototlon occlrots ln o clockwls dlrctlon, occlrotlon to th lt rsults ln
o countrclockwls rototlon. O cours, lt`s lmportont to thlnk obout scol ln thls cos. 1h x
componnt o th occlrotlon vctor mlght b o quontlty thot`s too lorg, couslng th objct
to spln ln o woy thot looks rldlculous or unrollstlc. 5o dlvldlng th x componnt by som
volu, or prhops constrolnlng th ongulor vloclty to o rosonobl rong, could rolly hlp.
Hr`s th ntlr 3$&,2%45 unctlon wlth ths twoks oddd.
IJ&7:5# =K<L G*)0#8 4/'" W&)E/')&)UX &16(5&) 7*'/*1
,V00%-%/,2:87 ' ,00%-%/,2:87N!*
A8:& 3$&,2%45 1
A%-80:2"N,&&4,00%-%/,2:875*
-80,2:87N,&&4A%-80:2"5*
Calculate angular acceleration according to
acceleration's horizontal direction and
magnitude.
,V00%-%/,2:87 ' ,00%-%/,2:87N! = )BNB*
,`%-80:2" (' ,V00%-%/,2:87*
1h Notur o Cod [v005j
J07
Use constrain() to ensure that angular
velocity doesn't spin out of control.
,`%-80:2" ' 087#2/,:74,`%-80:2"C6BN)CBN)5*
,7?-% (' ,`%-80:2"*
,00%-%/,2:87N93-24B5*
@
5tp J. Crot o slmulotlon whr objcts or shot out o o connon. Loch objct
should xprlnc o suddn orc whn shot [just oncj os wll os grovlty [olwoys
prsntj.
5tp 2. Add rototlon to th objct to modl lts spln os lt ls shot rom th connon. How
rollstlc con you mok lt look?
MO(.2&-( ="0 MO(.2&-( ="0
="= @.&<*;*E('./ ="= @.&<*;*E('./
| thlnk lt moy b tlm. W`v lookd ot ongls, w`v spun on objct. |t`s tlm or.
sohcohtoo. Ys, sohcohtoo. 1hls smlngly nonsnslcol word ls octuolly th oundotlon or o
lot o computr grophlcs work. A boslc undrstondlng o trlgonomtry ls ssntlol l you
wont to colculot on ongl, lgur out th dlstonc btwn polnts, work wlth clrcls, orcs,
or llns. And sohcohtoo ls o mnmonlc dvlc [olblt o somwhot obsurd onj or whot th
trlgonomtrlc unctlons sln, cosln, ond tongnt mon.
- )!+ )!+. sln opposlt / hypotnus
- %(+ %(+. cosln odjocnt / hypotnus
- &!( &!(. tongnt opposlt / odjocnt
Iiure .(
Choptr 3. Osclllotlon
J08
1ok o look ot |lgur 3.4 ogoln. 1hr`s no
nd to mmorlz lt, but mok sur you l
comortobl wlth lt. Lrow lt ogoln yoursl.
Now lt`s drow lt o sllghtly dlrnt woy
[|lgur 3.5j.
5 how w crot o rlght trlongl out o o
vctor? 1h vctor orrow ltsl ls th
hypotnus ond th componnts o th
vctor [! ond "j or th slds o th trlongl.
1h ongl ls on oddltlonol mons or
spclylng th vctor`s dlrctlon [or
hodlng"j.
Bcous th trlgonomtrlc unctlons ollow us to stobllsh o rlotlonshlp btwn th
componnts o o vctor ond lts dlrctlon mognltud, thy wlll prov vry usul throughout
thls book. W`ll bgln by looklng ot on xompl thot rqulrs th tongnt unctlon.
Iiure .
="> 5*&;'&;< &; ',( \&.(2'&*; *+ ]*I(E(;' ="> 5*&;'&;< &; ',( \&.(2'&*; *+ ]*I(E(;'
Lt`s go oll th woy bock to Lxompl J.J0, whlch oturs o d8A%/ objct occlrotlng towords
th mous.
You mlght notlc thot olmost oll o th shops w`v bn drowlng so or or clrcls. 1hls ls
convnlnt or o numbr o rosons, on o whlch ls thot w don`t hov to consldr th
qustlon o rototlon. Rotot o clrcl ond, wll, lt looks xoctly th som. Howvr, thr coms
o tlm ln oll motlon progrommrs` llvs whn thy wont to drow somthlng on th scrn thot
polnts ln th dlrctlon o movmnt. Prhops you or drowlng on ont, or o cor, or o spocshlp.
And whn w soy "polnt ln th dlrctlon o movmnt," whot w or rolly soylng ls rotot
occordlng to th vloclty vctor." Vloclty ls o vctor, wlth on ! ond o " componnt, but to
rotot ln Procsslng w nd on ongl, ln rodlons. Lt`s drow our trlgonomtry dlogrom on
mor tlm, wlth on objct`s vloclty vctor [|lgur 3.6j.
1h Notur o Cod [v005j
J09
|t |t tongent(oI b
then then o otctongent(bI
|t |t tongent(ong|eI ve|oc|ty
y
/ ve|oc|ty
x
then then ong|e otctongent(ve|oc|ty
y
/ ve|oc|ty
x
I
OK. W know thot th dlnltlon o tongnt
ls.
4:&;0&4(:&;<0)
$0<5324 %
%
$0<5324 %
"
1h problm wlth th obov ls thot w
know vloclty, but w don`t know th
ongl. W hov to solv or th ongl. 1hls
ls whr o spclol unctlon known os
|nvetse tongent coms ln, somtlms
rrrd to os otctongent or ton
-!
. [1hr ls
olso on |nvetse s|ne ond on |nvetse cos|ne.j
| th tongnt o som volu , quols som volu I, thn th lnvrs tongnt o I quols ,.
|or xompl.
5 how thot ls th lnvrs? 1h obov now ollows us to solv or th ongl.
Now thot w hov th ormulo, lt`s s whr lt should go ln our movr`s &:#$-,"45
unctlon. Notlc thot ln Procsslng, th unctlon or orctongnt ls colld ,2,745.
Now th obov cod ls prtty dorn clos, ond olmost works. W stlll hov o blg problm,
though. Lt`s consldr th two vloclty vctors dplctd blow.
Iiure .
A8:& &:#$-,"45 1
Solve for angle by using atan(). E-8,2 ,7?-% ' ,2,74A%-80:2"N"=A%-80:2"N!5*
#2/8.%4B5*
E:--4)OJ5*
$3#<d,2/:!45*
/%02d8&%4MhknhY5*
2/,7#-,2%4-80,2:87N!C-80,2:87N"5*
Rotate according to that angle. /82,2%4,7?-%5*
/%024BCBCHBC)B5*
$8$d,2/:!45*
@
Choptr 3. Osclllotlon
JJ0
1hough suprlclolly slmllor, th two vctors polnt ln qult dlrnt dlrctlonsopposlt
dlrctlons, ln oct! Howvr, l w wr to opply our ormulo to solv or th ongl to och
vctor.
ND _ &#G'$ " &/&#*T<;E+ " &/&#*TD->=+ " T?-`>@>`=> )&12&#. " T=E 1$G)$$.
N> _ &#G'$ " &/&#*<;TE+ " &/&#*TD->=+ " T?-`>@>`=> )&12&#. " T=E 1$G)$$.
.w gt th som ongl or och vctor. 1hls con`t b rlght or both, th vctors polnt ln
opposlt dlrctlons! 1h thlng ls, thls ls o prtty common problm ln computr grophlcs.
Rothr thon slmply uslng ,2,745 olong wlth o bunch o condltlonol stotmnts to occount or
posltlv/ngotlv scnorlos, Procsslng [olong wlth prtty much oll progrommlng
nvlronmntsj hos o nlc unctlon colld ,2,7>45 thot dos lt or you.
IJ&7:5# =K=L 9*/1'/16 /1 '"# -/)#0'/*1 *+ 7*'/*1
Iiure .;
A8:& &:#$-,"45 1
Using atan2() to account for all possible
directions
E-8,2 ,7?-% ' ,2,7>4A%-80:2"N"CA%-80:2"N!5*
#2/8.%4B5*
E:--4)OJ5*
$3#<d,2/:!45*
/%02d8&%4MhknhY5*
2/,7#-,2%4-80,2:87N!C-80,2:87N"5*
1h Notur o Cod [v005j
JJJ
1o slmplly thls vn urthr, th ]`%028/ closs ltsl provlds o unctlon colld
<%,&:7?>\45, whlch toks cor o colllng ,2,7>45 or you so you con gt th dlrctlon
ongl, ln rodlons, or ony Procsslng ]`%028/.
Rotate according to that angle. /82,2%4,7?-%5*
/%024BCBCHBC)B5*
$8$d,2/:!45*
@
The easiest way to do this! E-8,2 ,7?-% ' A%-80:2"N<%,&:7?>\45*
Crot o slmulotlon o o vhlcl thot you con drlv oround th scrn uslng th orrow
kys. lt orrow occlrots th cor to th lt, rlght to th rlght. 1h cor should polnt
ln th dlrctlon ln whlch lt ls currntly movlng.
MO(.2&-( ="= MO(.2&-( ="=
="? 5*%4. I-" P4.'(-&4; P**.9&;4'(- ="? 5*%4. I-" P4.'(-&4; P**.9&;4'(-
Any tlm w dlsploy o shop ln Procsslng, w hov to spcly o plxl locotlon, o st o !
ond " coordlnots. 1hs coordlnots or known os M(1&$)/(. %!!18/.(&$) M(1&$)/(. %!!18/.(&$), nomd or
Rn Lscorts, th |rnch mothmotlclon who dvlopd th ldos bhlnd Cortslon
spoc.
Anothr usul coordlnot systm known os A!'(1 %!!18/.(&$) A!'(1 %!!18/.(&$) dscrlbs o polnt ln spoc
os on ongl o rototlon oround th orlgln ond o rodlus rom th orlgln. 1hlnklng obout thls ln
trms o o vctor.
Cortslon coordlnotth x,y componnts o o vctor
Polor coordlnotth mognltud [lngthj ond dlrctlon [onglj o o vctor
Procsslng`s drowlng unctlons, howvr, don`t undrstond polor coordlnots. Whnvr w
wont to dlsploy somthlng ln Procsslng, w hov to spcly locotlons os (x,yI Cortslon
coordlnots. Howvr, somtlms lt ls o grot dol mor convnlnt or us to thlnk ln polor
coordlnots whn dslgnlng. Hopplly or us, wlth trlgonomtry w con convrt bock ond
orth btwn polor ond Cortslon, whlch ollows us to dslgn wlth whotvr coordlnot
systm w hov ln mlnd but olwoys drow wlth Cortslon coordlnots.
Choptr 3. Osclllotlon
JJ2
.2#$*/H$/&+ " 3;) a 3 " ) F .2#$*/H$/&+
:8.2#$*/H$/&+ " I;) a I " ) F :8.2#$*/H$/&+
|or xompl, l / ls 75 ond 2<%2, ls 45 dgrs [or P|/4 rodlonsj, w con colculot ! ond " os
blow. 1h unctlons or sln ond cosln ln Procsslng or #:745 ond 08#45, rspctlvly.
1hy och tok on orgumnt, on ongl mosurd ln rodlons.
1hls typ o convrslon con b usul ln crtoln oppllcotlons. |or xompl, to mov o shop
olong o clrculor poth uslng Cortslon coordlnots ls not so osy. Wlth polor coordlnots, on
th othr hond, lt`s slmpl. lncrmnt th ongl!
Hr`s how lt ls don wlth globol vorlobls / ond 2<%2,.
Iiure .8: The Greel letter 0 (thetc) is ojten used to denote cn cnle. Since c polcr coordincte is
contentioncll rejerred to cs (r, 0), ue'll use thetc cs c tcricble ncme uhen rejerrin to cn cnle.
E-8,2 / ' OJ*
E-8,2 2<%2, ' ]c = D*
Converting from polar (r,theta) to Cartesian
(x,y)
E-8,2 ! ' / Q 08#42<%2,5*
E-8,2 " ' / Q #:742<%2,5*
1h Notur o Cod [v005j
JJ3
IJ&7:5# =K>L 9*5&) '* ,&)'#8/&1
E-8,2 / ' OJ*
E-8,2 2<%2, ' B*
A8:& #%23$45 1
#:F%4>BBC>BB5*
I,0.?/837&4>JJ5*
#9882<45*
@
A8:& &/,;45 1
Polar coordinates (r,theta) are converted
to Cartesian (x,y) for use in the ellipse()
function.
E-8,2 ! ' / Q 08#42<%2,5*
E-8,2 " ' / Q #:742<%2,5*
78[2/8.%45*
E:--4B5*
%--:$#%4!(;:&2<=>C "(<%:?<2=>C )GC )G5*
2<%2, (' BNB)*
@
Choptr 3. Osclllotlon
JJ4
slng Lxompl 3.4 os o bosls, drow o splrol poth. 5tort ln th cntr ond mov outwords.
Not thot thls con b don by only chonglng on lln o cod ond oddlng on lln o
cod!
MO(.2&-( ="> MO(.2&-( =">
5lmulot th spocshlp ln th gom Astrolds. |n cos you orn`t omlllor wlth Astrolds,
hr ls o brl dscrlptlon. A spocshlp [rprsntd os o trlonglj loots ln two
dlmnslonol spoc. 1h lt orrow ky turns th spocshlp countrclockwls, th rlght
orrow ky, clockwls. 1h z ky opplls o thrust" orc ln th dlrctlon th spocshlp ls
polntlng.
MO(.2&-( ="? MO(.2&-( ="?
1h Notur o Cod [v005j
JJ5
="K F-2&%%4'&*; !EQ%&':9( 4;9 5(.&*9 ="K F-2&%%4'&*; !EQ%&':9( 4;9 5(.&*9
Ar you omozd yt? W`v sn som prtty grot uss o tongnt [or lndlng th ongl o
o vctorj ond sln ond cosln [or convrtlng rom polor to Cortslon coordlnotsj. W could
stop rlght hr ond b sotlsld. But w`r not golng to. 1hls ls only th bglnnlng. Whot
sln ond cosln con do or you gos byond mothmotlcol ormulos ond rlght trlongls.
Lt`s tok o look ot o groph o th sln unctlon, whr y s|ne(xI.
You`ll notlc thot th output o th sln unctlon ls o smooth curv oltrnotlng btwn J
ond J. 1hls typ o o bhovlor ls known os !)%/''(&/!. !)%/''(&/!., o prlodlc movmnt btwn two
polnts. Plucklng o gultor strlng, swlnglng o pndulum, bounclng on o pogo stlckths or
oll xompls o osclllotlng motlon.
And so w hopplly dlscovr thot w con slmulot osclllotlon ln o Procsslng sktch by
osslgnlng th output o th sln unctlon to on objct`s locotlon. Not thot thls wlll ollow th
som mthodology w opplld to Prlln nols ln th |ntroductlon [s pog J7j.
Lt`s bgln wlth o rolly boslc scnorlo. W wont o clrcl to osclllot rom th lt sld to th
rlght sld o o Procsslng wlndow.
Iiure .p: = sine(x)
Choptr 3. Osclllotlon
JJ6
1hls ls whot ls known os )/-A'$ +(1-!./% -!&/!. )/-A'$ +(1-!./% -!&/!. [or, to b onclr, th prlodlc slnusoldol
osclllotlon o on objct"j. |t`s golng to b o slmpl progrom to wrlt, but bor w gt lnto th
cod, lt`s omlllorlz ourslvs wlth som o th trmlnology o osclllotlon [ond wovsj.
5lmpl hormonlc motlon con b xprssd os ony locotlon [ln our cos, th ! locotlonj os o
unctlon o tlm, wlth th ollowlng two lmnts.
- D-A'/&:8$ D-A'/&:8$. 1h dlstonc rom th cntr o motlon to lthr xtrm
- N$1/!8 N$1/!8. 1h omount o tlm lt toks or on complt cycl o motlon
Looklng ot th groph o sln [|lgur 3.9j, w con s thot th omplltud ls J ond th prlod ls
n+Ua]c, th output o sln nvr rlss obov J or blow -J, ond vry n+Ua]c rodlons [or 360
dgrsj th wov pottrn rpots.
Now, ln th Procsslng world w llv ln, whot ls omplltud ond whot ls prlod? Amplltud con
b mosurd rothr oslly ln plxls. |n th cos o o wlndow 200 plxls wld, w would
osclllot rom th cntr J00 plxls to th rlght ond J00 plxls to th lt. 1hror.
let|od ls th omount o tlm lt toks or on cycl, but whot ls tlm ln our Procsslng world? |
mon, crtolnly w could soy w wont th clrcl to osclllot vry thr sconds. And w
could trock th mllllscondsuslng 9:--:#45 ln Procsslng ond com up wlth on loborot
olgorlthm or osclllotlng on objct occordlng to rol-world tlm. But or us, rol-world tlm
dosn`t rolly mottr. 1h rol mosur o tlm ln Procsslng ls ln roms. 1h osclllotlng
motlon should rpot vry 30 roms, or 50 roms, or J000 roms, tc.
Onc w hov th omplltud ond prlod, lt`s tlm to wrlt o ormulo to colculot x os o
unctlon o tlm, whlch w now know ls th currnt rom count.
Our amplitude is measured in pixels. E-8,2 ,9$-:23&% ' )BB*
Our period is measured in frames (our unit
of time for animation).
E-8,2 $%/:8& ' )>B*
E-8,2 ! ' ,9$-:23&% Q 08#4n+Ua]c Q E/,9%M8372 = $%/:8&5*
1h Notur o Cod [v005j
JJ7
Lt`s dlssct th ormulo o blt mor ond try to undrstond och componnt. 1h lrst ls
probobly th oslst. Whotvr coms out o th cosln unctlon w multlply by omplltud.
W know thot cosln wlll osclllot btwn -J ond J. | w tok thot volu ond multlply lt by
omplltud thn w`ll gt th dslrd rsult. o volu osclllotlng btwn -omplltud ond
omplltud. [Not. thls ls olso o ploc whr w could us Procsslng`s 9,$45 unctlon to
mop th output o cosln to o custom rong.j
Now, lt`s look ot whot ls lnsld th cosln unctlon.
b%cdMe F 9)&5$f84#/ ; 0$)281
Whot`s golng on hr? Lt`s stort wlth whot w know. W know thot cosln wlll rpot vry
2'P| rodlonsl.. lt wlll stort ot 0 ond rpot ot 2'P|, 4'P|, 6'P|, tc. | th prlod ls J20, thn
w wont th osclllotlng motlon to rpot whn th E/,9%M8372 ls ot J20 roms, 240 roms,
360 roms, tc. E/,9%M8372 ls rolly th only vorlobl, lt storts ot 0 ond counts upword.
Lt`s tok o look ot whot th ormulo yllds wlth thos volus.
+)&7#,*(1' +)&7#,*(1' +)&7#,*(1' Z :#)/*- +)&7#,*(1' Z :#)/*-
!MY[9F \ +)&7#,*(1' Z !MY[9F \ +)&7#,*(1' Z
:#)/*- :#)/*-
0 0 0
60 0.5 P|
J20 J 1WO_P|
240 2 2 ' 1WO_P| [or 4' P|j
tc.
E/,9%M8372 dlvldd by $%/:8& tlls us how mony cycls w`v compltdor w holwoy
through th lrst cycl? Hov w compltd two cycls? By multlplylng thot numbr by
n+Ua]c, w gt th rsult w wont, slnc n+Ua]c ls th numbr o rodlons rqulrd or on
cosln [or slnj to complt on cycl.
Wropplng thls oll up, hr`s th Procsslng xompl thot osclllots th ! locotlon o o clrcl
wlth on omplltud o J00 plxls ond o prlod o J20 roms.
Choptr 3. Osclllotlon
JJ8
IJ&7:5# =K? O/7:5# ]&)7*1/0 P*'/*1
|t`s olso worth mntlonlng th trm ;1$9:$.%@ ;1$9:$.%@. th numbr o cycls pr tlm unlt. |rquncy
ls quol to J dlvldd by $%/:8&. | th prlod ls J20 roms, thn only J/J20th o o cycl ls
compltd ln on rom, ond so rquncy J/J20. |n th obov xompl, w slmply chos to
dln th rot o osclllotlon ln trms o prlod ond thror dld not nd o vorlobl or
rquncy.
A8:& #%23$45 1
#:F%4>BBC>BB5*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
E-8,2 $%/:8& ' )>B*
E-8,2 ,9$-:23&% ' )BB*
E-8,2 ! ' ,9$-:23&% Q 08#4n+Ua]c Q E/,9%M8372 = $%/:8&5*
#2/8.%4B5*
E:--4)OJ5*
2/,7#-,2%4;:&2<=>C<%:?<2=>5*
-:7%4BCBC!CB5*
%--:$#%4!CBC>BC>B5*
@
Calculating horizontal location according to
the formula for simple harmonic motion
slng th sln unctlon, crot o slmulotlon o o wlght [somtlms rrrd to os o
bob"j thot hongs rom o sprlng rom th top o th wlndow. s th 9,$45 unctlon to
colculot th vrtlcol locotlon o th bob. Lotr ln thls choptr, w`ll s how to rcrot
thls som slmulotlon by modllng th orcs o o sprlng occordlng to Hook`s low.
MO(.2&-( ="K MO(.2&-( ="K
="L F-2&%%4'&*; 8&', !;<:%4. R(%*2&'/ ="L F-2&%%4'&*; 8&', !;<:%4. R(%*2&'/
An undrstondlng o th concpts o osclllotlon, omplltud, ond rquncy/prlod ls otn
rqulrd ln th cours o slmulotlng rol-world bhovlors. Howvr, thr ls o sllghtly oslr
woy to rwrlt th obov xompl wlth th som rsult. Lt`s tok on mor look ot our
osclllotlon ormulo.
And lt`s rwrlt lt o sllghtly dlrnt woy.
E-8,2 ! ' ,9$-:23&% Q 08#4n+Ua]c Q E/,9%M8372 = $%/:8&5*
1h Notur o Cod [v005j
JJ9
| w cor obout prclsly dlnlng th prlod o osclllotlon ln trms o roms o onlmotlon,
w mlght nd th ormulo th woy w lrst wrot lt, but w con just os oslly rwrlt our
xompl uslng th concpt o ongulor vloclty [ond occlrotlonj rom sctlon 3.2 [s pog
J04j. Assumlng.
ln &/,;45, w con slmply soy.
,7?-% ls our som volu thot lncrmnts slowly."
IJ&7:5# =K@ O/7:5# ]&)7*1/0 P*'/*1 FF
Just bcous w`r not rrnclng lt dlrctly dosn`t mon thot w`v llmlnotd th
concpt o $%/:8&. Atr oll, th grotr th ongulor vloclty, th ostr th clrcl wlll
osclllot [thror lowrlng th prlodj. |n oct, th numbr o tlms lt toks to odd up th
ongulor vloclty to gt to n+Ua]c ls th prlod or.
0$)281 " b%cdMe ; &#G4'&) L$'8:2/3
E-8,2 ! ' ,9$-:23&% Q 08# 4 #89% A,-3% 2<,2 :70/%9%72# #-8;-" 5*
E-8,2 ,7?-% ' B*
E-8,2 ,`%-80:2" ' BNBJ*
,7?-% (' ,`%-80:2"*
E-8,2 ! ' ,9$-:23&% Q 08#4,7?-%5*
E-8,2 ,7?-% ' B*
E-8,2 ,`%-80:2" ' BNBJ*
A8:& #%23$45 1
#:F%4>BBC>BB5*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
E-8,2 ,9$-:23&% ' )BB*
E-8,2 ! ' ,9$-:23&% Q 08#4,7?-%5*
Using the concept of angular velocity to
increment an angle variable
,7?-% (' ,`%-80:2"*
%--:$#%d8&%4MhknhY5*
#2/8.%4B5*
E:--4)OJ5*
2/,7#-,2%4;:&2<=>C<%:?<2=>5*
-:7%4BCBC!CB5*
%--:$#%4!CBC>BC>B5*
@
Choptr 3. Osclllotlon
J20
Lt`s xpond thls xompl o blt mor ond crot on U#0:--,28/ closs. And lt`s ossum w
wont th osclllotlon to hoppn olong both th x-oxls [os obovj ond th y-oxls. 1o do thls, w`ll
nd two ongls, two ongulor vlocltls, ond two omplltuds [on or och oxlsj. Anothr
prct opportunlty or ]`%028/!
IJ&7:5# =KAL Y80/55&'*) *E^#0'8
0-,## U#0:--,28/ 1
Using a PVector to track two angles! ]`%028/ ,7?-%*
]`%028/ A%-80:2"*
]`%028/ ,9$-:23&%*
U#0:--,28/45 1
,7?-% ' 7%; ]`%028/45*
A%-80:2" ' 7%; ]`%028/4/,7&8946BNBJCBNBJ5C/,7&8946BNBJCBNBJ55*
,9$-:23&% ' 7%; ]`%028/4/,7&894;:&2<=>5C/,7&894<%:?<2=>55*
@
A8:& 8#0:--,2%45 1
,7?-%N,&&4A%-80:2"5*
@
A8:& &:#$-,"45 1
Random velocities and amplitudes
Oscillating on the x-axis E-8,2 ! ' #:74,7?-%N!5Q,9$-:23&%N!*
Oscillating on the y-axis E-8,2 " ' #:74,7?-%N"5Q,9$-:23&%N"*
$3#<d,2/:!45*
2/,7#-,2%4;:&2<=>C<%:?<2=>5*
#2/8.%4B5*
E:--4)OJ5*
1h Notur o Cod [v005j
J2J
Drawing the Oscillator as a line connecting
a circle
-:7%4BCBC!C"5*
%--:$#%4!C"C)GC)G5*
$8$d,2/:!45*
@
@
1ry lnltlollzlng och U#0:--,28/ objct wlth vlocltls ond omplltuds thot or not
rondom to crot som sort o rgulor pottrn. Con you mok th osclllotors oppor
to b th lgs o o lnsct-llk crotur?
MO(.2&-( ="L MO(.2&-( ="L
|ncorporot ongulor occlrotlon lnto th U#0:--,28/ objct.
MO(.2&-( ="N MO(.2&-( ="N
="N 64I(- ="N 64I(-
| you`r soylng to yoursl, m, thls ls oll grot ond vrythlng, but whot | rolly wont ls to
drow o wov onscrn," wll, thn, th tlm hos com. 1h thlng ls, w`r obout 90 thr.
Whn w osclllot o slngl clrcl up ond down occordlng to th sln unctlon, whot w or
dolng ls looklng ot o slngl polnt olong th x-oxls o o wov pottrn. Wlth o llttl ponoch
ond o E8/ loop, w con ploc o whol bunch o ths osclllotlng clrcls nxt to och othr.
1hls wovy pottrn could b usd ln th dslgn o th body or oppndogs o o crotur, os
wll os to slmulot o sot suroc [such os wotrj.
Hr, w`r golng to ncountr th som qustlons o omplltud [hlght o pottrnj ond
prlod. |nstod o prlod rrrlng to tlm, howvr, slnc w`r looklng ot th ull wov, w
Choptr 3. Osclllotlon
J22
con tolk obout prlod os th wldth [ln plxlsj o o ull wov cycl. And just os wlth slmpl
osclllotlon, w hov th optlon o computlng th wov pottrn occordlng to o prcls prlod or
slmply ollowlng th modl o ongulor vloclty.
Lt`s go wlth th slmplr cos, ongulor vloclty. W know w nd to stort wlth on ongl, on
ongulor vloclty, ond on omplltud.
1hn w`r golng to loop through oll o th ! volus whr w wont to drow o polnt o th
wov. Lt`s soy vry 24 plxls or now. |n thot loop, w`r golng to wont to do thr thlngs.
J. Colculot th y locotlon occordlng to omplltud ond sln o th ongl.
2. Lrow o clrcl ot th (x,yI locotlon.
3. |ncrmnt th ongl occordlng to ongulor vloclty.
Lt`s look ot th rsults wlth dlrnt volus or ,7?-%`%-.
E-8,2 ,7?-% ' B*
E-8,2 ,7?-%`%- ' BN>*
E-8,2 ,9$-:23&% ' )BB*
E8/ 4:72 ! ' B* ! P' ;:&2<* ! (' >D5 1
1) Calculate the y location according to
amplitude and sine of the angle.
E-8,2 " ' ,9$-:23&%Q#:74,7?-%5*
2) Draw a circle at the (x,y) location. %--:$#%4!C"(<%:?<2=>CDXCDX5*
3) ncrement the angle according to angular
velocity.
,7?-% (' ,7?-%`%-*
@
cnleVel = o.o cnleVel = o.z cnleVel = o.(
1h Notur o Cod [v005j
J23
Notlc how, olthough w`r not prclsly computlng th prlod o th wov, th hlghr th
ongulor vloclty, th shortr th prlod. |t`s olso worth notlng thot os th prlod bcoms
shortr, lt bcoms mor ond mor dllcult to mok out th wov ltsl os th dlstonc
btwn th lndlvlduol polnts lncross. On optlon w hov ls to us I%?:7[<,$%45 ond
%7&[<,$%45 to connct th polnts wlth o lln.
IJ&7:5# =KBL O'&'/0 4&N# -)&41 &8 & 0*1'/1(*(8 5/1#
You moy hov notlcd thot th obov xompl ls stotlc. 1h wov nvr chongs, nvr
undulots. 1hls oddltlonol stp ls o blt trlcky. Your lrst lnstlnct mlght b to soy. Hy, no
problm, w`ll just lt thto b o globol vorlobl ond lt lt lncrmnt rom on cycl through
&/,;45 to onothr."
Whll lt`s o nlc thought, lt dosn`t work. | you look ot th wov, th rlghthond dg dosn`t
motch th lthond, whr lt nds ln on cycl o &/,;45 con`t b whr lt storts ln th nxt.
E-8,2 ,7?-% ' B*
E-8,2 ,7?-%`%- ' BN>*
E-8,2 ,9$-:23&% ' )BB*
#:F%4DBBC>BB5*
I,0.?/837&4>JJ5*
#9882<45*
#2/8.%4B5*
#2/8.%+%:?<24>5*
78b:--45*
I%?:7[<,$%45*
E8/ 4:72 ! ' B* ! P' ;:&2<* ! (' J5 1
Here's an example of using the map()
function instead.
E-8,2 " ' 9,$4#:74,7?-%5C6)C)CBC<%:?<25*
With beginShape() and endShape(), you
call vertex() to set all the vertices of your
shape.
A%/2%!4!C"5*
,7?-% (',7?-%`%-*
@
%7&[<,$%45*
Choptr 3. Osclllotlon
J24
|nstod, whot w nd to do ls hov o vorlobl ddlcotd ntlrly to trocklng whot volu o
ongl th wov should stort wlth. 1hls ongl [whlch w`ll coll #2,/2V7?-%j lncrmnts wlth lts
own ongulor vloclty.
IJ&7:5# =KCL !"# M&N#
E-8,2 #2,/2V7?-% ' B*
E-8,2 ,7?-%`%- ' BN)*
A8:& #%23$45 1
#:F%4DBBC>BB5*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
n order to move the wave, we start at a
different theta value each frame. startAngle
+= 0.02;
E-8,2 ,7?-% ' #2,/2V7?-%*
E8/ 4:72 ! ' B* ! P' ;:&2<* ! (' >D5 1
E-8,2 " ' 9,$4#:74,7?-%5C6)C)CBC<%:?<25*
#2/8.%4B5*
E:--4BCJB5*
%--:$#%4!C"CDXCDX5*
,7?-% (' ,7?-%`%-*
@
@
1h Notur o Cod [v005j
J25
1ry uslng th Prlln nols unctlon lnstod o sln or cosln wlth th obov xompl.
MO(.2&-( ="W MO(.2&-( ="W
Lncopsulot th obov xompls lnto o +,A% closs ond crot o sktch thot dlsploys
two wovs [wlth dlrnt omplltuds/prlodsj os ln th scrnshot blow. Mov
byond ploln clrcls ond llns ond try vlsuollzlng th wov ln o mor crotlv woy.
MO(.2&-( ="#T MO(.2&-( ="#T
Mor complx wovs con b producd by th volus o multlpl wovs togthr.
Crot o sktch thot lmplmnts thls, os ln th scrnshot blow.
MO(.2&-( ="## MO(.2&-( ="##
Choptr 3. Osclllotlon
J26
="W @.&<*;*E('./ 4;9 S*.2(-D @,( 5(;9:%:E ="W @.&<*;*E('./ 4;9 S*.2(-D @,( 5(;9:%:E
Lo you mlss Nwton`s lows o motlon? | know | sur do. Wll, lucky or you, lt`s tlm to brlng lt
oll bock hom. Atr oll, lt`s bn nlc lornlng obout trlongls ond tongnts ond wovs, but
rolly, th cor o thls book ls obout slmulotlng th physlcs o movlng bodls. Lt`s tok o look
ot how trlgonomtry con hlp us wlth thls pursult.
A pndulum ls o bob suspndd rom o plvot. Obvlously o rol-world pndulum would llv ln o
3L spoc, but w`r golng to look ot o slmplr scnorlo, o pndulum ln o 2L spoco
Procsslng wlndow [s |lgur 3.J0j.
|n Choptr 2, w lornd how o orc [such os th orc o grovlty ln |lgur 3.JJj couss on
objct to occlrot. ^ " g F h or h " ^ ; g. |n thls cos, howvr, th pndulum bob
dosn`t slmply oll to th ground bcous lt ls ottochd by on orm to th plvot polnt. And so, ln
ordr to dtrmln lts ongu|ot occlrotlon, w not only nd to look ot th orc o grovlty,
but olso th orc ot th ongl o th pndulum`s orm [rlotlv to o pndulum ot rst wlth on
ongl o 0j.
|n th obov cos, slnc th pndulum`s orm ls o lxd lngth, th only vorlobl ln th
scnorlo ls th ongl. W or golng to slmulot th pndulum`s motlon through th us o
ongulor vloclty ond occlrotlon. 1h ongulor occlrotlon wlll b colculotd uslng Nwton`s
scond low wlth o llttl trlgonomtry twlst.
Lt`s zoom ln on th rlght trlongl rom th pndulum dlogrom.
Iiure .:o Iiure .::
1h Notur o Cod [v005j
J27
W con s thot th orc o th pndulum
[b
$
j should polnt prpndlculor to th orm
o th pndulum ln th dlrctlon thot th
pndulum ls swlnglng. Atr oll, l thr
wr no orm, th bob would just oll
strolght down. |t`s th tnslon orc o th
orm thot kps th bob occlrotlng
towords th pndulum`s rst stot. 5lnc
th orc o grovlty [b
$
j polnts downword,
by moklng o rlght trlongl out o ths two
vctors, w`v occompllshd somthlng
qult mognllcnt. W`v mod th orc o
grovlty th hypotnus o o rlght trlongl
ond sporotd th vctor lnto two
componnts, on o whlch rprsnts th
orc o th pndulum. 5lnc sln quols
opposlt ovr hypotnus, w hov.
.2#$*i+ " ^
0
; ^
G
1hror.
^
0
" ^
G
F .2#$*i+
Lst w orgt, w`v bn dolng oll o thls wlth o slngl qustlon ln mlnd. Whot ls th
ongulor occlrotlon o th pndulum? Onc w hov th ongulor occlrotlon, w`ll b obl
to opply our ruls o motlon to lnd th nw ongl or th pndulum.
&#G4'&) L$'8:2/3 " &#G4'&) L$'8:2/3 K &#G4'&) &::$'$)&/28#
&#G'$ " &#G'$ K &#G4'&) L$'8:2/3
1h good nws ls thot wlth Nwton`s scond low, w know thot thr ls o rlotlonshlp
btwn orc ond occlrotlon, nomly | M ' A, or A | / M. 5o l th orc o th
pndulum ls quol to th orc o grovlty tlms sln o th ongl, thn.
0$#14'45 &#G4'&) &::$'$)&/28# " &::$'$)&/28# 14$ /8 G)&L2/3 F .2#$ *i+
1hls ls o good tlm to rmlnd ourslvs thot w`r Procsslng progrommrs ond not
physlclsts. Ys, w know thot th occlrotlon du to grovlty on orth ls 9.8 mtrs pr
scond squord. But thls numbr lsn`t rlvont to us. Whot w hov hr ls just on orbltrory
constont [w`ll coll lt ?/,A:2"j, on thot w con us to scol th occlrotlon to somthlng
thot ls rlght.
&#G4'&) &::$'$)&/28# " G)&L2/3 F .2#$*i+
Amozlng. Atr oll thot, th ormulo ls so slmpl. You mlght b wondrlng, why bothr golng
through th drlvotlon ot oll? | mon, lornlng ls grot ond oll, but w could hov oslly just
Iiure .:z
Choptr 3. Osclllotlon
J28
sold, "Hy, th ongulor occlrotlon o o pndulum ls som constont tlms th sln o th
ongl." 1hls ls just onothr momnt ln whlch w rmlnd ourslvs thot th purpos o th
book ls not to lorn how pndulums swlng or grovlty works. 1h polnt ls to thlnk crotlvly
obout how thlngs con mov obout th scrn ln o computotlonolly bosd grophlcs systm. 1h
pndulum ls just o cos study. | you con undrstond th opprooch to progrommlng o
pndulum, thn howvr you choos to dslgn your onscrn world, you con opply th som
tchnlqus.
O cours, w`r not lnlshd yt. W moy b hoppy wlth our slmpl, lgont ormulo, but w
stlll hov to opply lt ln cod. 1hls ls most dlnltly o good tlm to proctlc our objct-orlntd
progrommlng skllls ond crot o ]%7&3-39 closs. Lt`s thlnk obout oll th proprtls w`v
ncountrd ln our pndulum dlscusslon thot th closs wlll nd.
- orm lngth
- ongl
- ongulor vloclty
- ongulor occlrotlon
W`ll olso nd to wrlt o unctlon 3$&,2%45 to updot th pndulum`s ongl occordlng to our
ormulo.
0-,## ]%7&3-39 1
Length of arm E-8,2 /*
Pendulum arm angle E-8,2 ,7?-%*
Angular velocity E-8,2 ,`%-80:2"*
Angular acceleration E-8,2 ,V00%-%/,2:87*
A8:& 3$&,2%45 1
Arbitrary constant E-8,2 ?/,A:2" ' BND*
Calculate acceleration according to our
formula.
,V00%-%/,2:87 ' 6) Q ?/,A:2" Q #:74,7?-%5*
ncrement velocity. ,`%-80:2" (' ,V00%-%/,2:87*
ncrement angle. ,7?-% (' ,`%-80:2"*
@
1h Notur o Cod [v005j
J29
.os wll os o unctlon &:#$-,"45 to drow
th pndulum ln th wlndow. 1hls bgs th
qustlon. m, whr do w drow th
pndulum?" W know th ongl ond th
orm lngth, but how do w know th x,y
[Cortslon!j coordlnots or both th
pndulum`s plvot polnt [lt`s coll lt orlglnj
ond bob locotlon [lt`s coll lt locotlonj? 1hls
moy b gttlng o llttl tlrlng, but th
onswr, yt ogoln, ls trlgonomtry.
1h orlgln ls just somthlng w mok up,
os ls th orm lngth. Lt`s soy.
W`v got th currnt ongl stord ln our vorlobl ,7?-%. 5o rlotlv to th orlgln, th
pndulum`s locotlon ls o polor coordlnot. (t,ong|eI. And w nd lt to b Cortslon. Lucklly
or us, w just spnt som tlm [sctlon 3.5j drlvlng th ormulo or convrtlng rom polor
to Cortslon. And so.
5lnc th locotlon ls rlotlv to whrvr th orlgln hoppns to b, w con just odd orlgln to
th locotlon ]`%028/.
And oll thot rmolns ls th llttl mottr o drowlng o lln ond lllps [you should b mor
crotlv, o coursj.
Bor w put vrythlng togthr, thr`s on lost llttl dtoll | nglctd to mntlon. Lt`s
thlnk obout th pndulum orm or o momnt. |s lt o mtol rod? A strlng? A rubbr bond? How
ls lt ottochd to th plvot polnt? How long ls lt? Whot ls lts moss? |s lt o wlndy doy? 1hr
or o lot o qustlons thot w could contlnu to osk thot would oct th slmulotlon. W`r
Iiure .:
]`%028/ 8/:?:7 ' 7%; ]`%028/4)BBC)B5*
E-8,2 / ' )>J*
]`%028/ -80,2:87 ' 7%; ]`%028/4/Q#:74,7?-%5C/Q08#4,7?-%55*
-80,2:87N,&&48/:?:75*
#2/8.%4B5*
E:--4)OJ5*
-:7%48/:?:7N!C8/:?:7N"C-80,2:87N!C-80,2:87N"5*
%--:$#%4-80,2:87N!C-80,2:87N"C)GC)G5*
Choptr 3. Osclllotlon
J30
llvlng, o cours, ln o ontosy world, on whr th pndulum`s orm ls som ldollzd rod thot
nvr bnds ond th moss o th bob ls concntrotd ln o slngl, lnlnltslmolly smoll polnt.
Nvrthlss, vn though w don`t wont to worry ourslvs wlth oll o th qustlons, w
should odd on mor vorlobl to our colculotlon o ongulor occlrotlon. 1o kp thlngs
slmpl, ln our drlvotlon o th pndulum`s occlrotlon, w ossumd thot th lngth o th
pndulum`s orm ls J. |n oct, th lngth o th pndulum`s orm octs th occlrotlon grotly.
th longr th orm, th slowr th occlrotlon. 1o slmulot o pndulum mor occurotly, w
dlvld by thot lngth, ln thls cos /. |or o mor lnvolvd xplonotlon, vlslt 1h 5lmpl
Pndulum wbslt [http.//colculuslob.dltocollg.du/OLL/7-A-2/7-A-2-h.htmlj.
|lnolly, o rol-world pndulum ls golng to xprlnc som omount o rlctlon [ot th plvot
polntj ond olr rslstonc. Wlth our cod os ls, th pndulum would swlng orvr, so to mok lt
mor rollstlc w con us o domplng" trlck. | soy tt|c| bcous rothr thon modl th
rslstonc orcs wlth som dgr o occurocy [os w dld ln Choptr 2j, w con ochlv o
slmllor rsult by slmply rduclng th ongulor vloclty durlng och cycl. 1h ollowlng cod
rducs th vloclty by J [or multlplls lt by 99j durlng och rom o onlmotlon.
Puttlng vrythlng togthr, w hov th ollowlng xompl [wlth th pndulum bglnnlng ot o
45-dgr onglj.
IJ&7:5# =K;DL O4/16/16 :#1-(5(7
,V00%-%/,2:87 ' 46) Q Z Q #:74,7?-%55 = /*
,`%-80:2" Q' BNpp*
]%7&3-39 $*
A8:& #%23$45 1
#:F%4>BBC>BB5*
1h Notur o Cod [v005j
J3J
We make a new Pendulum object with an
origin location and arm length.
$ ' 7%; ]%7&3-3947%; ]`%028/4;:&2<=>C)B5C)>J5*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
$N?845*
@
0-,## ]%7&3-39 1
Many, many variables to keep track of the
Pendulum's various properties
]`%028/ -80,2:87* == l80,2:87 8E I8I
]`%028/ 8/:?:7* == l80,2:87 8E ,/9 8/:?:7
E-8,2 /* == l%7?2< 8E ,/9
E-8,2 ,7?-%* == ]%7&3-39 ,/9 ,7?-%
E-8,2 ,`%-80:2"* == V7?-% A%-80:2"
E-8,2 ,V00%-%/,2:87* == V7?-% ,00%-%/,2:87
E-8,2 &,9$:7?* == V/I:2/,/" &,9$:7? ,98372
]%7&3-394]`%028/ 8/:?:7aC E-8,2 /a5 1
8/:?:7 ' 8/:?:7aN?%245*
-80,2:87 ' 7%; ]`%028/45*
/ ' /a*
,7?-% ' ]c=D*
,`%-80:2" ' BNB*
,V00%-%/,2:87 ' BNB*
An arbitrary damping so that the Pendulum
slows over time
&,9$:7? ' BNppJ*
@
A8:& ?845 1
3$&,2%45*
&:#$-,"45*
@
A8:& 3$&,2%45 1
E-8,2 ?/,A:2" ' BND*
,V00%-%/,2:87 ' 46) Q ?/,A:2" = /5 Q #:74,7?-%5*
Formula we worked out for angular
acceleration
Standard angular motion algorithm ,`%-80:2" (' ,V00%-%/,2:87*
,7?-% (' ,`%-80:2"*
Apply some damping. ,`%-80:2" Q' &,9$:7?*
@
A8:& &:#$-,"45 1
Where is the bob relative to the origin?
Polar to Cartesian coordinates will tell us!
-80,2:87N#%24/Q#:74,7?-%5C/Q08#4,7?-%5CB5*
-80,2:87N,&&48/:?:75*
#2/8.%4B5*
Choptr 3. Osclllotlon
J32
(Note thot the vets|on ot the exomp|e posted on the webs|te hos odd|t|ono| code to o||ow the
uset to gtob the pendu|um ond sw|ng |t w|th the mouse.I
The arm -:7%48/:?:7N!C8/:?:7N"C-80,2:87N!C-80,2:87N"5*
E:--4)OJ5*
The bob %--:$#%4-80,2:87N!C-80,2:87N"C)GC)G5*
@
@
5trlng togthr o srls o pndulums so thot th ndpolnt o on ls th orlgln polnt o
onothr. Not thot dolng thls moy produc lntrlgulng rsults but wlll b wlldly lnoccurot
physlcolly. 5lmulotlng on octuol doubl pndulum lnvolvs sophlstlcotd quotlons,
whlch you con rod obout hr. http.//sclncworld.wolrom.com/physlcs/
LoublPndulum.html [http.//sclncworld.wolrom.com/physlcs/LoublPndulum.htmlj.
MO(.2&-( ="#0 MO(.2&-( ="#0
slng trlgonomtry, whot ls th
mognltud o th normol orc ln th
lllustrotlon on th rlght [th orc
prpndlculor to th lnclln on whlch th
sld rstsj? Not thot, os lndlcotd, th
normol" orc ls o componnt o th
orc o grovlty.
MO(.2&-( ="#= MO(.2&-( ="#=
Crot on xompl thot slmulots o box slldlng down th lnclln wlth rlctlon. Not thot
th mognltud o th rlctlon orc ls quol to th normol orc.
MO(.2&-( ="#> MO(.2&-( ="#>
1h Notur o Cod [v005j
J33
="#T UQ.&;< S*.2(- ="#T UQ.&;< S*.2(-
|n sctlon 3.6 [s pog JJ5j, w lookd ot modllng slmpl hormonlc motlon by mopplng
th sln wov to o plxl rong. Lxrcls 3.6 [s pog JJ9j oskd you to us thls tchnlqu
to crot o slmulotlon o o bob honglng rom o sprlng. Whll uslng th #:745 unctlon ls o
qulck-ond-dlrty, on-lln-o-cod woy o gttlng somthlng up ond runnlng, lt won`t do l
whot w rolly wont ls to hov o bob honglng rom o sprlng ln o two-dlmnslonol spoc thot
rsponds to othr orcs ln th nvlronmnt [wlnd, grovlty, tc.j 1o occompllsh o slmulotlon
llk thls [on thot ls ldntlcol to th pndulum xompl, only now th orm ls o sprlngy
connctlonj, w nd to modl th orcs o o sprlng uslng ]`%028/.
1h orc o o sprlng ls colculotd occordlng to Hook`s low, nomd or Robrt Hook, o
Brltlsh physlclst who dvlopd th ormulo ln J660. Hook orlglnolly stotd th low ln Lotln.
"Ut tens|o, s|c v|s," or As th xtnslon, so th orc." Lt`s thlnk o lt thls woy.
1h orc o th sprlng ls dlrctly proportlonol to th xtnslon o th
sprlng.
Iiure .:(
Choptr 3. Osclllotlon
J34
|n othr words, l you pull on th bob o lot,
th orc wlll b strong, l you pull on th
bob o llttl, th orc wlll b wok.
Mothmotlcolly, th low ls stotd os ollows.
^
.0)2#G
" T ( F I
- . ls constont ond lts volu wlll
ultlmotly scol th orc. |s th
sprlng hlghly lostlc or qult rlgld?
- ! rrs to th dlsplocmnt o th
sprlng, l.. th dlrnc btwn
th currnt lngth ond th rst
lngth. 1h rst lngth ls dlnd
os th lngth o th sprlng ln o
stot o qulllbrlum.
Now rmmbr, orc ls o vctor, so w
nd to colculot both mognltud ond
dlrctlon. Lt`s look ot on mor dlogrom o
th sprlng ond lobl oll th glvns w mlght hov ln o Procsslng sktch.
Lt`s stobllsh th ollowlng thr vorlobls os shown ln |lgur 3.J6.
Iiure .:: x = current lenth - rest lenth
Iiure .:
]`%028/ ,70<8/*
]`%028/ -80,2:87*
E-8,2 /%#2l%7?2<*
1h Notur o Cod [v005j
J35
|lrst, lt`s us Hook`s low to colculot th mognltud o th orc. W nd to know . ond
!. . ls osy, lt`s just o constont, so lt`s mok somthlng up.
! ls prhops o blt mor dllcult. W nd to know th dlrnc btwn th currnt
lngth ond th rst lngth." 1h rst lngth ls dlnd os th vorlobl /%#2l%7?2<. Whot`s
th currnt lngth? 1h dlstonc btwn th onchor ond th bob. And how con w
colculot thot dlstonc? How obout th mognltud o o vctor thot polnts rom th onchor to
th bob? [Not thot thls ls xoctly th som procss w mployd whn colculotlng dlstonc
ln Lxompl 2.9. grovltotlonol ottroctlon.j
Now thot w`v sortd out th lmnts ncssory or th mognltud o th orc [-J ' . ' !j,
w nd to lgur out th dlrctlon, o unlt vctor polntlng ln th dlrctlon o th orc. 1h
good nws ls thot w olrody hov thls vctor. Rlght? Just o momnt ogo w thought to
ourslvs. How w con colculot thot dlstonc? How obout th mognltud o o vctor thot
polnts rom th onchor to th bob?" Wll, thot ls th dlrctlon o th orc!
E-8,2 . ' BN)*
A vector pointing from anchor to bob gives
us the current length of the spring.
]`%028/ &:/ ' ]`%028/N#3I4I8IC,70<8/5*
E-8,2 03//%72l%7?2< ' &:/N9,?45*
E-8,2 ! ' /%#2l%7?2< 6 03//%72l%7?2<*
Iiure .:;
Choptr 3. Osclllotlon
J36
|n |lgur 3.J7, w con s thot l w strtch th sprlng byond lts rst lngth, thr should b
o orc pulllng lt bock towords th onchor. And l lt shrlnks blow lts rst lngth, th orc
should push lt owoy rom th onchor. 1hls rvrsol o dlrctlon ls occountd or ln th ormulo
wlth th -J. And so oll w nd to do ls normollz th ]`%028/ w usd or th dlstonc
colculotlon! Lt`s tok o look ot th cod ond rnom thot ]`%028/ vorlobl os orc."
Now thot w hov th olgorlthm workd out or computlng th sprlng orc vctor, th
qustlon rmolns. whot objct-orlntd progrommlng structur should w us? 1hls, ogoln, ls
on o thos sltuotlons ln whlch thr ls no corrct" onswr. 1hr or svrol posslbllltls,
whlch on w choos dpnds on th progrom`s gools ond on`s own prsonol codlng styl.
5tlll, slnc w`v bn worklng oll olong wlth o d8A%/ closs, lt`s kp golng wlth thls som
romwork. Lt`s thlnk o our d8A%/ closs os th sprlng`s bob." 1h bob nds -80,2:87,
A%-80:2", ond ,00%-%/,2:87 vctors to mov obout th scrn. Prctw`v got thot
olrody! And prhops th bob xprlncs o grovlty orc vlo th ,$$-"b8/0%45 unctlon. Just
on mor stpw nd to opply th sprlng orc.
Magnitude of spring force according to
Hooke's law
E-8,2 . ' BN)*
]`%028/ E8/0% ' ]`%028/N#3I4I8IC,70<8/5*
E-8,2 03//%72l%7?2< ' &:/N9,?45*
E-8,2 ! ' /%#2l%7?2< 6 03//%72l%7?2<*
Direction of spring force (unit vector) E8/0%N78/9,-:F%45*
Putting it together: direction and magnitude! E8/0%N93-246) Q . Q !5*
W8I I8I*
A8:& #%23$45 1
I8I ' 7%; W8I45*
@
A8:& &/,;45 1
Our Chapter 2 "make-up-a-gravity force ]`%028/ ?/,A:2" ' 7%; ]`%028/4BC)5*
I8IN,$$-"b8/0%4?/,A:2"5*
We need to also calculate and apply a
spring force!
MN$:/8) .0)2#G^8):$ " dddddddddddddddjjjj
686-&00'3^8):$*.0)2#G+,
Our standard update() and display()
functions
I8IN3$&,2%45*
I8IN&:#$-,"45*
@
1h Notur o Cod [v005j
J37
On optlon would b to wrlt out oll o th sprlng orc cod ln th moln &/,;45 loop. But
thlnklng ohod to whn you mlght hov multlpl bobs ond multlpl sprlng connctlons, lt
moks o good dol o sns to wrlt on oddltlonol closs, o [$/:7? closs. As shown ln |lgur
3.J8, th W8I closs kps trock o th movmnts o th bob, th [$/:7? closs kps trock
o th sprlng`s onchor ond lts rst lngth ond colculots th sprlng orc on th bob.
1hls ollows us to wrlt o lovly moln progrom os ollows.
Iiure .:8
W8I I8I*
Adding a Spring object k0)2#G .0)2#G,
A8:& #%23$45 1
I8I ' 7%; W8I45*
#$/:7? ' 7%; [$/:7?45*
@
A8:& &/,;45 1
]`%028/ ?/,A:2" ' 7%; ]`%028/4BC)5*
I8IN,$$-"b8/0%4?/,A:2"5*
This new function in the Spring class will
take care of computing the force of the
spring on the bob.
.0)2#G-:8##$:/*686+,
I8IN3$&,2%45*
I8IN&:#$-,"45*
#$/:7?N&:#$-,"45*
@
Choptr 3. Osclllotlon
J38
You moy notlc hr thot thls ls qult slmllor to whot w dld ln Lxompl 2.6 [s pog 94j wlth
on ottroctor. 1hr, w sold somthlng llk.
1h onologous sltuotlon hr wlth o sprlng would b.
Nvrthlss, ln thls xompl oll w sold wos.
Whot glvs? Why don`t w nd to coll ,$$-"b8/0%45 on th bob? 1h onswr ls, o cours,
thot w do nd to coll ,$$-"b8/0%45 on th bob. Only lnstod o dolng lt ln &/,;45, w`r
just dmonstrotlng thot o prctly rosonobl [ond somtlms prroblj oltrnotlv ls to osk
th 0877%0245 unctlon to lntrnolly hondl colllng ,$$-"b8/0%45 on th bob.
Why do lt on woy wlth th V22/,028/ closs ond onothr woy wlth th [$/:7? closs? Whn w
wr lrst lornlng obout orcs, lt wos o blt clorr to show oll th orcs blng opplld ln th
moln &/,;45 loop, ond hopully thls hlpd you lorn obout orc occumulotlon. Now thot
w`r mor comortobl wlth thot, prhops lt`s slmplr to mbd som o th dtolls lnsld th
objcts thmslvs.
Lt`s tok o look ot th rst o th lmnts ln th [$/:7? closs.
]`%028/ E8/0% ' ,22/,028/N,22/,02498A%/5*
98A%/N,$$-"b8/0%4E8/0%5*
]`%028/ E8/0% ' #$/:7?N0877%024I8I5*
I8IN,$$-"b8/0%4E8/0%5*
#$/:7?N0877%024I8I5*
A8:& 0877%024W8I I5 1
]`%028/ E8/0% ' #89% E,70" 0,-03-,2:87#
The function connect() takes care of calling
applyForce() and therefore doesn't have to
return a vector to the calling area.
IN,$$-"b8/0%4E8/0%5*
@
1h Notur o Cod [v005j
J39
IJ&7:5# =K;;L 2 O:)/16 0*11#0'/*1
1h ull cod or thls xompl ls lncludd on th book wbslt, ond th Wb vrslon olso
lncorporots two oddltlonol oturs. [Jj th W8I closs lncluds unctlons or mous
0-,## [$/:7? 1
We need to keep track of the spring's
anchor location.
]`%028/ ,70<8/*
Rest length and spring constant variables E-8,2 -%7*
E-8,2 . ' BN)*
The constructor initializes the anchor point
and rest length.
[$/:7?4E-8,2 !C E-8,2 "C :72 -5 1
,70<8/ ' 7%; ]`%028/4!C"5*
-%7 ' -*
@
Calculate spring forceour implementation
of Hooke's Law.
A8:& 0877%024W8I I5 1
Get a vector pointing from anchor to Bob
location.
MN$:/8) 98):$ "
MN$:/8)-.46*6-'8:&/28#J&#:H8)+,
9'8&/ 1 " 98):$-5&G*+,
Calculate the displacement between
distance and rest length.
9'8&/ ./)$/:H " 1 T '$#,
Direction and magnitude together! 98):$-#8)5&'2]$*+,
98):$-54'/*TD F ( F ./)$/:H+,
Call applyForce() right here! IN,$$-"b8/0%4E8/0%5*
@
Draw the anchor. A8:& &:#$-,"45 1
E:--4)BB5*
/%02d8&%4MhknhY5*
/%024,70<8/N!C,70<8/N"C)BC)B5*
@
Draw the spring connection between Bob
location and anchor.
A8:& &:#$-,"l:7%4W8I I5 1
#2/8.%4>JJ5*
-:7%4IN-80,2:87N!CIN-80,2:87N"C,70<8/N!C,70<8/N"5*
@
@
Choptr 3. Osclllotlon
J40
lntroctlvlty so thot th bob con b droggd oround th wlndow, ond [2j th [$/:7? objct
lncluds o unctlon to constroln th connctlon`s lngth btwn o mlnlmum ond o moxlmum.
Bor runnlng to s th xompl onlln, tok o look ot thls constroln unctlon ond s
l you con lll ln th blonks.
A8:& 087#2/,:7l%7?2<4W8I IC E-8,2 9:7-%7C E-8,2 9,!-%75 1
Vector pointing from Bob to Anchor ]`%028/ &:/ ' ]`%028/N#3I4aaaaaaCaaaaaa5*
E-8,2 & ' &:/N9,?45*
s it too short? :E 4& P 9:7-%75 1
&:/N78/9,-:F%45*
&:/N93-24aaaaaaaa5*
Keep location within constraint. IN-80,2:87 ' ]`%028/N,&&4aaaaaaCaaaaaa5*
INA%-80:2"N93-24B5*
s it too long? @ %-#% :E 4aaaaaaaaaaaa5 1
&:/N78/9,-:F%45*
&:/N93-24aaaaaaaaa5*
Keep location within constraint. IN-80,2:87 ' ]`%028/N,&&4aaaaaaCaaaaaa5*
INA%-80:2"N93-24B5*
@
@
MO(.2&-( ="#? MO(.2&-( ="#?
Crot o systm o multlpl bobs ond sprlng connctlons. How would you hov o bob
connctd to o bob wlth no lxd onchor?
MO(.2&-( ="#K MO(.2&-( ="#K
1h Notur o Cod [v005j
J4J
@,( M2*-/-'(E 5.*G(2' @,( M2*-/-'(E 5.*G(2'
U'(Q = MO(.2&-(D
@43( *;( *+ /*:. 2.(4':.(- 4;9 &;2*.Q*.4'( *-2&%%4'&*; &;'* &'- E*'&*;" a*: 24;
:-( ',( U#0:--,28/ 2%4-- +.*E MO4EQ%( ="L 4- 4 E*9(%" @,( U#0:--,28/ *)G(2'`
,*8(I(.` *-2&%%4'(- 4.*:;9 4 -&;<%( Q*&;' ^',( E&99%( *+ ',( 8&;9*8_" @./
*-2&%%4'&;< 4.*:;9 4 E*I&;< Q*&;'" C; *',(. 8*.9-` 9(-&<; 4 2.(4':.( ',4' E*I(-
4.*:;9 ',( -2.((; 422*.9&;< '* %*24'&*;` I(%*2&'/` 4;9 422(%(.4'&*;" b:' ',4'
2.(4':.( &-;H' G:-' 4 -'4'&2 -,4Q(` &'H- 4; *-2&%%4'&;< )*9/" P*;-&9(. '/&;< ',( -Q((9
*+ *-2&%%4'&*; '* ',( -Q((9 *+ E*'&*;" @,&;3 *+ 4 ):''(.+%/H- +%4QQ&;< 8&;<- *. ',(
%(<- *+ 4; &;-(2'" P4; /*: E43( &' 4QQ(4. ',4' ',( 2.(4':.(H- &;'(.;4% E(2,4;&2-
^*-2&%%4'&*;_ 9.&I( &'- %*2*E*'&*;7 S*. 4 -4EQ%(` 2,(23 *:' ',(
A!''.42'&*;!..4/6&',F-2&%%4'&*;B (O4EQ%( 8&', ',( 2*9( 9*8;%*49"
Choptr 3. Osclllotlon
J42
,"&:'#) >K 9&)'/05# ,"&:'#) >K 9&)'/05#
OU8'#78 OU8'#78
Thct is uise. Were I to intole loic, houeter, loic clecrl dictctes thct
the needs oj the mcn outueih the needs oj the jeu.
! 630.G
|n J982, Wllllom 1. Rvs, o rsorchr ot Lucosllm Ltd., wos worklng on th llm 5tot 7te| ll.
7he toth ot khon. Much o th movl rvolvs oround th Gnsls Lvlc, o torpdo thot
whn shot ot o borrn, lllss plont hos th oblllty to rorgonlz mottr ond crot o
hobltobl world or colonlzotlon. Lurlng th squnc, o woll o lr rlppls ovr th plont
whll lt ls blng trroormd." 1h trm A(1&/%'$ )@)&$- A(1&/%'$ )@)&$-, on lncrdlbly common ond usul
tchnlqu ln computr grophlcs, wos colnd ln th crotlon o thls portlculor ct.
A pcrticle sstem is c collection oj mcn mcn minute pcrticles thct toether represent c
juzz object. Dter c period oj time, pcrticles cre enercted into c sstem, mote cnd chcne
jrom uithin the sstem, cnd die jrom the sstem.
-Willicm Reetes, "Pcrticle Sstems-A Technique jor Modelin c Clcss oj Iuzz
Dbjects," >@H (2$,'$.4-0,' 0, I2$3E-.' z:z (April :p8), pz.
5lnc th orly J980s, portlcl systms hov bn usd ln countlss vldo goms, onlmotlons,
dlgltol ort plcs, ond lnstollotlons to modl vorlous lrrgulor typs o noturol phnomno,
such os lr, smok, wotrolls, og, gross, bubbls, ond so on.
1hls choptr wlll b ddlcotd to looklng ot lmplmntotlon strotgls or codlng o portlcl
systm. How do w orgonlz our cod? Whr do w stor lnormotlon rlotd to lndlvlduol
portlcls vrsus lnormotlon rlotd to th systm os o whol? 1h xompls w`ll look ot wlll
1h Notur o Cod [v005j
J43
ocus on monoglng th doto ossoclotd wlth o portlcl systm. 1hy`ll us slmpl shops or
th portlcls ond opply only th most boslc bhovlors [such os grovltyj. Howvr, by uslng
thls romwork ond bulldlng ln mor lntrstlng woys to rndr th portlcls ond comput
bhovlors, you con ochlv o vorlty o cts.
>"# 6,/ 6( X((9 54.'&2%( U/-'(E- >"# 6,/ 6( X((9 54.'&2%( U/-'(E-
W`v dlnd o portlcl systm to b o collctlon o lndpndnt objcts, otn
rprsntd by o slmpl shop or dot. Why dos thls mottr? Crtolnly, th prospct o
modllng som o th phnomno w llstd [xploslons!j ls ottroctlv ond potntlolly usul.
But rolly, thr`s on vn bttr roson or us to concrn ourslvs wlth portlcl systms. |
w wont to gt onywhr ln thls notur o cod ll, w`r golng to nd to work wlth
systms o mony thlngs. W`r golng to wont to look ot bolls bounclng, blrds locklng,
cosystms volvlng, oll sorts o thlngs ln plurol.
Just obout vry choptr otr thls on ls golng to nd to dol wlth o llst o objcts. Ys,
w`v don thls wlth on orroy ln som o our lrst vctor ond orcs xompls. But w nd
to go whr no orroy hos gon bor.
|lrst, w`r golng to wont to dol wlth lxlbl quontltls o lmnts. 5omtlms w`ll hov
zro thlngs, somtlms on thlng, somtlms tn thlngs, ond somtlms tn thousond
thlngs. 5cond, w`r golng to wont to tok o mor sophlstlcotd objct-orlntd opprooch.
|nstod o slmply wrltlng o closs to dscrlb o slngl portlcl, w`r olso golng to wont to
wrlt o closs thot dscrlbs th collctlon o portlclsth portlcl systm ltsl. 1h gool
hr ls to b obl to wrlt o moln progrom thot looks llk th ollowlng.
No slngl portlcl ls vr rrncd ln th obov cod, yt th rsult wlll b ull o portlcls
lylng oll ovr th scrn. Gttlng usd to wrltlng Procsslng sktchs wlth multlpl closss,
ond closss thot kp llsts o lnstoncs o othr closss, wlll prov vry usul os w gt to
mor odvoncd choptrs ln thls book.
|lnolly, worklng wlth portlcl systms ls olso o good xcus or us to tockl two othr
odvoncd objct-orlntd progrommlng tchnlqus. lnhrltonc ond polymorphlsm. Wlth th
Ah, isn't this main program so simple and
lovely?
],/2:0-%["#2%9 $#*
A8:& #%23$45 1
#:F%4>BBC>BB5*
$# ' 7%; ],/2:0-%["#2%945*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
$#N/3745*
@
Choptr 4. Portlcl 5ystms
J44
xompls w`v sn up untll now, w`v olwoys hod on orroy o o slngl typ o objct, llk
"movrs" or osclllotors." Wlth lnhrltonc [ond polymorphlsmj, w`ll lorn o convnlnt woy to
stor o slngl llst thot contolns objcts o dlrnt typs. 1hls woy, o portlcl systm nd not
only b o systm o o slngl typ o portlcl.
1hough lt moy sm obvlous to you, |`d olso llk to polnt out thot thr or typlcol
lmplmntotlons o portlcl systms, ond thot`s whr w wlll bgln ln thls choptr. Howvr,
th oct thot th portlcls ln thls choptr look or bhov o crtoln woy should not llmlt your
lmoglnotlon. Just bcous portlcl systms tnd to look sporkly, ly orword, ond oll wlth
grovlty dosn`t mon thot thos or th choroctrlstlcs yours should hov.
1h ocus hr ls rolly just how to kp trock o o systm o mony lmnts. Whot thos
lmnts do ond how thos lmnts look ls up to you.
>"0 ! U&;<%( 54.'&2%( >"0 ! U&;<%( 54.'&2%(
Bor w con gt rolllng on th systm ltsl, w hov to wrlt th closs thot wlll dscrlb o
slngl portlcl. 1h good nws. w`v don thls olrody. Our d8A%/ closs rom Choptr 2
srvs os th prct tmplot. |or us, o portlcl ls on lndpndnt body thot movs obout th
scrn. |t hos -80,2:87, A%-80:2", ond ,00%-%/,2:87, o constructor to lnltlollz thos
vorlobls, ond unctlons to &:#$-,"45 ltsl ond 3$&,2%45 lts locotlon.
1hls ls obout os slmpl os o portlcl con gt. |rom hr, w could tok our portlcl ln svrol
dlrctlons. W could odd on ,$$-"b8/0%45 unctlon to oct th portlcl`s bhovlor [w`ll do
0-,## ],/2:0-% 1
A "Particle object is just another name for
our "Mover. t has location, velocity, and
acceleration.
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
],/2:0-%4]`%028/ -5 1
-80,2:87 ' -N?%245*
,00%-%/,2:87 ' 7%; ]`%028/45*
A%-80:2" ' 7%; ]`%028/45*
@
A8:& 3$&,2%45 1
A%-80:2"N,&&4,00%-%/,2:875*
-80,2:87N,&&4A%-80:2"5*
@
A8:& &:#$-,"45 1
#2/8.%4B5*
E:--4)OJ5*
%--:$#%4-80,2:87N!C-80,2:87N"CXCX5*
@
@
1h Notur o Cod [v005j
J45
prclsly thls ln o utur xomplj. W could odd vorlobls to dscrlb color ond shop, or
rrnc o ]c9,?% to drow th portlcl. |or now, howvr, lt`s ocus on oddlng just on
oddltlonol dtoll. '/;$)A(. '/;$)A(..
1yplcol portlcl systms lnvolv somthlng colld on $-/&&$1 $-/&&$1. 1h mlttr ls th sourc o
th portlcls ond controls th lnltlol sttlngs or th portlcls, locotlon, vloclty, tc. An
mlttr mlght mlt o slngl burst o portlcls, or o contlnuous strom o portlcls, or both.
1h polnt ls thot or o typlcol lmplmntotlon such os thls, o portlcl ls born ot th mlttr
but dos not llv orvr. | lt wr to llv orvr, our Procsslng sktch would vntuolly
grlnd to o holt os th numbr o portlcls lncross to on unwlldy numbr ovr tlm. As
nw portlcls or born, w nd old portlcls to dl. 1hls crots th llluslon o on lnlnlt
strom o portlcls, ond th prormonc o our progrom dos not sur. 1hr or mony
dlrnt woys to dcld whn o portlcl dls. |or xompl, lt could com lnto contoct wlth
onothr objct, or lt could slmply lov th scrn. |or our lrst ],/2:0-% closs, howvr,
w`r slmply golng to odd o -:E%#$,7 vorlobl. 1h tlmr wlll stort ot 255 ond count down
to 0, whn th portlcl wlll b consldrd dod." And so w xpond th ],/2:0-% closs os
ollows.
1h roson w chos to stort th llspon ot 255 ond count down to 0 ls or convnlnc.
Wlth thos volus, w con osslgn -:E%#$,7 to oct os th olpho tronsporncy or th lllps
os wll. Whn th portlcl ls dod" lt wlll olso hov odd owoy onscrn.
0-,## ],/2:0-% 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
A new variable to keep track of how long
the particle has been "alive
9'8&/ '29$.0&#,
],/2:0-%4]`%028/ -5 1
-80,2:87 ' -N?%245*
,00%-%/,2:87 ' 7%; ]`%028/45*
A%-80:2" ' 7%; ]`%028/45*
We start at 255 and count down for
convenience
'29$.0&# " >==,
@
A8:& 3$&,2%45 1
A%-80:2"N,&&4,00%-%/,2:875*
-80,2:87N,&&4A%-80:2"5*
Lifespan decreases '29$.0&# T" >-?,
@
A8:& &:#$-,"45 1
Since our life ranges from 255 to 0 we can
use it for alpha
./)8($*?J'29$.0&#+,
92''*D@=J'29$.0&#+,
%--:$#%4-80,2:87N!C-80,2:87N"CXCX5*
@
@
Choptr 4. Portlcl 5ystms
J46
Wlth th oddltlon o th -:E%#$,7 vorlobl, w`ll olso nd on oddltlonol unctlono unctlon
thot con b qurld [or o tru or ols onswrj os to whthr th portlcl ls ollv or dod. 1hls
wlll com ln hondy whn w or wrltlng th ],/2:0-%["#2%9 closs, whos tosk wlll b to
monog th llst o portlcls thmslvs. Wrltlng thls unctlon ls prtty osy, w just nd to
chck ond s l th volu o -:E%#$,7 ls lss thon 0. | lt ls w /%23/7 2/3%, l not w
/%23/7 E,-#%.
Bor w gt to th nxt stp o moklng mony portlcls, lt`s worth toklng o momnt to mok
sur our portlcl works corrctly ond crot o sktch wlth on slngl ],/2:0-% objct. Hr ls
th ull cod blow, wlth two smoll oddltlons. W odd o convnlnc unctlon colld /3745
thot slmply colls both 3$&,2%45 ond &:#$-,"45 or us. |n oddltlon, w glv th portlcl o
rondom lnltlol vloclty os wll os o downword occlrotlon [to slmulot grovltyj.
IJ&7:5# >K;L 2 8/165# :&)'/05#
I88-%,7 :#\%,&45 1
s the particle still alive? :E 4-:E%#$,7 P BNB5 1
/%23/7 2/3%*
@ %-#% 1
/%23/7 E,-#%*
@
@
],/2:0-% $*
A8:& #%23$45 1
#:F%4>BBC>BB5*
$ ' 7%; ],/2:0-%47%; ]`%028/4;:&2<=>C)B55*
#9882<45*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
1h Notur o Cod [v005j
J47
Operating the single Particle $N/3745*
:E 4$N:#\%,&455 1
$/:72-74T],/2:0-% &%,&ST5*
@
@
0-,## ],/2:0-% 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
E-8,2 -:E%#$,7*
],/2:0-%4]`%028/ -5 1
,00%-%/,2:87 ' 7%; ]`%028/4BCBNBJ5*
A%-80:2" ' 7%; ]`%028/4/,7&8946)C)5C/,7&8946>CB55*
-80,2:87 ' -N?%245*
-:E%#$,7 ' >JJNB*
@
For demonstration purposes we assign the
Particle an initial velocity and constant
acceleration.
Sometimes it's convenient to have a "run
function that calls all the other functions we
need.
A8:& /3745 1
3$&,2%45*
&:#$-,"45*
@
A8:& 3$&,2%45 1
A%-80:2"N,&&4,00%-%/,2:875*
-80,2:87N,&&4A%-80:2"5*
-:E%#$,7 6' >NB*
@
A8:& &:#$-,"45 1
#2/8.%4BC-:E%#$,75*
E:--4BC-:E%#$,75*
%--:$#%4-80,2:87N!C-80,2:87N"CXCX5*
@
s the Particle alive or dead? I88-%,7 :#\%,&45 1
:E 4-:E%#$,7 P BNB5 1
/%23/7 2/3%*
@ %-#% 1
/%23/7 E,-#%*
@
@
@
Choptr 4. Portlcl 5ystms
J48
Now thot w hov o closs to dscrlb o slngl portlcl, w`r rody or th nxt blg stp. How
do w kp trock o mony portlcls, whn w con`t nsur xoctly how mony portlcls w
mlght hov ot ony glvn tlm?
Rwrlt th xompl so thot th portlcl con rspond to orc vctors vlo on
,$$-"b8/0%45 unctlon.
MO(.2&-( >"# MO(.2&-( >"#
Add ongulor vloclty [rototlonj to th portlcl. Crot your own non-clrcl portlcl
dslgn.
MO(.2&-( >"0 MO(.2&-( >"0
>"= @,( !..4/V&-' >"= @,( !..4/V&-'
|n truth, w could us o slmpl orroy to monog our ],/2:0-% objcts. 5om portlcl systms
mlght hov o lxd numbr o portlcls, ond orroys or mognllcntly lclnt ln thos
lnstoncs. Procsslng olso ors %!$,7&45, 0872/,0245, #3I#%245, #$-:0%45, ond othr
mthods or rslzlng orroys. Howvr, or ths xompls, w`r golng to tok o mor
sophlstlcotd opprooch ond us th Jovo closs V//,"l:#2, ound ln th jovo.utll pockog
ArroyLlst Locumntotlon [http.//downlood.orocl.com/jovos/6/docs/opl/jovo/utll/
ArroyLlst.htmlj.
slng on V//,"l:#2 ollows th som ldo os uslng o stondord orroy, but wlth dlrnt syntox.
1h ollowlng two cod xompls [whlch ossum th xlstnc o o gnrlc ],/2:0-% clossj
produc th som rsult. lrst wlth on orroy, ond scond wlth on V//,"l:#2.
1h stondord orroy woy.
:72 282,- ' )B*
],/2:0-%KL $,//," ' 7%; ],/2:0-%K282,-L*
A8:& #%23$45 1
This is what we're used to, accessing
elements on the array via an index and
brackets[ ].
E8/ 4:72 : ' B* : P $,//,"N-%7?2<* :((5 1
$,//,"K:L ' 7%; ],/2:0-%45*
@
1h Notur o Cod [v005j
J49
1h nw V//,"l:#2 woy.
1hls lost E8/ loop looks prtty slmllor to our cod thot loopd through o rgulor orroy by
occsslng och lndx. W lnltlollz o vorlobl colld : to 0 ond count up by J, occsslng
och lmnt o th V//,"l:#2 untll w gt to th nd. Howvr, thls ls o nlc momnt to
mntlon th nhoncd E8/ loop" ovollobl ln Jovo [ond Procsslngj whlch ls o blt mor
concls. 1h nhoncd loop works wlth both V//,"l:#2s ond rgulor orroys ond looks llk
thls.
Lt`s tronslot thot. 5oy or och" lnstod o or" ond soy ln" lnstod o .". Now you hov.
|or och Portlcl p ln portlcls, run thot Portlcl p!"
| know. You connot contoln your xcltmnt. | con`t. | know lt`s not ncssory, but | just hov
to typ thot ogoln.
@
A8:& &/,;45 1
E8/ 4:72 : ' B* : P $,//,"N-%7?2<* :((5 1
],/2:0-% $ ' $,//,"K:L*
$N/3745*
@
@
:72 282,- ' )B*
V//,"l:#2P],/2:0-%^ $-:#2 ' 7%; V//,"l:#2P],/2:0-%^45*
A8:& #%23$45 1
E8/ 4:72 : ' B* : P 282,-* :((5 1
Have you ever seen this syntax before?
This is a new feature in Java 1.6 (called
"generics") that Processing now supports.
t allows us to specify in advance what type
of object we intend to put in the ArrayList.
An object is added to an ArrayList with
add().
$-:#2N,&&47%; ],/2:0-%455*
@
@
A8:& &/,;45 1
The size of the ArrayList is returned by
size().
E8/ 4:72 : ' B* : P $-:#2N#:F%45* :((5 1
An object is accessed from the ArrayList
with get(). Because we are using generics,
we do not need to specify a type when we
pull objects out of the ArrayList.
],/2:0-% $ ' $-:#2N?%24:5*
$N/3745*
@
@
V//,"l:#2P],/2:0-%^ $-:#2 ' 7%; V//,"l:#2P],/2:0-%^45*
E8/ 4],/2:0-% $q $,/2:0-%#5 1
$N/3745*
@
Choptr 4. Portlcl 5ystms
J50
5lmpl, lgont, concls, lovly. 1ok o momnt. Broth. | hov som bod nws. Ys, w
lov thot nhoncd loop ond w wlll gt to us lt. But not rlght now. Our portlcl systm
xompls wlll rqulr o otur thot moks uslng thot loop lmposslbl. Lt`s contlnu.
1h cod w`v wrlttn obov dosn`t tok odvontog o th V//,"l:#2`s rslzoblllty, ond lt
uss o lxd slz o J0. W nd to dslgn on xompl thot lts wlth our portlcl systm
scnorlo, whr w mlt o contlnuous strom o ],/2:0-% objcts, oddlng on nw portlcl
wlth och cycl through &/,;45. W`ll sklp rhoshlng th ],/2:0-% closs cod hr, os lt
dosn`t nd to chong.
Run th obov cod or o w mlnuts ond you`ll stort to s th rom rot slow down urthr
ond urthr untll th progrom grlnds to o holt [my tsts ylldd horrllc prormonc otr
ltn mlnutsj. 1h lssu o cours ls thot w or crotlng mor ond mor portlcls wlthout
rmovlng ony.
|ortunotly, th V//,"l:#2 closs hos o convnlnt /%98A%45 unctlon thot ollows us to dlt
o Portlcl [by rrnclng lts lndxj. 1hls ls why w connot us th nw nhoncd E8/ loop w
just lornd, th nhoncd loop provlds no mons or dltlng lmnts whll ltrotlng.
Hr, w wont to coll /%98A%45 whn th Portlcl`s :#\%,&45 unctlon rturns tru.
This enhanced loop also works for regular
arrays!
E8/ 4],/2:0-% $ q $,/2:0-%#5 1
$N/3745*
@
V//,"l:#2P],/2:0-%^ $,/2:0-%#*
A8:& #%23$45 1
#:F%4>BBC>BB5*
$,/2:0-%# ' 7%; V//,"l:#2P],/2:0-%^45*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
$,/2:0-%#N,&&47%; ],/2:0-%47%; ]`%028/4;:&2<=>CJB555*
E8/ 4:72 : ' B* : P $,/2:0-%#N#:F%45* :((5 1
],/2:0-% $ ' $,/2:0-%#N?%24:5*
$N/3745*
@
@
A new Particle object is added to the
ArrayList every cycle through draw().
E8/ 4:72 : ' B* : P $,/2:0-%#N#:F%45* :((5 1
],/2:0-% $ ' $,/2:0-%#N?%24:5*
$N/3745*
f the Particle is "dead, we can go ahead
and delete it from the list.
:E 4$N:#\%,&455 1
$,/2:0-%#N/%98A%4:5*
@
@
1h Notur o Cod [v005j
J5J
Although th obov cod wlll run just ln [ond th progrom wlll nvr grlnd to o holtj, w
hov opnd up o mdlum-slzd con o worms. Whnvr w monlpulot th contnts o o
llst whll ltrotlng through thot vry llst, w con gt ourslvs lnto troubl. 1ok, or
xompl, th ollowlng cod.
1hls ls o somwhot xtrm xompl [wlth lowd loglcj, but lt provs th polnt. |n th
obov cos, or och portlcl ln th llst, w odd o nw portlcl to th llst [monlpulotlng th
#:F%45 o th V//,"l:#2j. 1hls wlll rsult ln on lnlnlt loop, os : con nvr lncrmnt post
th slz o th V//,"l:#2.
Whll rmovlng lmnts rom th V//,"l:#2 durlng o loop dosn`t cous th progrom to
crosh [os lt dos wlth oddlngj, th problm ls olmost mor lnsldlous ln thot lt lovs no
vldnc. 1o dlscovr th problm w must lrst stobllsh on lmportont oct. Whn on objct
ls rmovd rom th V//,"l:#2, oll lmnts or shltd on spot to th lt. Not th
dlogrom blow whr portlcl C [lndx 2j ls rmovd. Portlcls A ond B kp th som
lndx, whll portlcls L ond L shlt rom 3 ond 4 to 2 ond 3, rspctlvly.
Lt`s prtnd w or : looplng through th V//,"l:#2.
!H$# 2 " ? a fH$:( 0&)/2:'$ h a Z8 #8/ 1$'$/$
!H$# 2 " D a fH$:( 0&)/2:'$ l a Z8 #8/ 1$'$/$
!H$# 2 " > a fH$:( 0&)/2:'$ f a Z$'$/$m
k'21$ 0&)/2:'$. Z &#1 n 6&:( 9)85 .'8/. E &#1 < /8 > &#1 E
!H$# 2 " E a fH$:( 0&)/2:'$ n a Z8 #8/ 1$'$/$
Notlc th problm? W nvr chckd portlcl L! Whn C wos dltd rom slot #2, L
movd lnto slot #2, but l hos olrody movd on to slot # 3. 1hls ls not o dlsostr, slnc
E8/ 4:72 : ' B* : P $,/2:0-%#N#:F%45* :((5 1
],/2:0-% $ ' $,/2:0-%#N?%24:5*
$N/3745*
$,/2:0-%#N,&&47%; ],/2:0-%47%; ]`%028/4;:&2<=>CJB555*
@ Adding a new Particle to the list while
iterating?
Iiure (.:
Choptr 4. Portlcl 5ystms
J52
portlcl L wlll gt chckd th nxt tlm oround. 5tlll, th xpctotlon ls thot w or wrltlng
cod to ltrot through vry slngl lmnt o th V//,"l:#2. 5klpplng on lmnt ls
unoccptobl.
1hr or two solutlons to thls problm. 1h lrst solutlon ls to slmply ltrot through th
V//,"l:#2 bockwords. | you or slldlng lmnts rom rlght to lt os lmnts or rmovd,
lt`s lmposslbl to sklp on lmnt by occldnt. Hr`s how th cod would look.
1hls ls o prctly ln solutlon ln nlnty-nln coss out o o hundrd. But somtlms, th
ordr ln whlch th lmnts or drown could b lmportont ond you moy not wont to ltrot
bockwords. Jovo provlds o spclol clossc2%/,28/thot toks cor o oll o th dtolls o
ltrotlon or you. You gt to soy.
Hey, ld |||e to |tetote thtough th|s V//,"l:#2. Cou|d you cont|nue to g|ve me the next
e|ement |n the ||st one ot o t|me unt|| we get to the end? And |t l temove e|ements ot move
them otound |n the ||st wh||e wete |tetot|ng, w||| you mo|e sute l dont |oo| ot ony e|ements
tw|ce ot s||p ony by occ|dent?
An V//,"l:#2 con produc on c2%/,28/ objct or you.
Onc you`v got th ltrotor, th <,#k%!245 unctlon wlll tll us whthr thr ls o ],/2:0-%
or us to run ond th 7%!245 unctlon wlll grob thot ],/2:0-% objct ltsl.
And l you coll th /%98A%45 unctlon on th c2%/,28/ objct durlng th loop, lt wlll dlt th
currnt ],/2:0-% objct [ond not sklp ohod post th nxt on, os w sow wlth countlng
orword through th V//,"l:#2j.
Looping through the list backwards 98) *2#/ 2 " 0&)/2:'$.-.2]$*+TD, 2 Q" ?, 2TT+ O
],/2:0-% $ ' 4],/2:0-%5 $,/2:0-%#N?%24:5*
$N/3745*
:E 4$N:#\%,&455 1
$,/2:0-%#N/%98A%4:5*
@
@
Note that with the terator object, we can
also use the new <ClassName> generics
syntax and specify the type that the terator
will reference.
c2%/,28/P],/2:0-%^ :2 ' $,/2:0-%#N:2%/,28/45*
An terator object doing the iterating for you ;<:-% 4:2N<,#k%!2455 1
],/2:0-% $ ' :2N7%!245*
$N/3745*
:E 4$N:#\%,&455 1
1h Notur o Cod [v005j
J53
Puttlng lt oll togthr, w hov.
IJ&7:5# >K<L 2))&U_/8' *+ :&)'/05#8 4/'" F'#)&'*)
An terator object doing the deleting for you :2N/%98A%45*
@
@
V//,"l:#2P],/2:0-%^ $,/2:0-%#*
A8:& #%23$45 1
#:F%4>BBC>BB5*
$,/2:0-%# ' 7%; V//,"l:#2P],/2:0-%^45*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
$,/2:0-%#N,&&47%; ],/2:0-%47%; ]`%028/4;:&2<=>CJB555*
c2%/,28/P],/2:0-%^ :2 ' $,/2:0-%#N:2%/,28/45*
Using an terator object instead of
counting with int i
;<:-% 4:2N<,#k%!2455 1
],/2:0-% $ ' :2N7%!245*
$N/3745*
:E 4$N:#\%,&455 1
:2N/%98A%45*
@
@
@
Choptr 4. Portlcl 5ystms
J54
>"> @,( 54.'&2%( U/-'(E P%4-- >"> @,( 54.'&2%( U/-'(E P%4--
OK. Now w`v don two thlngs. W`v wrlttn o closs to dscrlb on lndlvlduol ],/2:0-%
objct. W`v conqurd th V//,"l:#2 ond usd lt to monog o llst o mony ],/2:0-%
objcts [wlth th oblllty to odd ond dlt ot wlllj.
W could stop hr. Howvr, on oddltlonol stp w con ond should tok ls to wrlt o closs
to dscrlb th llst o ],/2:0-% objcts ltslth ],/2:0-%["#2%9 closs. 1hls wlll ollow us to
rmov th bulky loglc o looplng through oll portlcls rom th moln tob, os wll os opn up
th posslblllty o hovlng mor thon on portlcl systm.
| you rcoll th gool w st ot th bglnnlng o thls choptr, w wontd our moln tob to look
llk thls.
Lt`s tok th cod rom Lxompl 4.2 ond rvlw o blt o objct-orlntd progrommlng,
looklng ot how och plc rom th moln tob con lt lnto th ],/2:0-%["#2%9 closs.
Just one wee ParticleSystem! ],/2:0-%["#2%9 $#*
A8:& #%23$45 1
#:F%4>BBC>BB5*
$# ' 7%; ],/2:0-%["#2%945*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
$#N/3745*
@
1h Notur o Cod [v005j
J55
2))&U_/8' /1 '"# 7&/1 '&E 2))&U_/8' /1 '"# 7&/1 '&E 2))&U_/8' /1 '"# 9&)'/05#OU8'#7 05&88 2))&U_/8' /1 '"# 9&)'/05#OU8'#7 05&88
h))&3o2./SM&)/2:'$Q 0&)/2:'$.,
A8:& #%23$45 1
#:F%4>BBC>BB5*
0&)/2:'$. " #$! h))&3o2./SM&)/2:'$Q*+,
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
0&)/2:'$.-&11*#$! M&)/2:'$*++,
e/$)&/8)SM&)/2:'$Q 2/ "
0&)/2:'$.-2/$)&/8)*+,
!H2'$ *2/-H&.p$I/*++ O
M&)/2:'$ 0 " 2/-#$I/*+,
0-)4#*+,
29 *0-2.Z$&1*++ O
2/-)$58L$*+,
P
P
@
0-,## ],/2:0-%["#2%9 1
h))&3o2./SM&)/2:'$Q 0&)/2:'$.,
],/2:0-%["#2%945 1
0&)/2:'$. " #$! h))&3o2./SM&)/2:'$Q*+,
@
A8:& ,&&],/2:0-%45 1
0&)/2:'$.-&11*#$! M&)/2:'$*++,
@
A8:& /3745 1
e/$)&/8)SM&)/2:'$Q 2/ "
0&)/2:'$.-2/$)&/8)*+,
!H2'$ *2/-H&.p$I/*++ O
M&)/2:'$ 0 " 2/-#$I/*+,
0-)4#*+,
29 *0-2.Z$&1*++ O
2/-)$58L$*+,
P
P
@
@
W could olso odd som nw oturs to th portlcl systm ltsl. |or xompl, lt mlght b
usul or th ],/2:0-%["#2%9 closs to kp trock o on orlgln polnt whr portlcls or
mod. 1hls lts ln wlth th ldo o o portlcl systm blng on mlttr," o ploc whr
portlcls or born ond snt out lnto th world. 1h orlgln polnt should b lnltlollzd ln th
constructor.
IJ&7:5# >K=L O/7:5# O/165# 9&)'/05# OU8'#7
0-,## ],/2:0-%["#2%9 1
V//,"l:#2 $,/2:0-%#*
This particular ParticleSystem
implementation includes an origin point
where each Particle begins.
MN$:/8) 8)2G2#,
],/2:0-%["#2%94]`%028/ -80,2:875 1
8/:?:7 ' -80,2:87N?%245*
$,/2:0-%# ' 7%; V//,"l:#245*
@
A8:& ,&&],/2:0-%45 1
The origin is passed to each Particle when
it is added.
0&)/2:'$.-&11*#$! M&)/2:'$*8)2G2#++,
@
Choptr 4. Portlcl 5ystms
J56
Mok th orlgln polnt mov dynomlcolly. Hov th portlcls mlt rom th mous
locotlon or us th concpts o vloclty ond occlrotlon to mok th systm mov
outonomously.
MO(.2&-( >"= MO(.2&-( >"=
Bulldlng o Choptr 3`s Astrolds" xompl, us o portlcl systm to mlt portlcls
rom th shlp`s thrustrs" whnvr o thrust orc ls opplld. 1h portlcls` lnltlol
vloclty should b rlotd to th shlp`s currnt dlrctlon.
MO(.2&-( >"> MO(.2&-( >">
>"? ! U/-'(E *+ U/-'(E- >"? ! U/-'(E *+ U/-'(E-
Lt`s rvlw or o momnt whr w or. W know how to tolk obout on lndlvlduol ],/2:0-%
objct. W olso know how to tolk obout o systm o ],/2:0-% objcts, ond thls w coll o
portlcl systm." And w`v dlnd o portlcl systm os o collctlon o lndpndnt objcts.
But lsn`t o portlcl systm ltsl on objct? | thot`s th cos [whlch lt lsj, thr`s no roson why
w couldn`t olso hov o collctlon o mony portlcl systms, l.. o systm o systms.
1hls lln o thlnklng could o cours tok us vn urthr, ond you mlght lock yoursl ln o
bosmnt or doys sktchlng out o dlogrom o o systm o systms o systms o systms o
systms o systms. O systms. Atr oll, thls ls how th world works. An orgon ls o systm o
clls, o humon body ls o systm o orgons, o nlghborhood ls o systm o humon bodls, o clty
ls o systm o nlghborhoods, ond so on ond so orth. Whll thls ls on lntrstlng rood to
trovl down, lt`s o blt byond whr w nd to b rlght now. |t ls, howvr, qult usul to
know how to wrlt o Procsslng sktch thot kps trock o mony portlcl systms, och o
whlch kp trock o mony portlcls. Lt`s tok th ollowlng scnorlo.
You stort wlth o blonk scrn.
1h Notur o Cod [v005j
J57
You cllck th mous ond gnrot o portlcl systm ot th mous`s locotlon.
Loch tlm you cllck th mous, o nw portlcl systm ls crotd ot th mous`s locotlon.
|n Lxompl 4.3 [s pog J56j, w stord o slngl rrnc to o portlcl systm objct ln
th vorlobl $#.
|or thls nw xompl, whot w wont to do lnstod ls crot on V//,"l:#2 to kp trock o
multlpl lnstoncs o portlcl systms. Whn th progrom storts, l.. ln #%23$45, th
V//,"l:#2 ls mpty.
],/2:0-%["#2%9 $#*
A8:& #%23$45 1
#:F%4>BBC>BB5*
$# ' 7%; ],/2:0-%["#2%94)C7%; ]`%028/4;:&2<=>CJB55*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
$#N/3745*
$#N,&&],/2:0-%45*
@
Choptr 4. Portlcl 5ystms
J58
IJ&7:5# >K>L OU8'#7 *+ 8U8'#78
Whnvr th mous ls prssd, o nw ],/2:0-%["#2%9 objct ls crotd ond plocd lnto th
V//,"l:#2.
And ln &/,;45, lnstod o rrnclng o slngl ],/2:0-%["#2%9 objct, w now look through
oll th systms ln th V//,"l:#2 ond coll /3745 on och o thm.
This time, the type of thing we are putting in
the ArrayList is a ParticleSystem itself!
V//,"l:#2P],/2:0-%["#2%9^ #"#2%9#*
A8:& #%23$45 1
#:F%4GBBC>BB5*
#"#2%9# ' 7%; V//,"l:#2P],/2:0-%["#2%9^45*
@
A8:& 983#%]/%##%&45 1
#"#2%9#N,&&47%; ],/2:0-%["#2%947%; ]`%028/4983#%eC983#%f555*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
Since we aren't deleting elements, we can
use our enhanced loop!
E8/ 4],/2:0-%["#2%9 $#q #"#2%9#5 1
$#N/3745*
$#N,&&],/2:0-%45*
@
@
Rwrlt Lxompl 4.4 so thot och portlcl systm dosn`t llv orvr. Whn o portlcl
systm ls mpty [l.. hos no portlcls lt ln lts V//,"l:#2j, rmov lt rom th
V//,"l:#2 #"#2%9#.
MO(.2&-( >"? MO(.2&-( >"?
Crot o slmulotlon o on objct shottrlng lnto mony plcs. How con you turn on
lorg shop lnto mony smoll portlcls? Whot l thr or svrol lorg shops on th
scrn ond thy shottr whn you cllck on thm?
MO(.2&-( >"K MO(.2&-( >"K
1h Notur o Cod [v005j
J59
>"K C;,(.&'4;2( 4;9 5*%/E*.Q,&-ED !; C;'.*9:2'&*; >"K C;,(.&'4;2( 4;9 5*%/E*.Q,&-ED !; C;'.*9:2'&*;
You moy hov ncountrd th trms |nhet|tonce ond po|ymotph|sm ln your progrommlng
ll bor thls book. Atr oll, thy or two o th thr undomntol prlnclpls bhlnd th
thory o objct-orlntd progrommlng [th othr blng encopsu|ot|onj. | you`v rod othr
Procsslng or Jovo progrommlng books, choncs or lt`s bn covrd. My bglnnr txt,
leotn|ng ltocess|ng, hos clos to on ntlr choptr [#22j ddlcotd to ths two toplcs.
5tlll, prhops you`v only lornd obout lt ln th obstroct sns ond nvr hod o roson to
rolly us lnhrltonc ond polymorphlsm. | thls ls tru, you`v com to th rlght ploc.
Wlthout ths two toplcs, your oblllty to progrom o vorlty o portlcls ond portlcl systms
ls xtrmly llmltd. [|n th nxt choptr, w`ll olso s how undrstondlng ths toplcs wlll
hlp us to us physlcs llbrorls.j
|mogln th ollowlng. |t`s o 5oturdoy mornlng, you`v just gon out or o lovly jog, hod o
dllclous bowl o crol, ond or slttlng qultly ot your computr wlth o cup o worm
chomomll to. |t`s your old rlnd 5o ond 5o`s blrthdoy ond you`v dcldd you`d llk to
mok o grtlng cord ln Procsslng. How obout som conttl or o blrthdoy? Purpl
conttl, plnk conttl, stor-shopd conttl, squor conttl, ost conttl, luttry conttl,
tc. All o ths plcs o conttl wlth dlrnt opporoncs ond dlrnt bhovlors
xplod onto th scrn ot onc.
Whot w`v got hr ls clorly o portlcl systmo collctlon o lndlvlduol plcs o conttl
[l.. portlclsj. W mlght b obl to clvrly dslgn our ],/2:0-% closs to hov vorlobls
thot stor lts color, shop, bhovlor, tc. And prhops w lnltlollz th volus o ths
vorlobls rondomly. But whot l your portlcls or drostlcolly dlrnt? 1hls could bcom
vry mssy, hovlng oll sorts o cod or dlrnt woys o blng o portlcl ln th som closs.
Wll, you mlght consldr dolng th ollowlng.
1hls ls o nlc solutlon. w hov thr dlrnt closss to dscrlb th dlrnt klnds o
plcs o conttl thot could b port o our portlcl systm. 1h ],/2:0-%["#2%9
constructor could thn hov som cod to plck rondomly rom th thr closss whn llllng
th V//,"l:#2. Not thot thls proboblllstlc mthod ls th som on w mployd ln our
rondom wolk xompls ln th |ntroductlon [s pog 2j.
0-,## r,$$"M87E%22: 1
@
0-,## b37M87E%22: 1
@
0-,## +,0."M87E%22: 1
@
Choptr 4. Portlcl 5ystms
J60
OK, w now nd to pous or o momnt. W`v don nothlng wrong. All w wontd to do
wos wlsh our rlnd o hoppy blrthdoy ond njoy wrltlng som cod. But whll th rosonlng
bhlnd th obov opprooch ls qult sound, w`v opnd up two mojor problms.
Problm #J. Arn`t w golng to b copylng/postlng o lot o cod btwn th
dlrnt conttl" closss?
Ys. Lvn though our klnds o portlcls or dlrnt nough to mrlt our broklng thm out
lnto sporot closss, thr ls stlll o ton o cod thot thy wlll llkly shor. 1hy`ll oll hov
]`%028/s to kp trock o locotlon, vloclty, ond occlrotlon, on 3$&,2%45 unctlon thot
lmplmnts our motlon olgorlthm, tc.
1hls ls whr /.+$1/&(.%$ /.+$1/&(.%$ coms ln. |nhrltonc ollows us to wrlt o closs thot |nhet|ts
vorlobls ond unctlons rom onothr closs, oll th whll lmplmntlng lts own custom
oturs.
Problm #2. How wlll th ArroyLlst know whlch objcts or whlch typ?
1hls ls o prtty srlous problm. Rmmbr, w wr uslng gnrlcs to tll th V//,"l:#2
whot typ o objcts w`r golng to put lnsld lt. Ar w suddnly golng to nd thr
dlrnt V//,"l:#2s?
1hls sms owully lnconvnlnt, glvn thot w rolly just wont on llst to kp trock o oll th
stu ln th portlcl systm. 1hot con b mod posslbl wlth polymorphlsm. Polymorphlsm wlll
ollow us to consldr objcts o dlrnt typs os th som typ ond stor thm ln o slngl
V//,"l:#2.
0-,## ],/2:0-%["#2%9 1
],/2:0-%["#2%94:72 7395 1
$,/2:0-%# ' 7%; V//,"l:#245*
E8/ 4:72 : ' B* : P 739* :((5 1
E-8,2 / ' /,7&894)5*
Randomly picking a "kind" of particle
:E 4/ P BNHH5 1 $,/2:0-%#N,&&47%; r,$$"M87E%22:455* @
%-#% :E 4/ P BNGO5 1 $,/2:0-%#N,&&47%; b37M87E%22:455* @
%-#% 1 $,/2:0-%#N,&&47%; +,0."M87E%22:455* @
@
@
V//,"l:#2Pr,$$"M87E%22:^ ,) ' 7%; V//,"l:#2Pr,$$"M87E%22:^45*
V//,"l:#2Pb37M87E%22:^ ,> ' 7%; V//,"l:#2Pb37M87E%22:^45*
V//,"l:#2P+,0."M87E%22:^ ,H ' 7%; V//,"l:#2P+,0."M87E%22:^45*
1h Notur o Cod [v005j
J6J
Now thot w undrstond th problm, lt`s look ot ths two concpts ln o blt mor dtoll
ond thn crot o portlcl systm xompl thot lmplmnts both lnhrltonc ond
polymorphlsm.
>"L C;,(.&'4;2( b4-&2- >"L C;,(.&'4;2( b4-&2-
Lt`s tok o dlrnt xompl, th world o onlmols. dogs, cots, monkys, pondos, wombots,
ond so nttls. W`ll stort by progrommlng o \8? closs. A \8? objct wlll hov on og
vorlobl [on lntgrj, os wll os %,245, #-%%$45, ond I,/.45 unctlons.
Now, lt`s mov on to cots.
0-,## \8? 1
:72 ,?%*
Dogs and cats have the same variables
(age) and functions (eat, sleep).
\8?45 1
,?% ' B*
@
A8:& %,245 1
$/:72-74Tf39ST5*
@
A8:& #-%%$45 1
$/:72-74TsFFFFFT5*
@
A unique function for barking. A8:& I,/.45 1
$/:72-74T+UUbST5*
@
@
Choptr 4. Portlcl 5ystms
J62
As w rwrlt th som cod or lsh, horss, koolos, ond lmurs, thls procss wlll bcom
rothr tdlous. |nstod, lt`s dvlop o gnrlc V7:9,- closs thot con dscrlb ony typ o
onlmol. All onlmols ot ond slp, otr oll. W could thn soy.
- A dog ls on onlmol ond hos oll th proprtls o onlmols ond con do oll th thlngs
onlmols do. Also, o dog con bork.
- A cot ls on onlmol ond hos oll th proprtls o onlmols ond con do oll th thlngs
onlmols do. Also, o cot con mow.
|nhrltonc moks thls oll posslbl. Wlth lnhrltonc, closss con lnhrlt proprtls [vorloblsj
ond unctlonollty [mthodsj rom othr closss. A \8? closs ls o chlld [):"%'()) ):"%'())j o on V7:9,-
closs. Chlldrn wlll outomotlcolly lnhrlt oll vorlobls ond unctlons rom th pornt
[):A$1%'()) ):A$1%'())j, but con olso lnclud unctlons ond vorlobls not ound ln th pornt. Llk o
phylogntlc "tr o ll," lnhrltonc ollows o tr structur. Logs lnhrlt rom conlns,
whlch lnhrlt rom mommols, whlch lnhrlt rom onlmols, tc.
0-,## M,2 1
:72 ,?%*
M,245 1
,?% ' B*
@
A8:& %,245 1
$/:72-74Tf39ST5*
@
A8:& #-%%$45 1
$/:72-74TsFFFFFT5*
@
A8:& 9%8;45 1
$/:72-74TdhU+ST5*
@
@
Iiure (.z
1h Notur o Cod [v005j
J63
Hr ls how th syntox works wlth lnhrltonc.
1hls brlngs up two nw trms.
- $K&$.8) $K&$.8) 1hls kyword ls usd to lndlcot o pornt or th closs blng dlnd.
Not thot closss con only xtnd one closs. Howvr, closss con xtnd closss
thot xtnd othr closss, l.. \8? %!2%7&# V7:9,-, n%//:%/ %!2%7&# \8?.
Lvrythlng ls lnhrltd oll th woy down th lln.
- ):A$1OP ):A$1OP 1hls colls th constructor ln th pornt closs. |n othr words, whotvr
you do ln th pornt constructor, do so ln th chlld constructor os wll. Othr cod
con b wrlttn lnto th constructor ln oddltlon to #3$%/45. #3$%/45 con olso
The Animal class is the parent (or super)
class.
0-,## V7:9,- 1
Dog and Cat inherit the variable age. :72 ,?%*
V7:9,-45 1
,?% ' B*
@
Dog and Cat inherit the functions eat() and
sleep().
A8:& %,245 1
$/:72-74Tf39ST5*
@
A8:& #-%%$45 1
$/:72-74TsFFFFFT5*
@
@
The Dog class is the child (or sub) class,
indicated by the code "extends Animal".
:'&.. Z8G $I/$#1. h#25&' O
\8?45 1
super() executes code found in the parent
class.
.40$)*+,
@
We define bark() in the child class, since it
isn't part of the parent class.
A8:& I,/.45 1
$/:72-74T+UUbST5*
@
@
0-,## M,2 %!2%7&# V7:9,- 1
M,245 1
#3$%/45*
@
A8:& 9%8;45 1
$/:72-74TdhU+ST5*
@
@
Choptr 4. Portlcl 5ystms
J64
rclv orgumnts l thr ls o pornt constructor dlnd wlth motchlng orgumnts.
A subcloss con b xpondd to lnclud oddltlonol unctlons ond proprtls byond whot ls
contolnd ln th suprcloss. |or xompl, lt`s ossum thot o \8? objct hos o holrcolor
vorlobl ln oddltlon to og, whlch ls st rondomly ln th constructor. 1h closs would now look
llk thls.
Not how th pornt constructor ls colld vlo #3$%/45, whlch sts th og to 0, but th
holrcolor ls st lnsld th \8? constructor ltsl. | o \8? objct ots dlrntly thon o gnrlc
V7:9,- objct, pornt unctlons con b ovett|dden by rwrltlng th unctlon lnsld th
subcloss.
But whot l o dog ots th som woy os o gnrlc onlmol, just wlth som xtro unctlonollty? A
subcloss con both run th cod rom o pornt closs ond lncorporot custom cod.
0-,## \8? %!2%7&# V7:9,- 1
A child class can introduce new variables
not included in the parent.
08-8/ <,:/08-8/*
\8?45 1
#3$%/45*
<,:/08-8/ ' 08-8/4/,7&894>JJ55*
@
A8:& I,/.45 1
$/:72-74T+UUbST5*
@
@
0-,## \8? %!2%7&# V7:9,- 1
08-8/ <,:/08-8/*
\8?45 1
#3$%/45*
<,:/08-8/ ' 08-8/4/,7&894>JJ55*
@
A child can override a parent function if
necessary.
A8:& %,245 1
A Dog's specific eating characteristics $/:72-74T+88ES +88ES [-3/$NT5
@
A8:& I,/.45 1
$/:72-74T+UUbST5*
@
@
1h Notur o Cod [v005j
J65
0-,## \8? %!2%7&# V7:9,- 1
08-8/ <,:/08-8/*
\8?45 1
#3$%/45*
<,:/08-8/ ' 08-8/4/,7&894>JJ55*
@
A8:& %,245 1
Call eat() from Animal. A child can execute
a function from the parent while adding its
own code.
.40$)-$&/*+,
Add some additional code for a Dog's
specific eating characteristics.
$/:72-74T+88ESSST5*
@
A8:& I,/.45 1
$/:72-74T+UUbST5*
@
@
>"N 54.'&2%(- 8&', C;,(.&'4;2( >"N 54.'&2%(- 8&', C;,(.&'4;2(
Now thot w`v hod on lntroductlon to th thory o lnhrltonc ond lts syntox, w con
dvlop o worklng xompl ln Procsslng bosd on our ],/2:0-% closs.
Lt`s rvlw o slmpl ],/2:0-% lmplmntotlon, urthr slmpllld rom Lxompl 4.J [s
pog J47j.
Choptr 4. Portlcl 5ystms
J66
Nxt, w crot o subcloss rom ],/2:0-% [lt`s coll lt M87E%22:j. |t wlll lnhrlt oll th lnstonc
vorlobls ond mthods rom ],/2:0-%. W wrlt o nw constructor wlth th nom M87E%22:
ond xcut th cod rom th pornt closs by colllng #3$%/45.
0-,## ],/2:0-% 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
],/2:0-%4]`%028/ -5 1
,00%-%/,2:87 ' 7%; ]`%028/4BCBNBJ5*
A%-80:2" ' 7%; ]`%028/4/,7&8946)C)5C/,7&8946>CB55*
-80,2:87 ' -N?%245*
@
A8:& /3745 1
3$&,2%45*
&:#$-,"45*
@
A8:& 3$&,2%45 1
A%-80:2"N,&&4,00%-%/,2:875*
-80,2:87N,&&4A%-80:2"5*
@
A8:& &:#$-,"45 1
E:--4B5*
%--:$#%4-80,2:87N!C-80,2:87N"CXCX5*
@
@
0-,## M87E%22: %!2%7&# ],/2:0-% 1
We could add variables for only Confetti
here.
M87E%22:4]`%028/ -5 1
#3$%/4-5*
@
There is no code here because we inherit
update() from parent.
Override the display method. A8:& &:#$-,"45 1
/%02d8&%4MhknhY5*
E:--4)OJ5*
#2/8.%4B5*
/%024-80,2:87N!C-80,2:87N"CXCX5*
@
@
1h Notur o Cod [v005j
J67
Lt`s mok thls o blt mor sophlstlcotd. Lt`s soy w wont to hov th M87E%22: portlcl
rotot os lt lls through th olr. W could, o cours, modl ongulor vloclty ond
occlrotlon os w dld ln Choptr 3. |nstod, w`ll try o qulck ond dlrty solutlon.
W know o portlcl hos on x locotlon somwhr btwn 0 ond th wldth o th wlndow.
Whot l w sold. whn th portlcl`s x locotlon ls 0, lts rototlon should b 0, whn lts x
locotlon ls quol to th wldth, lts rototlon should b quol to n+Ua]c? Los thls rlng o bll?
Whnvr w hov o volu wlth on rong thot w wont to mop to onothr rong, w con
us Procsslng`s 9,$45 unctlon, whlch w lornd obout ln th |ntroductlon [s pog J7j!
And just to glv lt o blt mor spln, w con octuolly mop th ongl`s rong rom 0 to
n+Ua]c'2. Lt`s look ot how thls cod lts lnto th &:#$-,"45 unctlon.
Now thot w hov o M87E%22: closs thot xtnds our bos ],/2:0-% closs, w nd to
lgur out how our ],/2:0-%["#2%9 closs con monog portlcls o dlrnt typs wlthln th
som systm. 1o occompllsh thls gool, lt`s rturn to th onlmol klngdom lnhrltonc
xompl ond s how th concpt xtnds lnto th world o polymorphlsm.
E-8,2 ,7?-% ' 9,$4-80,2:87N!CBC;:&2<CBCn+Ua]c5*
A8:& &:#$-,"45 1
E-8,2 2<%2, ' 9,$4-80,2:87N!CBC;:&2<CBCn+Ua]cQ>5*
/%02d8&%4MhknhY5*
E:--4BC-:E%#$,75*
#2/8.%4BC-:E%#$,75*
f we rotate() a shape in Processing, we
need to familiarize ourselves with
transformations. For more, visit:
http://processing.org/learning/transform2d/
$3#<d,2/:!45*
2/,7#-,2%4-80,2:87N!C-80,2:87N"5*
/82,2%42<%2,5*
/%024BCBCXCX5*
$8$d,2/:!45*
@
|nstod o uslng 9,$45 to colculot thto, how would you modl ongulor vloclty ond
occlrotlon?
MO(.2&-( >"L MO(.2&-( >"L
>"W 5*%/E*.Q,&-E b4-&2- >"W 5*%/E*.Q,&-E b4-&2-
Wlth th concpt o lnhrltonc undr our blts, w con lmogln how w would progrom o
dlvrs onlmol klngdom uslng V//,"l:#2son orroy o dogs, on orroy o cots, o turtls, o
klwls, tc. rollcklng obout.
Choptr 4. Portlcl 5ystms
J68
As th doy bglns, th onlmols or oll prtty hungry ond or looklng to ot. 5o lt`s o to
looplng tlm [nhoncd looplng tlm!j.
1hls works wll, but os our world xponds to lnclud mony mor onlmol spcls, w`r golng
to gt stuck wrltlng o lot o lndlvlduol loops. |s thls rolly ncssory? Atr oll, th croturs
or oll onlmols, ond thy oll llk to ot. Why not just hov on V//,"l:#2 o V7:9,- objcts
ond lll lt wlth oll dlrnt ||nds o onlmols?
Separate ArrayLists for each animal V//,"l:#2P\8?^ &8?# ' 7%; V//,"l:#2P\8?^45*
V//,"l:#2PM,2^ 0,2# ' 7%; V//,"l:#2PM,2^45*
V//,"l:#2Pn3/2-%^ 23/2-%# ' 7%; V//,"l:#2Pn3/2-%^45*
V//,"l:#2Pt:;:^ .:;:# ' 7%; V//,"l:#2Pt:;:^45*
E8/ 4:72 : ' B* : P )B* :((5 1
&8?#N,&&47%; \8?455*
@
E8/ 4:72 : ' B* : P )J* :((5 1
0,2#N,&&47%; M,2455*
@
E8/ 4:72 : ' B* : P G* :((5 1
23/2-%#N,&&47%; n3/2-%455*
@
E8/ 4:72 : ' B* : P pX* :((5 1
.:;:#N,&&47%; t:;:455*
@
Separate loops for each animal E8/ 4\8? &q &8?#5 1
&N%,245*
@
E8/ 4M,2 0q 0,2#5 1
0N%,245*
@
E8/ 4n3/2-% 2q 23/2-%#5 1
2N%,245*
@
E8/ 4t:;: .q .:;:#5 1
.N%,245*
@
1h Notur o Cod [v005j
J69
1h oblllty to trot o \8? objct os lthr o mmbr o th \8? closs or th V7:9,- closs [lts
porntj ls on xompl o polymorphlsm. N!'@-!1A+/)- N!'@-!1A+/)- [rom th Grk po|ymotphos,
monlng mony ormsj rrs to th trotmnt o o slngl lnstonc o on objct ln multlpl
orms. A dog ls crtolnly o dog, but slnc \8? %!2%7&# V7:9,-, lt con olso b consldrd
on onlmol. |n cod, w con rr to lt both woys.
Although th scond lln o cod mlght lnltlolly sm to vlolot syntox ruls, both woys o
dclorlng o \8? objct or lgol. Lvn though w dclor #$82 os on V7:9,- objct, w`r
rolly moklng o \8? objct ond storlng lt ln th #$82 vorlobl. And w con soly coll oll o
th V7:9,- closs mthods on spot bcous th ruls o lnhrltonc dlctot thot o dog con
do onythlng on onlmol con.
Whot l th \8? closs, howvr, ovrrlds th %,245 unctlon ln th V7:9,- closs? Lvn l
spot ls dclord os on V7:9,-, Jovo wlll dtrmln thot lts tru ldntlty ls thot o o \8? ond
run th opproprlot vrslon o th %,245 unctlon.
1hls ls portlculorly usul whn w hov on orroy or V//,"l:#2.
V//,"l:#2PV7:9,-^ .:7?&89 ' 7%; V//,"l:#2PV7:9,-^45*
E8/ 4:72 : ' B* : P )BBB* :((5 1
:E 4: P )BB5 .:7?&89N,&&47%; \8?455*
%-#% :E 4: P DBB5 .:7?&89N,&&47%; M,2455*
%-#% :E 4: P pBB5 .:7?&89N,&&47%; n3/2-%455*
%-#% .:7?&89N,&&47%; t:;:455*
@
E8/ 4V7:9,- ,q .:7?&895 1
,N%,245*
@
Just one ArrayList for all the animals!
\8? /8A%/ ' 7%; \8?45*
V7:9,- #$82 ' 7%; \8?45*
>"#T 54.'&2%( U/-'(E- 8&', 5*%/E*.Q,&-E >"#T 54.'&2%( U/-'(E- 8&', 5*%/E*.Q,&-E
Lt`s prtnd or o momnt thot polymorphlsm dosn`t xlst ond rwrlt o ],/2:0-%["#2%9
closs to lnclud mony ],/2:0-% objcts ond mony M87E%22: objcts.
0-,## ],/2:0-%["#2%9 1
We're stuck doing everything twice with
two lists!
h))&3o2./SM&)/2:'$Q 0&)/2:'$.,
h))&3o2./Sf8#9$//2Q :8#9$//2,
Choptr 4. Portlcl 5ystms
J70
Notlc how w hov two sporot llsts, on or portlcls ond on or conttl. Lvry octlon w
wont to prorm w hov to do twlc! Polymorphlsm ollows us to slmplly th obov by just
moklng on V//,"l:#2 o portlcls thot contolns both stondord ],/2:0-% objcts os wll os
M87E%22: objcts. W don`t hov to worry obout whlch or whlch, thls wlll oll b tokn cor o
or us! [Also, not thot th cod or th moln progrom ond th closss hos not chongd, so w
orn`t lncludlng lt hr. 5 th wbslt or th ull xompl.j
]`%028/ 8/:?:7*
],/2:0-%["#2%94]`%028/ -80,2:875 1
8/:?:7 ' -80,2:87N?%245*
We're stuck doing everything twice with two
lists!
0&)/2:'$. " #$! h))&3o2./SM&)/2:'$Q*+,
:8#9$//2 " #$! h))&3o2./Sf8#9$//2Q*+,
@
A8:& ,&&],/2:0-%45 1
We're stuck doing everything twice with two
lists!
0&)/2:'$.-&11*#$! M&)/2:'$*8)2G2#++,
0&)/2:'$.-&11*#$! f8#9$//2*8)2G2#++,
@
A8:& /3745 1
We're stuck doing everything twice with two
lists!
e/$)&/8)SM&)/2:'$Q 2/ " 0&)/2:'$.-2/$)&/8)*+,
;<:-% 4:2N<,#k%!2455 1
],/2:0-% $ ' :2N7%!245*
$N/3745*
:E 4$N:#\%,&455 1
:2N/%98A%45*
@
@
2/ " :8#9$//2-2/$)&/8)*+,
;<:-% 4:2N<,#k%!2455 1
M87E%22: 0 ' :2N7%!245*
0N/3745*
:E 40N:#\%,&455 1
:2N/%98A%45*
@
@
@
@
1h Notur o Cod [v005j
J7J
IJ&7:5# >K?L 9&)'/05# 8U8'#7 /1"#)/'&10# &1- :*5U7*):"/87
0-,## ],/2:0-%["#2%9 1
One list, for anything that is a Particle or
extends Particle
h))&3o2./SM&)/2:'$Q 0&)/2:'$.,
]`%028/ 8/:?:7*
],/2:0-%["#2%94]`%028/ -80,2:875 1
8/:?:7 ' -80,2:87N?%245*
$,/2:0-%# ' 7%; V//,"l:#2P],/2:0-%^45*
@
A8:& ,&&],/2:0-%45 1
E-8,2 / ' /,7&894)5*
We have a 50% chance of adding each
kind of Particle.
:E 4/ P BNJ5 1
0&)/2:'$.-&11*#$! M&)/2:'$*8)2G2#++,
@ %-#% 1
0&)/2:'$.-&11*#$! f8#9$//2*8)2G2#++,
@
@
A8:& /3745 1
c2%/,28/P],/2:0-%^ :2 ' $,/2:0-%#N:2%/,28/45*
;<:-% 4:2N<,#k%!2455 1
Polymorphism allows us to treat everything
as a Particle, whether it is a Particle or a
Confetti.
M&)/2:'$ 0 " 2/-#$I/*+,
$N/3745*
:E 4$N:#\%,&455 1
:2N/%98A%45*
@
@
@
@
Choptr 4. Portlcl 5ystms
J72
Crot o portlcl systm wlth dlrnt klnds" o portlcls ln th som systm. 1ry
vorylng mor thon just th look o th portlcls. How do you dol wlth dlrnt
bhovlors uslng lnhrltonc?
MO(.2&-( >"N MO(.2&-( >"N
>"## 54.'&2%( U/-'(E- 8&', S*.2(- >"## 54.'&2%( U/-'(E- 8&', S*.2(-
5o or ln thls choptr, w`v bn ocuslng on structurlng our cod ln on objct-orlntd woy
to monog o collctlon o portlcls. Moyb you notlcd, or moyb you dldn`t, but durlng thls
procss w unwlttlngly took o coupl stps bockword rom whr w wr ln prvlous
choptrs. Lt`s xomln th constructor o our slmpl ],/2:0-% closs.
And now lt`s look ot th 3$&,2%45 unctlon.
Our ],/2:0-% closs ls structurd to hov o constont occlrotlon, on thot nvr chongs. A
much bttr romwork would b to ollow Nwton`s scond low [| M' Aj ond lncorporot
th orc occumulotlon olgorlthm w workd so hord on ln Choptr 2 [s pog 68j.
5tp J would b to odd ln th ,$$-"b8/0%45 unctlon. [Rmmbr, w nd to mok o copy o
th ]`%028/ bor w dlvld lt by moss.j
],/2:0-%4]`%028/ -5 1
We're setting acceleration to a constant
value!
&::$'$)&/28# " #$! MN$:/8)*?J?-?=+,
A%-80:2" ' 7%; ]`%028/4/,7&8946)C)5C/,7&8946>CB55*
-80,2:87 ' -N?%245*
-:E%#$,7 ' >JJNB*
@
A8:& 3$&,2%45 1
A%-80:2"N,&&4,00%-%/,2:875*
-80,2:87N,&&4A%-80:2"5*
== +<%/% :# 2<% -:7% 8E 08&% 28 0-%,/ ,00%-%/,2:87i
-:E%#$,7 6' >NB*
@
A8:& ,$$-"b8/0%4]`%028/ E8/0%5 1
]`%028/ E ' E8/0%N?%245*
EN&:A49,##5*
,00%-%/,2:87N,&&4E5*
@
1h Notur o Cod [v005j
J73
Onc w hov thls, w con odd ln on mor lln o cod to clor th occlrotlon ot th nd
o 3$&,2%45.
And our ],/2:0-% closs ls complt!
A8:& 3$&,2%45 1
A%-80:2"N,&&4,00%-%/,2:875*
-80,2:87N,&&4A%-80:2"5*
There it is! ,00%-%/,2:87N93-24B5*
-:E%#$,7 6' >NB*
@
0-,## ],/2:0-% 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
E-8,2 -:E%#$,7*
We could vary mass for more interesting
results.
E-8,2 9,## ' )*
],/2:0-%4]`%028/ -5 1
We now start with acceleration of 0. ,00%-%/,2:87 ' 7%; ]`%028/4BCB5*
A%-80:2" ' 7%; ]`%028/4/,7&8946)C)5C/,7&8946>CB55*
-80,2:87 ' -N?%245*
-:E%#$,7 ' >JJNB*
@
A8:& /3745 1
3$&,2%45*
&:#$-,"45*
@
Newton's second law & force
accumulation
A8:& ,$$-"b8/0%4]`%028/ E8/0%5 1
]`%028/ E ' E8/0%N?%245*
EN&:A49,##5*
,00%-%/,2:87N,&&4E5*
@
Standard update A8:& 3$&,2%45 1
A%-80:2"N,&&4,00%-%/,2:875*
-80,2:87N,&&4A%-80:2"5*
,00%-%/,2:87N93-24B5*
-:E%#$,7 6' >NB*
@
Choptr 4. Portlcl 5ystms
J74
Now thot th ],/2:0-% closs ls compltd, w hov o vry lmportont qustlon to osk. Whr
do w coll th ,$$-"b8/0%45 unctlon? Whr ln th cod ls lt opproprlot to opply o orc to
o portlcl? 1h truth o th mottr ls thot thr`s no rlght or wrong onswr, lt rolly dpnds on
th xoct unctlonollty ond gools o o portlculor Procsslng sktch. 5tlll, w con crot o
gnrlc sltuotlon thot would llkly opply to most coss ond crot o modl or opplylng orcs to
lndlvlduol portlcls ln o systm.
Lt`s consldr th ollowlng gool. Apply o orc globolly vry tlm through &/,;45 to oll
portlcls. W`ll plck on osy on or now. o orc polntlng down, llk grovlty.
W sold lt should olwoys b opplld, l.. ln &/,;45, so lt`s tok o look ot our &/,;45 unctlon
os lt stonds.
Wll, lt sms thot w hov o smoll problm. ,$$-"b8/0%45 ls o mthod wrlttn lnsld th
],/2:0-% closs, but w don`t hov ony rrnc to th lndlvlduol portlcls thmslvs, only
th ],/2:0-%["#2%9 objct. th vorlobl $#.
5lnc w wont oll portlcls to rclv th orc, howvr, w con dcld to opply th orc to
th portlcl systm ond lt lt monog opplylng th orc to oll th lndlvlduol portlcls.
Our Particle is a circle. A8:& &:#$-,"45 1
#2/8.%4>JJC-:E%#$,75*
E:--4>JJC-:E%#$,75*
%--:$#%4-80,2:87N!C-80,2:87N"CXCX5*
@
Should the Particle be deleted? I88-%,7 :#\%,&45 1
:E 4-:E%#$,7 P BNB5 1
/%23/7 2/3%*
@ %-#% 1
/%23/7 E,-#%*
@
@
@
]`%028/ ?/,A:2" ' 7%; ]`%028/4BCBN)5*
A8:& &/,;45 1
I,0.?/837&4)BB5*
$#N,&&],/2:0-%45*
$#N/3745*
@
A8:& &/,;45 1
I,0.?/837&4)BB5*
]`%028/ ?/,A:2" ' 7%; ]`%028/4BCBN)5*
1h Notur o Cod [v005j
J75
O cours, l w coll o nw unctlon on th ],/2:0-%["#2%9 objct ln &/,;45, wll, w hov
to wrlt thot unctlon ln th ],/2:0-%["#2%9 closs. Lt`s dscrlb th job thot unctlon
nds to prorm. rclv o orc os o ]`%028/ ond opply thot orc to oll th portlcls.
Now ln cod.
|t olmost sms sllly to wrlt thls unctlon. Whot w`r soylng ls opply o orc to o portlcl
systm so thot th systm con opply thot orc to oll o th lndlvlduol portlcls."
Nvrthlss, lt`s rolly qult rosonobl. Atr oll, th ],/2:0-%["#2%9 objct ls ln chorg
o monoglng th portlcls, so l w wont to tolk to th portlcls, w`v got to tolk to thm
through thlr monogr. [Also, hr`s o chonc or th nhoncd loop slnc w orn`t
dltlng portlcls!j
Hr ls th ull xompl [ossumlng th xlstnc o th ],/2:0-% closs wrlttn obov, no
nd to lnclud lt ogoln slnc nothlng hos chongdj.
Applying a force to the system as a whole $#N,$$-"b8/0%4?/,A:2"5*
$#N,&&],/2:0-%45*
$#N/3745*
@
A8:& ,$$-"b8/0%4]`%028/ E5 1
E8/ 4],/2:0-% $q $,/2:0-%#5 1
$N,$$-"b8/0%4E5*
@
@
Choptr 4. Portlcl 5ystms
J76
IJ&7:5# >K@L 9&)'/05# 8U8'#7 4/'" +*)0#8
],/2:0-%["#2%9 $#*
A8:& #%23$45 1
#:F%4>BBC>BB5*
#9882<45*
$# ' 7%; ],/2:0-%["#2%947%; ]`%028/4;:&2<=>CJB55*
@
A8:& &/,;45 1
I,0.?/837&4)BB5*
Apply a force to all particles. MN$:/8) G)&L2/3 " #$! MN$:/8)*?J?-D+,
0.-&00'3^8):$*G)&L2/3+,
$#N,&&],/2:0-%45*
$#N/3745*
@
0-,## ],/2:0-%["#2%9 1
V//,"l:#2P],/2:0-%^ $,/2:0-%#*
]`%028/ 8/:?:7*
],/2:0-%["#2%94]`%028/ -80,2:875 1
8/:?:7 ' -80,2:87N?%245*
$,/2:0-%# ' 7%; V//,"l:#2P],/2:0-%^45*
@
A8:& ,&&],/2:0-%45 1
$,/2:0-%#N,&&47%; ],/2:0-%48/:?:755*
@
A8:& ,$$-"b8/0%4]`%028/ E5 1
Using an enhanced loop to apply the force
to all particles
E8/ 4],/2:0-% $q $,/2:0-%#5 1
$N,$$-"b8/0%4E5*
@
@
A8:& /3745 1
Can't use the enhanced loop because we
want to check for particles to delete.
c2%/,28/P],/2:0-%^ :2 ' $,/2:0-%#N:2%/,28/45*
;<:-% 4:2N<,#k%!2455 1
],/2:0-% $ ' 4],/2:0-%5 :2N7%!245*
$N/3745*
:E 4$N:#\%,&455 1
:2N/%98A%45*
@
@
@
@
1h Notur o Cod [v005j
J77
>"#0 54.'&2%( U/-'(E- 8&', Y(Q(%%(.- >"#0 54.'&2%( U/-'(E- 8&', Y(Q(%%(.-
Whot l w wontd to tok thls xompl on stp urthr ond odd o Y%$%--%/ objctth
lnvrs o th V22/,028/ objct w covrd ln Choptr 2 [s pog 88j thot pushs ony
portlcls owoy thot gt clos? 1hls rqulrs o blt mor sophlstlcotlon bcous, unllk th
grovlty orc, och orc on ottroctor or rpllr xrts on o portlcl must b colculotd or
och portlcl.
Lt`s stort solvlng thls problm by xomlnlng how w would lncorporot o nw Y%$%--%/
objct lnto our slmpl portlcl systm plus orcs xompl. W`r golng to nd two mojor
oddltlons to our cod.
J. A Y%$%--%/ objct [dclord, lnltlollzd, ond dlsploydj.
2. A unctlon thot posss th Y%$%--%/ objct lnto th ],/2:0-%["#2%9 so thot lt con
opply o orc to och portlcl objct.
Iiure (.: Grctit jorce-tectors cre cll
identiccl
Iiure (.(: Attrcctor jorce-tectors cre cll
dijjerent
],/2:0-%["#2%9 $#*
New thing: we declare a Repeller object. q$0$''$) )$0$''$),
A8:& #%23$45 1
#:F%4>BBC>BB5*
#9882<45*
$# ' 7%; ],/2:0-%["#2%947%; ]`%028/4;:&2<=>CJB55*
Choptr 4. Portlcl 5ystms
J78
Moklng o Y%$%--%/ objct ls qult osy, lt`s o dupllcot o th V22/,028/ closs rom Choptr
2, Lxompl 2.6 .
1h mor dllcult qustlon ls, how do w wrlt th ,$$-"Y%$%--%/45 unctlon? |nstod o
posslng o ]`%028/ lnto o unctlon llk w do wlth ,$$-"b8/0%45, w`r golng to lnstod poss
o Y%$%--%/ objct lnto ,$$-"Y%$%--%/45 ond osk thot unctlon to do th work o colculotlng
th orc btwn th rpllr ond oll portlcls. Lt`s look ot both o ths unctlons sld by
sld.
New thing: we initialize a Repeller object. )$0$''$) " #$! q$0$''$)*!21/H;>T>?JH$2GH/;>+,
@
A8:& &/,;45 1
I,0.?/837&4)BB5*
$#N,&&],/2:0-%45*
]`%028/ ?/,A:2" ' 7%; ]`%028/4BCBN)5*
$#N,$$-"b8/0%4?/,A:2"5*
New thing: we need a function to apply a
force from a repeller.
0.-&00'3q$0$''$)*)$0$''$)+,
$#N/3745*
New thing: we display the Repeller object. )$0$''$)-12.0'&3*+,
@
0-,## Y%$%--%/ 1
A Repeller doesn't move, so you just need
location.
]`%028/ -80,2:87*
E-8,2 / ' )B*
Y%$%--%/4E-8,2 !C E-8,2 "5 1
-80,2:87 ' 7%; ]`%028/4!C"5*
@
A8:& &:#$-,"45 1
#2/8.%4>JJ5*
E:--4>JJ5*
%--:$#%4-80,2:87N!C-80,2:87N"C/Q>C/Q>5*
@
@
1h Notur o Cod [v005j
J79
&::5UG*)0#WX &::5UG*)0#WX &::5UH#:#55#) &::5UH#:#55#)
A8:& ,$$-"b8/0%4]`%028/ E5 1
E8/ 4],/2:0-% $q $,/2:0-%#5 1
$N,$$-"b8/0%4E5*
@
@
A8:& ,$$-"Y%$%--%/4Y%$%--%/ /5 1
E8/ 4],/2:0-% $q $,/2:0-%#5 1
]`%028/ E8/0% ' /N/%$%-4$5*
$N,$$-"b8/0%4E8/0%5*
@
@
1h unctlons or olmost ldntlcol. 1hr or only two dlrncs. On w mntlond
boro Y%$%--%/ objct ls th orgumnt, not o ]`%028/. 1h scond dlrnc ls th
lmportont on. W must colculot o custom ]`%028/ orc or och ond vry portlcl ond
opply thot orc. How ls thot orc colculotd? |n o unctlon colld /%$%-45, whlch ls th
lnvrs o th ,22/,0245 unctlon w wrot or th V22/,028/ closs.
Notlc how throughout thls ntlr procss o oddlng o rpllr to th nvlronmnt, w`v
nvr onc consldrd dltlng th ],/2:0-% closs ltsl. A portlcl dosn`t octuolly hov to
know onythlng obout th dtolls o lts nvlronmnt, lt slmply nds to monog lts locotlon,
vloclty, ond occlrotlon, os wll os hov th oblllty to rclv on xtrnol orc ond oct on
lt.
5o w con now look ot thls xompl ln lts ntlrty, ogoln lovlng out th ],/2:0-% closs,
whlch hosn`t chongd.
All the same steps we had to calculate an
attractive force, only pointing in the
opposite direction.
]`%028/ /%$%-4],/2:0-% $5 1
1) Get force direction. ]`%028/ &:/ '
]`%028/N#3I4-80,2:87C$N-80,2:875*
2) Get distance (constrain distance). E-8,2 & ' &:/N9,?45*
& ' 087#2/,:74&CJC)BB5*
&:/N78/9,-:F%45*
3) Calculate magnitude. E-8,2 E8/0% ' 6) Q Z = 4& Q &5*
4) Make a vector out of direction and
magnitude.
&:/N93-24E8/0%5*
/%23/7 &:/*
@
Choptr 4. Portlcl 5ystms
J80
IJ&7:5# >KAL 9&)'/05#OU8'#7 4/'" )#:#55#)
One ParticleSystem ],/2:0-%["#2%9 $#*
One repeller Y%$%--%/ /%$%--%/*
A8:& #%23$45 1
#:F%4>BBC>BB5*
#9882<45*
$# ' 7%; ],/2:0-%["#2%947%; ]`%028/4;:&2<=>CJB55*
/%$%--%/ ' 7%; Y%$%--%/4;:&2<=>6>BC<%:?<2=>5*
@
A8:& &/,;45 1
I,0.?/837&4)BB5*
$#N,&&],/2:0-%45*
We're applying a universal gravity. ]`%028/ ?/,A:2" ' 7%; ]`%028/4BCBN)5*
$#N,$$-"b8/0%4?/,A:2"5*
Applying the repeller $#N,$$-"Y%$%--%/4/%$%--%/5*
$#N/3745*
/%$%--%/N&:#$-,"45*
@
1h Notur o Cod [v005j
J8J
The ParticleSystem manages all the
Particles.
0-,## ],/2:0-%["#2%9 1
V//,"l:#2P],/2:0-%^ $,/2:0-%#*
]`%028/ 8/:?:7*
],/2:0-%["#2%94]`%028/ -80,2:875 1
8/:?:7 ' -80,2:87N?%245*
$,/2:0-%# ' 7%; V//,"l:#2P],/2:0-%^45*
@
A8:& ,&&],/2:0-%45 1
$,/2:0-%#N,&&47%; ],/2:0-%48/:?:755*
@
Applying a force as a PVector A8:& ,$$-"b8/0%4]`%028/ E5 1
E8/ 4],/2:0-% $q $,/2:0-%#5 1
$N,$$-"b8/0%4E5*
@
@
A8:& ,$$-"Y%$%--%/4Y%$%--%/ /5 1
Calculating a force for each Particle based
on a Repeller
E8/ 4],/2:0-% $q $,/2:0-%#5 1
]`%028/ E8/0% ' /N/%$%-4$5*
$N,$$-"b8/0%4E8/0%5*
@
@
A8:& /3745 1
c2%/,28/P],/2:0-%^ :2 ' $,/2:0-%#N:2%/,28/45*
;<:-% 4:2N<,#k%!2455 1
],/2:0-% $ ' 4],/2:0-%5 :2N7%!245*
$N/3745*
:E 4$N:#\%,&455 1
:2N/%98A%45*
@
@
@
@
0-,## Y%$%--%/ 1
Choptr 4. Portlcl 5ystms
J82
How strong is the repeller? E-8,2 #2/%7?2< ' )BB*
]`%028/ -80,2:87*
E-8,2 / ' )B*
Y%$%--%/4E-8,2 !C E-8,2 "5 1
-80,2:87 ' 7%; ]`%028/4!C"5*
@
A8:& &:#$-,"45 1
#2/8.%4>JJ5*
E:--4>JJ5*
%--:$#%4-80,2:87N!C-80,2:87N"C/Q>C/Q>5*
@
]`%028/ /%$%-4],/2:0-% $5 1
This is the same repel algorithm we used in
Chapter 2: forces based on gravitational
attraction.
]`%028/ &:/ ' ]`%028/N#3I4-80,2:87C$N-80,2:875*
E-8,2 & ' &:/N9,?45*
&:/N78/9,-:F%45*
& ' 087#2/,:74&CJC)BB5*
E-8,2 E8/0% ' 6) Q #2/%7?2< = 4& Q &5*
&:/N93-24E8/0%5*
/%23/7 &:/*
@
@
Lxpond th obov xompl to lnclud mony rpllrs [uslng on orroy or V//,"l:#2j.
MO(.2&-( >"W MO(.2&-( >"W
Crot o portlcl systm ln whlch och portlcl rsponds to vry othr portlcl. [Not
thot w`ll b golng through thls ln dtoll ln Choptr 6.j
MO(.2&-( >"#T MO(.2&-( >"#T
>"#= CE4<( @(O':.(- 4;9 !99&'&I( b%(;9&;< >"#= CE4<( @(O':.(- 4;9 !99&'&I( b%(;9&;<
Lvn though thls book ls rolly obout bhovlors ond olgorlthms rothr thon computr grophlcs
ond dslgn, | don`t thlnk w would b obl to llv wlth ourslvs l w wnt through o
dlscusslon o portlcl systms ond nvr onc lookd ot on xompl thot lnvolvs txturlng
och portlcl wlth on lmog. 1h woy you choos to drow o portlcl ls o blg port o th puzzl
ln trms o dslgnlng crtoln typs o vlsuol cts.
Lt`s try to crot o smok slmulotlon ln Procsslng. 1ok o look ot th ollowlng two lmogs.
1h Notur o Cod [v005j
J83
Both o ths lmogs wr gnrotd rom ldntlcol olgorlthms. 1h only dlrnc ls thot o
whlt clrcl ls drown ln lmog A or och portlcl ond o uzzy" blob ls drown or och ln B.
1h good nws hr ls thot you gt o lot o bong or vry llttl buck. Bor you wrlt ony
cod, howvr, you`v got to mok your lmog txtur! | rcommnd uslng PNG ormot, os
Procsslng wlll rtoln th olpho chonnl [l.. tronsporncyj whn drowlng th lmog, whlch
ls ndd or blndlng th txtur os portlcls loyr on top o och othr. Onc you`v
mod your PNG ond dposltd lt ln your sktch`s doto" oldr, you or on your woy wlth
just o w llns o cod.
|lrst, w`ll nd to dclor o ]c9,?% objct.
IJ&7:5# >KBL F7&6# '#J'()# :&)'/05# 8U8'#7
Lood th lmog ln #%23$45.
White circles Iuzz imces uith trcnspcrenc
Iiure (.
]c9,?% :9?*
A8:& #%23$45 1
Loading the PNG :9? ' -8,&c9,?%4T2%!23/%N$7?T5*
@
Choptr 4. Portlcl 5ystms
J84
And whn lt coms tlm to drow th portlcl, w`ll us th lmog rrnc lnstod o drowlng
on lllps or rctongl.
|ncldntolly, thls smok xompl ls o nlc xcus to rvlslt th Gousslon numbr dlstrlbutlons
rom th |ntroductlon [s pog J0j. 1o mok th smok oppor o blt mor rollstlc, w don`t
wont to lounch oll th portlcls ln o purly rondom dlrctlon. |nstod, by crotlng lnltlol vloclty
vctors mostly oround o mon volu [wlth o lowr proboblllty o outllrsj, w`ll gt on ct
thot oppors lss ountoln-llk ond mor llk smok [or lrj.
Assumlng o Y,7&89 objct colld gnrotor", w could crot lnltlol vlocltls os ollows.
|lnolly, ln thls xompl, o wlnd orc ls opplld to th smok moppd rom th mous`s
horlzontol locotlon.
A8:& /%7&%/45 1
:9,?%d8&%4MhknhY5*
Note how tint() is the image equivalent of
shape's fill().
2:724>JJC-:E%#$,75*
:9,?%4:9?C-80N!C-80N"5*
@
E-8,2 A! ' 4E-8,25 ?%7%/,28/N7%!2Z,3##:,745QBNH*
E-8,2 A" ' 4E-8,25 ?%7%/,28/N7%!2Z,3##:,745QBNH 6 )NB*
A%- ' 7%; ]`%028/4A!CA"5*
A8:& &/,;45 1
I,0.?/837&4B5*
E-8,2 &! ' 9,$4983#%eCBC;:&2<C6BN>CBN>5*
Wind force points towards mouseX. ]`%028/ ;:7& ' 7%; ]`%028/4&!CB5*
$#N,$$-"b8/0%4;:7&5*
$#N/3745*
Two particles are added each cycle through
draw().
E8/ 4:72 : ' B* : P >* :((5 1
$#N,&&],/2:0-%45*
@
@
1h Notur o Cod [v005j
J85
|lnolly, lt`s worth notlng thot thr or mony dlrnt olgorlthms or blndlng colors ln
computr grophlcs. 1hs or otn rrrd to os blnd mods." By doult, whn w drow
somthlng on top o somthlng ls ln Procsslng, w only s th top loyrthls ls
commonly rrrd to os o normol" blnd mod. Whn th plxls hov olpho tronsporncy
[os thy do ln th smok xomplj, Procsslng uss on olpho composltlng olgorlthm thot
comblns o prcntog o th bockground plxls wlth th nw orground plxls bosd on
th olpho volus.
Howvr, lt`s posslbl to drow uslng othr blnd mods, ond o much lovd blnd mod or
portlcl systms ls oddltlv." Addltlv blndlng ln Procsslng wos plonrd by Robrt
Hodgln [http.//robrthodgln.com/j ln hls omous portlcl systm ond orcs xplorotlon,
Mogntosphr, whlch lotr bcom th l1uns vlsuollzr. |or mor s. Mogntosphr
[http.//robrthodgln.com/mogntosphr-port-2/j.
Addltlv blndlng ls ln oct on o th slmplst blnd olgorlthms ond lnvolvs oddlng th
plxl volus o on loyr to onothr [copplng oll volus ot 255 o coursj. 1hls rsults ln o
spoc-og glow ct du to th colors gttlng brlghtr ond brlghtr wlth mor loyrs.
1o ochlv oddltlv blndlng ln Procsslng, you`ll nd to us th ]>\ or ]H\ rndrr.
1ry crotlng your own txturs or dlrnt typs o cts. Con you mok lt look llk
lr, lnstod o smok?
MO(.2&-( >"## MO(.2&-( >"##
s on orroy o lmogs ond osslgn och ],/2:0-% objct o dlrnt lmog. Lvn
though slngl lmogs or drown by multlpl portlcls, mok sur you don`t coll
-8,&c9,?%45 ony mor thon you nd to, l.. onc or och lmog ll.
MO(.2&-( >"#0 MO(.2&-( >"#0
Choptr 4. Portlcl 5ystms
J86
IJ&7:5# >KCL 2--/'/N# E5#1-/16
1hn, bor you go to drow onythlng, you st th blnd mod uslng I-%7&d8&%45.
A8:& #%23$45 1
Using the P2D renderer #:F%4>BBC>BBC]>\5*
@
A8:& &/,;45 1
Additive blending I-%7&d8&%4V\\5*
Note that the "glowing effect of additive
blending will not work with a white (or very
bright) background.
I,0.?/837&4B5*
All your other particle stuff would go here.
@
s 2:7245 ln comblnotlon wlth oddltlv blndlng to crot o rolnbow ct.
MO(.2&-( >"#= MO(.2&-( >"#=
1ry blndlng wlth othr mods, such os [uWnYVMn, lcZrnh[n, \VYth[n, \cbbhYhkMh,
heMlu[cUk,or dulnc]lf.
MO(.2&-( >"#> MO(.2&-( >"#>
1h Notur o Cod [v005j
J87
@,( M2*-/-'(E 5.*G(2' @,( M2*-/-'(E 5.*G(2'
U'(Q > MO(.2&-(D
@43( /*:. 2.(4':.( +.*E U'(Q = 4;9 ):&%9 4 -/-'(E *+ 2.(4':.(-" f*8 24; ',(/
&;'(.42' 8&', (42, *',(.7 P4; /*: :-( &;,(.&'4;2( 4;9 Q*%/E*.Q,&-E '* 2.(4'( 4
I4.&('/ *+ 2.(4':.(-` 9(.&I(9 +.*E ',( -4E( 2*9( )4-(7 \(I(%*Q 4 E(',*9*%*</
+*. ,*8 ',(/ 2*EQ('( +*. .(-*:.2(- ^+*. (O4EQ%(` +**9_" P4; /*: '.423 4
2.(4':.(H- A,(4%',B E:2, %&3( 8( '.423(9 4 Q4.'&2%(H- %&+(-Q4;` .(E*I&;< 2.(4':.(-
8,(; 4QQ.*Q.&4'(7 6,4' .:%(- 24; /*: &;2*.Q*.4'( '* 2*;'.*% ,*8 2.(4':.(- 4.(
)*.;7
^!%-*` /*: E&<,' 2*;-&9(. :-&;< 4 Q4.'&2%( -/-'(E &'-(%+ &; ',( 9(-&<; *+ 4 2.(4':.("
6,4' ,4QQ(;- &+ /*:. (E&''(. &- '&(9 '* ',( 2.(4':.(H- %*24'&*;7_
Choptr 4. Portlcl 5ystms
J88
,"&:'#) ?K 9"U8/08 ,"&:'#) ?K 9"U8/08
_/E)&)/#8 _/E)&)/#8
A librcr implies cn cct oj jcith,Which enerctions still in dcrlness hid,
Sin in their niht in uitness oj the dcun.
! F-.402 J)70
Bor w mov on to onythlng ls, lt`s rvlslt som o th thlngs w`v don ln th lrst
our choptrs. W hov.
J. Lornd obout concpts rom th world o physlcs Whot ls o vctor? Whot ls o
orc? Whot ls o wov? tc.
2. ndrstood th moth ond olgorlthms bhlnd such concpts.
3. |mplmntd th olgorlthms ln Procsslng wlth on objct-orlntd opprooch.
1hs octlvltls hov ylldd o st o motlon slmulotlon xompls, ollowlng us to crotlvly
dln th physlcs o th worlds w bulld [whthr rollstlc or ontostlcolj. O cours, w orn`t
th lrst to try thls. 1h world o computr grophlcs ond progrommlng ls ull o sourc cod
ddlcotd to slmulotlon. Just try Googllng opn-sourc physlcs ngln" ond you could spnd
th rst o your doy pourlng ovr rlch ond complx cod. And so w must osk th qustlon. |
o cod llbrory wlll tok cor o physlcs slmulotlon, why should w bothr lornlng how to wrlt
ony o th olgorlthms ourslvs?
Hr ls whr th phllosophy bhlnd thls book coms lnto ploy. Whll mony o th llbrorls
out thr glv us physlcs [ond supr owsom odvoncd physlcs ot thotj or r, thr or
1h Notur o Cod [v005j
J89
slgnllcont rosons or lornlng th undomntols rom scrotch bor dlvlng lnto llbrorls.
|lrst, wlthout on undrstondlng o vctors, orcs, ond trlgonomtry, w`d b compltly lost
just rodlng th documntotlon o o llbrory. 5cond, vn though o llbrory moy tok cor o
th moth or us, lt won`t ncssorlly slmplly our cod. As w`ll s ln o momnt, thr con
b o grot dol o ovrhod ln slmply undrstondlng how o llbrory works ond whot lt
xpcts rom you cod-wls. |lnolly, os wondrul os o physlcs ngln mlght b, l you look
dp down lnto your horts, lt`s llkly thot you sk to crot worlds ond vlsuollzotlons thot
strtch th llmlts o lmoglnotlon. A llbrory ls grot, but lt provlds o llmltd st o oturs.
|t`s lmportont to know both whn to llv wlthln llmltotlons ln th pursult o o Procsslng
projct ond whn thos llmlts prov to b conlnlng.
1hls choptr ls ddlcotd to xomlnlng two opn-sourc physlcs llbrorlsBox2L ond
toxlcllbs` VrltPhyslcs ngln. Wlth och llbrory, w`ll voluot lts pros ond cons ond look
ot rosons why you mlght choos on o ths llbrorls or o glvn projct.
?"# 6,4' C- b*O0\ 4;9 6,(; C- C' [-(+:%7 ?"# 6,4' C- b*O0\ 4;9 6,(; C- C' [-(+:%7
Box2L bgon os o st o physlcs tutorlols wrlttn ln C by Lrln Cotto or th Gom
Lvlopr`s Conrnc ln 2006. Ovr th lost lv yors lt hos volvd lnto on rlch ond
loborot opn-sourc physlcs ngln. |t`s bn usd or countlss projcts, most notobly
hlghly succssul goms such os th oword-wlnnlng puzzl gom Croyon Physlcs ond th
runowoy mobll ond toblt hlt Angry Blrds.
On o th ky thlngs to rollz obout Box2L ls thot lt ls o tru physlcs ngln. Box2L
knows nothlng obout computr grophlcs ond th world o plxls, lt ls slmply o llbrory thot
toks ln numbrs ond splts out mor numbrs. And whot or thos numbrs? Mtrs,
kllogroms, sconds, tc. All o Box2L`s mosurmnts ond colculotlons or or rol-world
mosurmntsonly lts world" ls o two-dlmnslonol plon wlth top, bottom, lt, ond rlght
dgs. You tll lt thlngs llk. 1h grovlty o our world ls 9.8J nwtons pr kllogrom, ond o
clrcl wlth o rodlus o our mtrs ond o moss o lty kllogroms ls locotd tn mtrs obov
th world`s bottom." Box2L wlll thn tll you thlngs llk. On scond lotr, th rctongl ls
ot lv mtrs rom th bottom, two sconds lotr, lt ls tn mtrs blow," tc. Whll thls
provlds or on omozlng ond rollstlc physlcs ngln, lt olso ncssltots lots o compllcotd
cod ln ordr to tronslot bock ond orth btwn th physlcs world" [o ky trm ln Box2Lj
ond th world w wont to drow on th plxl" world o Procsslng.
5o whn ls lt worth lt to hov thls oddltlonol ovrhod? | | just wont to slmulot o clrcl
olllng down o Procsslng wlndow wlth grovlty, do | rolly nd to wrlt oll th xtro Box2L
cod just to gt thot ct? Crtolnly, th onswr ls no. W sow how to do thls rothr oslly
ln th lrst choptr o thls book. Lt`s consldr onothr scnorlo. Whot l | wont to hov o
hundrd o thos clrcls olllng? And whot l thos clrcls orn`t clrcls ot oll, but lrrgulorly
shopd polygons? And whot l | wont ths polygons to bounc o och othr ln o rollstlc
monnr whn thy collld?
Choptr 5. Physlcs Llbrorls
J90
You moy hov notlcd thot th lrst our choptrs o thls book, whll covrlng motlon ond
orcs ln dtoll, hos sklppd ovr o rothr lmportont ospct o physlcs slmulotlonco|||s|ons.
Lt`s prtnd or o momnt thot you orn`t rodlng o choptr obout llbrorls ond thot w
dcldd rlght now to covr how to hondl colllslons ln o portlcl systm. W`d hov to
voluot ond lorn two dlstlnct olgorlthms thot oddrss ths qustlons.
J. How do | dtrmln l two shops or collldlng [l.. lntrsctlngj?
2. How do | dtrmln th shops` vloclty otr th colllslon?
| w`r thlnklng obout shops llk rctongls or clrcls, qustlon #J lsn`t too tough. You`v
llkly ncountrd thls bor. |or xompl, w know two clrcls or lntrsctlng l th
dlstonc btwn thm ls lss thon th sum o thlr rodll.
OK. Now thot w know how to dtrmln l two clrcls or collldlng, how do w colculot thlr
vlocltls otr th colllslon? 1hls ls whr w`r golng to stop our dlscusslon. Why, you osk?
|t`s not thot undrstondlng th moth bhlnd colllslons lsn`t lmportont or voluobl. [|n oct, |`m
lncludlng oddltlonol xompls on th wbslt rlotd to colllslons wlthout o physlcs llbrory.j
1h roson or stopplng ls thot ll ls short [lt thls olso b o roson or you to consldr golng
outsld ond rollcklng lnstod o progrommlng oltogthrj. W con`t xpct to mostr vry
dtoll o physlcs slmulotlon. And whll w could contlnu thls dlscusslon or clrcls, lt`s only
golng to lod us to wontlng to work wlth rctongls. And strongly shopd polygons. And
curvd surocs. And swlnglng pndulums collldlng wlth sprlngy sprlngs. And ond ond ond
ond.
Worklng wlth colllslons ln our Procsslng sktch whll stlll hovlng tlm to spnd wlth our
rlnds ond omllythot`s th roson or thls choptr. Lrln Cotto spnt yors dvloplng
solutlons to ths klnds o problms so you don`t nd to nglnr thm yourslvs, ot lost
or now.
Iiure .:
1h Notur o Cod [v005j
J9J
|n concluslon, l you lnd yoursl dscrlblng on ldo or o Procsslng sktch ond th word
colllslons" coms up, thn lt`s llkly tlm to lorn Box2L. [W`ll olso ncountr othr words
thot mlght lod you down thls poth to Box2L, such os jolnt," hlng," pully," motor," tc.j
?"0 e(''&;< b*O0\ &; 5.*2(--&;< ?"0 e(''&;< b*O0\ &; 5.*2(--&;<
5o, l Box2L ls o physlcs ngln thot knows nothlng obout plxl-bosd computr grophlcs
ond ls wrlttn ln C, how or w supposd to us lt ln Procsslng?
1h good nws ls thot Box2L ls such on omozlng ond usul llbrory thot vryon wonts to
us lt|losh, Jovoscrlpt, Python, Ruby progrommrs. Oh, ond Jovo progrommrs. 1hr ls
somthlng colld JBox2L, o Jovo port o Box2L. And bcous Procsslng ls bullt on top o
Jovo, JBox2L con b usd dlrctly ln Procsslng!
5o hr`s whr w or so or.
- Box2L slt [http.//www.box2d.org/j or rrnc.
- JBox2L slt [http.//www.jbox2d.org/j or Procsslng compotlblllty.
1hls ls oll you nd to gt stortd wrltlng Box2L cod ln Procsslng. Howvr, os w or
golng to s ln o momnt, thr or svrol plcs o unctlonollty w`ll rpotdly nd ln
our Procsslng cod, ond so lt`s worth hovlng on oddltlonol loyr btwn our sktchs
ond JBox2L. |`m colllng thls PBox2Lo Procsslng Box2L hlpr" llbrory lncludd os port
o thls book`s cod xompl downloods.
- PBox2L GltHub rposltory [http.//glthub.com/shlmon/PBox2Lj
|t`s lmportont to rollz thot PBox2L ls not o Procsslng wroppr or oll o Box2L. Atr oll,
Box2L ls o thoughtully orgonlzd ond wll-structurd AP| ond thr`s no roson to tok lt
oport ond r-lmplmnt lt. Howvr, lt`s usul to hov o smoll st o unctlons thot hlp you
gt your Box2L world st up, os wll os hlp you lgur out whr to drow your Box2L
shops. And thls ls whot PBox2L wlll provld.
| should olso mntlon bor w mov orword thot thr or othr Procsslng llbrorls thot
wrop Box2L or you. On | would rcommnd toklng o look ot ls |lslco
[http.//www.rlcordmorxr.com/lslco/j by Rlcord Morxr.
?"= b*O0\ b4-&2- ?"= b*O0\ b4-&2-
Lo not dspolr! W rolly or golng to gt to th cod vry soon, ond ln som woys w`ll
blow our prvlous work out o th wotr. But bor w`r rody to do thot, lt`s lmportont to
Choptr 5. Physlcs Llbrorls
J92
wolk through th ovroll procss o uslng Box2L ln Procsslng. Lt`s bgln by wrltlng o
psudocod gnrollzotlon o oll o our xompls ln Choptrs J through 4.
Q=*RN3 Q=*RN3
J. Crot oll th objcts ln our world.
ESDF3 ESDF3
J. Colculot oll th orcs ln our world.
2. Apply oll th orcs to our objcts [| M ' Aj.
3. pdot th locotlons o oll th objcts bosd on thlr occlrotlon.
4. Lrow oll o our objcts.
Grot. Lt`s rwrlt thls psudocod os lt wlll oppor ln our Box2L xompls.
Q=*RN3 Q=*RN3
J. Crot oll th objcts ln our world.
ESDF3 ESDF3
J. Lrow oll o our objcts.
1hls, o cours, ls th ontosy o Box2L. W`v llmlnotd oll o thos polnul stps o lgurlng
out how th objcts or movlng occordlng to vloclty ond occlrotlon. Box2L ls golng to tok
cor o thls or us! 1h good nws ls thot thls dos occurotly rlct th ovroll procss. Lt`s
lmogln Box2L os o moglc box.
|n #%23$45, w`r golng to soy to Box2L. Hllo thr. Hr or oll o th thlngs | wont ln my
world." |n &/,;45, w`r golng to polltly osk Box2L. Oh, hllo ogoln. | lt`s not too much
troubl, |`d llk to drow oll o thos thlngs ln my world. Could you tll m whr thy or?"
1h bod nws. lt`s not os slmpl os th obov xplonotlon would lod you to bllv. |or on,
moklng th stu thot gos ln th Box2L world lnvolvs wodlng through th documntotlon or
how dlrnt klnds o shops or bullt ond conlgurd. 5cond, w hov to rmmbr thot w
con`t tll Box2L onythlng obout plxls, os lt wlll slmply gt conusd ond oll oport. Bor w
tll Box2L whot w wont ln our world, w hov to convrt our plxl unlts to Box2L world"
unlts. And th som ls tru whn lt coms tlm to drow our stu. Box2L ls golng to tll us th
locotlon o th thlngs ln lts world, whlch w thn hov to tronslot or th plxl world.
UM@[5 UM@[5
J. Crot vrythlng thot llvs ln our plxl world.
1h Notur o Cod [v005j
J93
2. 1ronslot th plxl world lnto th Box2L world.
\Y!6 \Y!6
J. Ask Box2L whr vrythlng ls.
2. 1ronslot Box2L`s onswr lnto th plxl world.
3. Lrow vrythlng.
Now thot w undrstond thot onythlng w crot ln our Procsslng sktch hos to b plocd
lnto th Box2L world, lt`s look ot on ovrvlw o th lmnts thot mok up thot world.
P*.( (%(E(;'- *+ 4 b*O0\ 8*.%9D P*.( (%(E(;'- *+ 4 b*O0\ 8*.%9D
J. F!1'8 F!1'8. Monogs th physlcs slmulotlon. |t knows vrythlng obout th ovroll
coordlnot spoc ond olso stors llsts o vry lmnt ln th world [s 2-4
blowj.
2. T!8@ T!8@. 5rvs os th prlmory lmnt ln th Box2L world. |t hos o locotlon. |t hos o
vloclty. 5ound omlllor? 1h W8&" ls ssntlolly th closs w`v bn wrltlng on
our own ln our vctors ond orcs xompls.
3. Q+(A$ Q+(A$. Kps trock o oll th ncssory colllslon gomtry ottochd to o body.
4. U/K&:1$ U/K&:1$. Attochs o shop to o body ond sts proprtls such os dnslty, rlctlon,
ond rstltutlon.
5. V!/.& V!/.&. Acts os o connctlon btwn two bodls [or btwn on body ond th
world ltslj.
|n th nxt our sctlons, w or golng to wolk through och o th obov lmnts ln dtoll,
bulldlng svrol xompls olong th woy. But lrst thr ls on othr lmportont lmnt w
should brlly dlscuss.
6. W$%X W$%X. Lscrlbs o vctor ln th Box2L world.
And so hr w or, orrlvlng wlth trpldotlon ot on unortunot truth ln th world o uslng
physlcs llbrorls. Any physlcs slmulotlon ls golng to lnvolv th concpt o o vctor. 1hls ls
th good port. Atr oll, w just spnt svrol choptrs omlllorlzlng ourslvs wlth whot lt
mons to dscrlb motlon ond orcs wlth vctors. W don`t hov to lorn onythlng nw
concptuolly.
Now or th port thot moks th slngl tor oll rom my y. w don`t gt to us ]`%028/.
|t`s nlc thot Procsslng hos ]`%028/ or us, but onytlm you us o physlcs llbrory you wlll
probobly dlscovr thot th llbrory lncluds lts own vctor lmplmntotlon. 1hls moks sns,
Choptr 5. Physlcs Llbrorls
J94
otr oll, why should Box2L b xpctd to know obout ]`%028/? And ln mony coss, th
physlcs ngln wlll wont to lmplmnt o vctor closs ln o spcllc woy so thot lt ls spclolly
compotlbl wlth th rst o th llbrory`s cod. 5o whll w don`t hov to lorn onythlng nw
concptuolly, w do hov to gt usd to som nw nomlng convntlons ond syntox. Lt`s
qulckly dmonstrot o w o th boslcs ln `%0> os compord to thos ln ]`%028/.
Lt`s soy w wont to odd two vctors togthr.
9Q#0'*) 9Q#0'*) Q#0< Q#0<
]`%028/ , ' 7%; ]`%028/4)C6)5*
]`%028/ I ' 7%; ]`%028/4HCD5*
,N,&&4I5*
`%0> , ' 7%; `%0>4)C6)5*
`%0> I ' 7%; `%0>4HCD5*
,N,&&l80,-4I5*
]`%028/ , ' 7%; ]`%028/4)C6)5*
]`%028/ I ' 7%; ]`%028/4HCD5*
]`%028/ 0 ' ]`%028/N,&&4,CI5*
`%0> , ' 7%; `%0>4)C6)5*
`%0> I ' 7%; `%0>4HCD5*
`%0> 0 ' ,N,&&4I5*
How obout l w wont to multlply ond scol thm?
9Q#0'*) 9Q#0'*) Q#0< Q#0<
]`%028/ , ' 7%; ]`%028/4)C6)5*
E-8,2 7 ' J*
,N93-2475*
`%0> , ' 7%; `%0>4)C6)5*
E-8,2 7 ' J*
,N93-l80,-475*
]`%028/ , ' 7%; ]`%028/4)C6)5*
E-8,2 7 ' J*
]`%028/ 0 ' ]`%028/N93-24,C75*
`%0> , ' 7%; `%0>4)C6)5*
E-8,2 7 ' J*
`%0> 0 ' ,N93-475*
Mognltud ond normollz?
9Q#0'*) 9Q#0'*) Q#0< Q#0<
]`%028/ , ' 7%; ]`%028/4)C6)5*
E-8,2 9 ' ,N9,?45*
,N78/9,-:F%45*
`%0> , ' 7%; `%0>4)C6)5*
E-8,2 9 ' ,N-%7?2<45*
,N78/9,-:F%45*
As you con s, th concpts or th som, but th unctlon noms ond th orgumnts or
sllghtly dlrnt. |or xompl, lnstod o stotlc ond non-stotlc ,&&45 ond 93-245, l o `%0> ls
oltrd, th word locol" ls lncludd ln th unctlon nom,&&l80,-45, 93-2l80,-45.
1h Notur o Cod [v005j
J95
W`ll covr th boslcs o whot you nd to know hr, but l you or looklng or mor, ull
documntotlon o `%0> con b ound by downloodlng th JBox2L sourc cod
[http.//cod.googl.com/p/jbox2d/j.
?"> V&I&;< &; 4 b*O0\ 6*.%9 ?"> V&I&;< &; 4 b*O0\ 6*.%9
1h Box2L +8/-& objct ls ln chorg o vrythlng. |t monogs th coordlnot spoc o th
world, oll o th stu thot llvs ln th world, ond dclds whn tlm movs orword ln th
world.
|n ordr to hov Box2L os port o our Procsslng sktchs, th +8/-& ls th vry lrst thlng
thot nds to b st up. Hr ls whr PBox2L coms ln hondy ond toks cor o moklng
th world or us.
Whn you coll 0/%,2%+8/-&45, PBox2L wlll st up o doult grovlty or you [polntlng downj,
howvr, you con olwoys oltr th grovlty o your world by soylng.
|t`s worth notlng thot grovlty dosn`t hov to b lxd, nor dos lt olwoys hov to polnt
downwords, you con odjust th grovlty vctor whll your progrom ls runnlng. Grovlty con b
turnd o by sttlng lt to o [0,0j vctor.
5o, whot or thos numbrs 0 ond -J0? 1hls should rmlnd us o on o th most lmportont
dtolls o uslng Box2L. th Box2L coordlnot systm ls not your plxl coordlnot systm!
Lt`s look ot how Box2L ond o Procsslng wlndow thlnk dlrntly o thlr worlds.
]W8!>\ I8!>&*
A8:& #%23$45 1
I8!>& ' 7%; ]W8!>\42<:#5*
nitializes a Box2D world with default
settings
I8!>&N0/%,2%+8/-&45*
@
I8!>&N#%2Z/,A:2"4BC 6)B5*
Choptr 5. Physlcs Llbrorls
J96
Notlc how ln Box2L (0,0I ls ln th cntr ond up ls th posltlv dlrctlon olong th y-oxls!
Box2L`s coordlnot systm ls just llk thot lovly old-oshlond Cortslon on wlth (0,0I ln th
cntr ond up polntlng ln o posltlv dlrctlon. Procsslng, on th othr hond, uss o trodltlonol
computr grophlcs coordlnot systm whr (0,0I ls ln th top lt cornr ond down ls th
posltlv dlrctlon olong th y-oxls. 1hls ls why l w wont objcts to oll down wlth grovlty, w
nd to glv Box2L o grovlty orc wlth o ngotlv y-volu.
Lucklly or us, l w prr to thlnk ln trms o plxl coordlnots [whlch os Procsslng
progrommrs, w or llkly to doj, PBox2L ors o srls o hlpr unctlons thot convrt
btwn plxl spoc ond Box2L spoc. Bor w mov onto th nxt sctlon ond bgln
crotlng Box2L bodls, lt`s tok o look ot how ths hlpr unctlons work.
Lt`s soy w wont to tll Box2L whr th mous ls ln lts world. W know th mous ls
locotd ot 4983#%eC983#%f5 ln Procsslng. 1o convrt lt, w soy w wont to convrt o
coordlnot" rom plxls" to world"088/&]:!%-#n8+8/-&45. Or.
Whot l w hod o Box2L world coordlnot ond wontd to tronslot lt to our plxl spoc?
Iiure .z
`%0> ?/,A:2" ' 7%; `%0>4BC 6)B5*
Convert mouseX,mouseY to coordinate in
Box2D world.
`%0> 983#%+8/-& '
I8!>&N088/&]:!%-#n8+8/-&4983#%eC983#%f5*
To demonstrate, let's just make up a world
position.
`%0> ;8/-&]8# ' 7%; `%0>46)BC>J5*
Convert to pixel space. This is necessary
because ultimately we are going to want to
draw the elements in our window.
`%0> $:!%-]8# ' I8!>&N088/&+8/-&n8]:!%-#4;8/-&]8#5*
%--:$#%4$:!%-]8#N!C $:!%-]8#N"C)GC)G5*
1h Notur o Cod [v005j
J97
PBox2L hos o st o unctlons to tok cor o tronslotlng bock ond orth btwn th Box2L
world ond plxls. |t`s probobly oslr to lorn obout oll o ths unctlons durlng th cours
o octuolly lmplmntlng our xompls, but lt`s qulckly look ovr th llst o th posslbllltls.
!&83 !&83 G(10'/*1 G(10'/*1
Convrt locotlon rom World to Plxls `%0> 088/&+8/-&n8]:!%-#4`%0> ;8/-&5
Convrt locotlon rom World to Plxls
`%0> 088/&+8/-&n8]:!%-#4E-8,2 ;8/-&eC
E-8,2 ;8/-&f5
Convrt locotlon rom Plxls to World `%0> 088/&]:!%-#n8+8/-&4`%0> #0/%%75
Convrt locotlon rom Plxls to World
`%0> 088/&]:!%-#n8+8/-&4E-8,2 $:!%-eC
E-8,2 $:!%-f5
5col o dlmnslon [such os hlght, wldth, or rodlusj
rom Plxls to World
E-8,2 #0,-,/]:!%-#n8+8/-&4E-8,2 A,-5
5col o dlmnslon rom World to Plxls E-8,2 #0,-,/+8/-&n8]:!%-#4E-8,2 A,-5
1hr or olso oddltlonol unctlons thot ollow you to poss or rclv o ]`%028/ whn
tronslotlng bock ond orth, but slnc w or only worklng wlth Box2L ln th xompls ln thls
choptr, lt`s oslst to stlck wlth th `%0> closs or oll vctors.
Onc th world ls lnltlollzd, w or rody to octuolly put stu ln th worldBox2L bodls.
?"? b:&%9&;< 4 b*O0\ )*9/ ?"? b:&%9&;< 4 b*O0\ )*9/
A Box2L body ls th prlmory lmnt ln th Box2L world. |t`s th qulvolnt to th d8A%/
closs w bullt on our own ln prvlous choptrsth thlng thot movs oround th spoc ond
xprlncs orcs. |t con olso b stotlc [monlng lxd ond not movlngj. |t`s lmportont to
not, howvr, thot o body hos no gomtry, lt lsn`t onythlng physlcol. Rothr, bodls hov
Box2L shops ottochd to thm. [1hls woy, o body con b o slngl rctongl or o rctongl
ottochd to o clrcl, tc.j W`ll look ot shops ln o momnt, lrst, lt`s bulld o body.
U'(Q #D \(+&;( 4 )*9/" U'(Q #D \(+&;( 4 )*9/"
1h lrst thlng w hov to do ls crot o body dlnltlon." 1hls wlll lt us dln th
proprtls o th body w lntnd to mok. 1hls moy sm o blt owkword ot lrst, but lt`s how
Box2L ls structurd. Anytlm you wont to mok o thlng," you hov to mok o thlng
dlnltlon" lrst. 1hls wlll hold tru or bodls, shops, ond jolnts.
Choptr 5. Physlcs Llbrorls
J98
Make a body definition before making a
Body.
W8&"\%E I& ' 7%; W8&"\%E45*
U'(Q 0D P*;+&<:.( ',( )*9/ 9(+&;&'&*;" U'(Q 0D P*;+&<:.( ',( )*9/ 9(+&;&'&*;"
1h body dlnltlon ls whr w con st spcllc proprtls or ottrlbuts o th body w lntnd
to mok. On ottrlbut o o body, or xompl, ls lts stortlng locotlon. Lt`s soy w wont to
posltlon th body ln th cntr o th Procsslng wlndow.
Longr, dongr! |`m not golng to oddrss thls wlth vry slngl xompl, but lt`s lmportont to
ot lost polnt out th prllous poth w or toklng wlth th obov lln o cod. Rmmbr, l w
or golng to tll Box2L whr w wont th body to stort, w must glv Box2L o world
coordlnot! Ys, w wont to thlnk o lts locotlon ln trms o plxls, but Box2L dosn`t cor.
And so bor w poss thot posltlon to th body dlnltlon, w must mok sur to us on o
our hlpr convrslon unctlons.
1h body dlnltlon must olso spcly th typ" o body w wont to mok. 1hr or thr
posslbllltls.
- E@.(-/%6 E@.(-/%6 1hls ls whot w wlll us most otno ully slmulotd" body. A dynomlc
body movs oround th world, colllds wlth othr bodls, ond rsponds to th orcs
ln lts nvlronmnt.
- Q&(&/%6 Q&(&/%6 A stotlc body ls on thot connot mov [os l lt hod on lnlnlt mossj. W`ll us
stotlc bodls or lxd plotorms ond boundorls.
- Y/.$-(&/%6 Y/.$-(&/%6 A klnmotlc body con b movd monuolly by sttlng lts vloclty dlrctly.
| you hov o usr-controlld objct ln your world, you con us o klnmotlc body.
Not thot klnmotlc bodls collld only wlth dynomlc bodls ond not wlth othr stotlc
or klnmotlc ons.
1hr or svrol othr proprtls you con st ln th body dlnltlon. |or xompl, l you wont
your body to hov o lxd rototlon [l.. nvr rototj, you con soy.
A Vec2 in the center of the Processing
window
`%0> 0%72%/ ' 7%; `%0>4;:&2<=>C<%:?<2=>5*
A Vec2 in the center of the Processing
window converted to Box2D World
coordinates!
`%0> 0%72%/ '
I8!>&N088/&]:!%-#n8+8/-&4;:&2<=>C<%:?<2=>55*
Setting the position attribute of the Box2D
body definition
I&N$8#:2:87N#%240%72%/5*
I&NE:!%&Y82,2:87 ' 2/3%*
1h Notur o Cod [v005j
J99
You con olso st o volu or llnor or ongulor domplng, so thot th objct contlnuously slows
os l thr ls rlctlon.
|n oddltlon, ost-movlng objcts ln Box2L should b st os bullts. 1hls tlls th Box2L
ngln thot th objct moy mov vry qulckly ond to chck lts colllslons mor corully so
thot lt dosn`t occldntolly jump ovr onothr body.
I&N-:7%,/\,9$:7? ' BNX*
I&N,7?3-,/\,9$:7? ' BNp*
I&NI3--%2 ' 2/3%*
U'(Q =D P.(4'( ',( )*9/" U'(Q =D P.(4'( ',( )*9/"
Onc w`r don wlth th dlnltlon [W8&"\%Ej, w con crot th W8&" objct ltsl. PBox2L
provlds o hlpr unctlon or thls0/%,2%W8&"[j.
The Body object is created by passing in
the Body Definition. (This allows for making
multiple bodies from one definition.)
W8&" I8&" ' I8!>&N0/%,2%W8&"4I&5*
U'(Q >D U(' 4;/ *',(. 2*;9&'&*;- +*. ',( )*9/H- -'4.'&;< -'4'(" U'(Q >D U(' 4;/ *',(. 2*;9&'&*;- +*. ',( )*9/H- -'4.'&;< -'4'("
|lnolly, though not rqulrd, l you wont to st ony othr lnltlol condltlons or th body, such
os llnor or ongulor vloclty, you con do so wlth th nwly crotd W8&" objct.
Setting an arbitrary initial velocity I8&"N#%2l:7%,/`%-80:2"47%; `%0>4BCH55*
Setting an arbitrary initial angular velocity I8&"N#%2V7?3-,/`%-80:2"4)N>5*
?"K @,.((H- P*EQ4;/D b*9&(- 4;9 U,4Q(- 4;9 ?"K @,.((H- P*EQ4;/D b*9&(- 4;9 U,4Q(- 4;9
S&O':.(- S&O':.(-
A body on lts own dosn`t physlcolly xlst ln th world. |t`s llk o soul wlth no humon orm to
lnhoblt. |or o body to hov moss, w must lrst dln o shop ond ottoch thot shop to th
body wlth somthlng known os o lxtur.
1h job o th Box2L [<,$% closs ls to kp trock o oll th ncssory colllslon gomtry
ottochd to o body. A shop olso hos svrol lmportont proprtls thot oct th body`s
motlon. 1hr ls dnslty, whlch ultlmotly dtrmlns thot body`s moss. 5hops olso hov
tt|ct|on ond test|tut|on [bounclnss"j whlch wlll b dlnd through o lxtur. On o th
Choptr 5. Physlcs Llbrorls
200
nlc thlngs obout Box2L`s mthodology, whlch sporots th concpts o bodls ond shops
lnto two sporot objcts, ls thot you con ottoch multlpl shops to o slngl body ln ordr to
crot mor complx orms. W`ll s thls ln o utur xompl.
1o crot o shop, w nd to lrst dcld whot klnd o shop w wont to mok. |or most
non-clrculor shops, o ]8-"?87[<,$% objct wlll work just ln. |or xompl, lt`s look ot how
w dln o rctongl.
U'(Q #D \(+&;( 4 -,4Q(" U'(Q #D \(+&;( 4 -,4Q("
Nxt up, w hov to dln th wldth ond hlght o th rctongl. Lt`s soy w wont our
rctongl to b J50J00 plxls. Rmmbr, plxl unlts or no good or Box2L shops! 5o w
hov to us our hlpr unctlons to convrt thm lrst.
Define the shape: a polygon. ]8-"?87[<,$% $# ' 7%; ]8-"?87[<,$%45*
Scale dimensions from pixels to Box2D
world.
E-8,2 I8!>\; ' I8!>&N#0,-,/]:!%-#n8+8/-&4)JB5*
E-8,2 I8!>\< ' I8!>&N#0,-,/]:!%-#n8+8/-&4)BB5*
Use setAsBox() function to define shape as
a rectangle.
$#N#%2V#W8!4I8!>\;C I8!>\<5*
U'(Q 0D P.(4'( 4 +&O':.(" U'(Q 0D P.(4'( 4 +&O':.("
1h shop ond body or mod os two sporot ntltls. |n ordr to ottoch o shop to o body,
w must mok o lxtur. A lxtur ls crotd, just os wlth th body, vlo o lxtur dlnltlon [l..
b:!23/%\%E clossj ond osslgnd o shop.
Onc w hov th lxtur dlnltlon, w con st poromtrs thot oct th physlcs or th
shop blng ottochd.
b:!23/%\%E E& ' 7%; b:!23/%\%E45*
The fixture is assigned the PolygonShape
we just made.
E&N#<,$% ' $#*
The coefficient of friction for the shape,
typically between 0 and 1
E&NE/:02:87 ' BNH*
The Shape's restitution (i.e. elasticity),
typically between 0 and 1
E&N/%#2:232:87 ' BNJ*
The Shape's density, measured in kilograms
per meter squared
E&N&%7#:2" ' )NB*
1h Notur o Cod [v005j
20J
U'(Q =D !''42, ',( -,4Q( '* ',( )*9/ 8&', ',( +&O':.(" U'(Q =D !''42, ',( -,4Q( '* ',( )*9/ 8&', ',( +&O':.("
Onc th lxtur ls dlnd, oll w hov lt to do ls ottoch th shop to th body wlth th
lxtur by colllng th 0/%,2%b:!23/%45 unctlon.
| should not thot 5tp 2 con b sklppd l you do not nd to st th physlcs proprtls.
[Box2L wlll us doult volus.j You con crot o lxtur ond ottoch th shop oll ln on stp
by soylng.
Whll most o our xompls wlll tok cor o ottochlng shops only onc whn th body ls
lrst bullt, thls ls not o llmltotlon o Box2L. Box2L ollows or shops to b crotd ond
dstroyd on th ly.
Bor w put ony o thls cod w`v bn wrltlng lnto o Procsslng sktch, lt`s rvlw oll
th stps w took to construct o Body.
J. Lln o body uslng o W8&"\%E objct [st ony proprtls, such os locotlonj.
2. Crot th W8&" objct rom th body dlnltlon.
3. Lln o [<,$% objct uslng ]8-"?87[<,$%, M:/0-%[<,$%, or ony othr shop
closs.
4. Lln o lxtur uslng b:!23/%\%E ond osslgn th lxtur o shop [st ony
proprtls, such os rlctlon, dnslty, ond rstltutlonj.
5. Attoch th shop to th body.
Creates the Fixture and attaches the
Shape to the Body object
I8&"N0/%,2%b:!23/%4E&5*
Creates the Fixture and attaches the
Shape with a density of 1
I8&"N0/%,2%b:!23/%4$#C)5*
Step 1. Define the body. W8&"\%E I& ' 7%; W8&"\%E45*
I&N$8#:2:87N#%24I8!>&N088/&]:!%-#n8+8/-&4;:&2<=>C<%:?<2=>55*
Step 2. Create the body. W8&" I8&" ' I8!>&N0/%,2%W8&"4I&5*
Step 3. Define the shape. ]8-"?87[<,$% $# ' 7%; ]8-"?87[<,$%45*
E-8,2 ; ' I8!>&N#0,-,/]:!%-#n8+8/-&4)JB5*
E-8,2 < ' I8!>&N#0,-,/]:!%-#n8+8/-&4)BB5*
$#N#%2V#W8!4;C <5*
Choptr 5. Physlcs Llbrorls
202
Step 4. Define the fixture. b:!23/%\%E E& ' 7%; b:!23/%\%E45*
E&N#<,$% ' $#*
E&N&%7#:2" ' )*
E&NE/:02:87 ' BNH*
E&N/%#2:232:87 ' BNJ*
Step 5. Attach the shape to the body with
the Fixture.
I8&"N0/%,2%b:!23/%4E&5*
Knowlng whot you know obout Box2L so or, lll ln th blonk ln th cod blow thot
dmonstrots how to mok o clrculor shop ln Box2L.
M:/0-%[<,$% 0# ' 7%; M:/0-%[<,$%45*
E-8,2 /,&:3# ' )B*
0#N9a/,&:3# ' aaaaaaaaaaaaaaaaaaaa*
b:!23/%\%E E& ' 7%; b:!23/%\%E45*
E&N#<,$% ' 0#*
E&N&%7#:2" ' )*
E&NE/:02:87 ' BN)*
E&N/%#2:232:87 ' BNH*
I8&"N0/%,2%b:!23/%4E&5*
MO(.2&-( ?"# MO(.2&-( ?"#
?"L b*O0\ 4;9 5.*2(--&;<D Y(:;&'(9 4;9 C' S((%- U* ?"L b*O0\ 4;9 5.*2(--&;<D Y(:;&'(9 4;9 C' S((%- U*
e**9 e**9
Onc o body ls mod, lt llvs ln th Box2L physlcs world. Box2L wlll olwoys know lt`s thr,
chck lt or colllslons, mov lt opproprlotly occordlng to th orcs, tc. |t`ll do oll thot or you
wlthout you hovlng to llt o lngr! Whot lt won`t do, howvr, ls dlsploy th body or you. 1hls
ls o good thlng. 1hls ls your tlm to shln. Whn worklng wlth Box2L, whot w`r ssntlolly
soylng ls, | wont to b th dslgnr o my world, ond | wont you, Box2L, to comput oll th
physlcs."
Now, Box2L wlll kp o llst o oll th bodls thot xlst ln th world. 1hls con b occssd by
colllng th World objct`s ?%2W8&"l:#245 unctlon. Nvrthlss, whot |`m golng to
dmonstrot hr ls o tchnlqu or kplng your own body llsts. Ys, thls moy b o blt
rdundont ond w prhops socrllc o blt o lclncy. But w mor thon mok up or thot wlth
os o us. 1hls mthodology wlll ollow us to progrom llk w`r usd to ln Procsslng, ond
w con oslly kp trock o whlch bodls or whlch ond rndr thm opproprlotly. Lt`s
consldr th structur o th ollowlng Procsslng sktch.
1h Notur o Cod [v005j
203
1hls looks llk ony ol` Procsslng sktch. W hov o moln tob colld Boxs" ond o
Boundory" ond o Box" tob. Lt`s thlnk obout th Box tob or o momnt. 1h Box tob ls
whr w wlll wrlt o slmpl closs to dscrlb o W8! objct, o rctongulor body ln our world.
Lt`s wrlt o moln tob thot crots o nw W8! whnvr th mous ls prssd ond stors oll
th W8! objcts ln on V//,"l:#2. [1hls ls vry slmllor to our opprooch ln th portlcl systm
xompls rom Choptr 4.j
Iiure .
0-,## W8! 1
Our Box object has an x,y location and a
width and a height.
E-8,2 !C"*
E-8,2 ;C<*
W8!4E-8,2 !aC E-8,2 "a5 1
The location is initalized in the constructor
via arguments
! ' !a*
" ' "a*
; ' )G*
< ' )G*
@
A8:& &:#$-,"45 1
We draw the Box object using Processing's
rect() function.
E:--4)OJ5*
#2/8.%4B5*
/%02d8&%4MhknhY5*
/%024!C"C;C<5*
@
@
Choptr 5. Physlcs Llbrorls
204
IJ&7:5# ?K;L 2 0*7+*)'&E5# &1- 0*VU 9)*0#88/16 83#'0" '"&' 1##-8 & 5/''5# S*J<.
Now, hr`s our osslgnmnt. 1ok th obov xompl vrbotlm, but lnstod o drowlng lxd
boxs on th scrn, drow boxs thot xprlnc physlcs [vlo Box2Lj os soon os thy oppor.
W`ll nd two mojor stps to occompllsh our gool.
A list to store all Box objects V//,"l:#2PW8!^ I8!%#*
A8:& #%23$45 1
#:F%4DBBCHBB5*
I8!%# ' 7%; V//,"l:#2PW8!^45*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
When the mouse is pressed, add a new
Box object.
:E 4983#%]/%##%&5 1
W8! $ ' 7%; W8!4983#%eC983#%f5*
I8!%#N,&&4$5*
@
Display all the Box objects. E8/ 4W8! Iq I8!%#5 1
IN&:#$-,"45*
@
@
U'(Q #D !99 b*O0\ '* *:. E4&; Q.*<.4E ^&"(" -(':Q^_ 4;9 9.48^__" U'(Q #D !99 b*O0\ '* *:. E4&; Q.*<.4E ^&"(" -(':Q^_ 4;9 9.48^__"
1hls port ls not too tough. W sow thls olrody ln our dlscusslon o bulldlng o Box2L world.
1hls ls tokn cor o or us by th PBox2L hlpr closs. W con crot o PBox2L objct ond
lnltlollz lt ln #%23$45.
1hn ln &/,;45, w nd to mok sur w coll on vry lmportont unctlon. #2%$45. Wlthout
thls unctlon, nothlng would vr hoppn! #2%$45 odvoncs th Box2L world o stp urthr ln
tlm. |ntrnolly, Box2L swps through ond looks ot oll o th Bodls ond lgurs out whot to
do wlth thm. Just colllng #2%$45 on lts own movs th Box2L world orword wlth doult
sttlngs, howvr, lt ls customlzobl [ond thls ls documntd ln th PBox2L sourcj.
]W8!>\ I8!>&*
A8:& #%23$45 1
nitialize and create the Box2D world. I8!>& ' 7%; ]W8!>\42<:#5*
I8!>&N0/%,2%+8/-&45*
@
1h Notur o Cod [v005j
205
A8:& &/,;45 1
We must always step through time! I8!>&N#2%$45*
@
U'(Q 0D V&;3 (I(./ 5.*2(--&;< b*O *)G(2' 8&', 4 b*O0\ b*9/ *)G(2'" U'(Q 0D V&;3 (I(./ 5.*2(--&;< b*O *)G(2' 8&', 4 b*O0\ b*9/ *)G(2'"
As o thls momnt, th W8! closs lncluds vorlobls or locotlon ond wldth ond hlght. Whot
w now wont to soy ls.
| hrby rllnqulsh th commond o thls objct`s posltlon to Box2L. | no longr nd to
kp trock o onythlng rlotd to locotlon, vloclty, ond occlrotlon. |nstod, | only nd to
kp trock o o Box2L body ond hov olth thot Box2L wlll do th rst."
W don`t nd (x,yI onymor slnc, os w`ll s, th body ltsl wlll kp trock o lts
locotlon. 1h body tchnlcolly could olso kp trock o th wldth ond hlght or us, but slnc
Box2L lsn`t golng to do onythlng to oltr thos volus ovr th ll o th W8! objct, w
mlght os wll just hold onto thm ourslvs untll lt`s tlm to drow th W8!.
1hn, ln our constructor, ln oddltlon to lnltlollzlng th wldth ond hlght, w con go ohod
ond lnclud oll o th body ond shop cod w lornd ln th prvlous two sctlons!
0-,## W8! 1
nstead of any of the usual variables, we
will store a reference to a Box2D body.
W8&" I8&"*
E-8,2 ;*
E-8,2 <*
W8!45 1
; ' )G*
< ' )G*
Build body. W8&"\%E I& ' 7%; W8&"\%E45*
I&N2"$% ' W8&"n"$%N\fkVdcM*
I&N$8#:2:87N#%24I8!>&N088/&]:!%-#n8+8/-&4983#%eC983#%f55*
I8&" ' I8!>&N0/%,2%W8&"4I&5*
Build shape. ]8-"?87[<,$% $# ' 7%; ]8-"?87[<,$%45*
Box2D considers the width and height of a
rectangle to be the distance from the
center to the edge (so half of what we
normally think of as width or height).
E-8,2 I8!>&+ ' I8!>&N#0,-,/]:!%-#n8+8/-&4;=>5*
E-8,2 I8!>&r ' I8!>&N#0,-,/]:!%-#n8+8/-&4<=>5*
Choptr 5. Physlcs Llbrorls
206
OK, w`r olmost thr. Bor w lntroducd Box2L, lt wos osy to drow th W8!. 1h
objct`s locotlon wos stord ln vorlobls ! ond ".
But now Box2L monogs th objct`s motlon, so w con no longr us our own vorlobls to
dlsploy th shop. Not to or! Our W8! objct hos o rrnc to th Box2L body ossoclotd
wlth lt. 5o oll w nd to do ls polltly osk th body, Pordon m, whr or you locotd?"
5lnc thls ls o tosk w`ll nd to do qult otn, PBox2L lncluds o hlpr unctlon.
?%2W8&"]:!%-M88/&45.
Just knowlng th locotlon o o body lsn`t nough, w olso nd to know lts ongl o rototlon.
Onc w hov th locotlon ond ongl, lt`s osy to dlsploy th objct uslng 2/,7#-,2%45 ond
/82,2%45. Not, howvr, thot th Box2L coordlnot systm consldrs rototlon ln th
opposlt dlrctlon rom Procsslng, so w nd to multlply th ongl by -J.
$#N#%2V#W8!4I8!>&+C I8!>&r5*
b:!23/%\%E E& ' 7%; b:!23/%\%E45*
E&N#<,$% ' $#*
E&N&%7#:2" ' )*
Set physics parameters. E&NE/:02:87 ' BNH*
E&N/%#2:232:87 ' BNJ*
Attach the Shape to the Body with the
Fixture.
I8&"N0/%,2%b:!23/%4E&5*
@
Drawing the object using rect() A8:& &:#$-,"45 1
E:--4)OJ5*
#2/8.%4B5*
/%02d8&%4MhknhY5*
/%024!C"C;C<5*
@
`%0> $8# ' I8!>&N?%2W8&"]:!%-M88/&4I8&"5*
E-8,2 , ' I8&"N?%2V7?-%45*
1h Notur o Cod [v005j
207
|n cos w wont to hov objcts thot con b rmovd rom th Box2L world, lt`s olso usul
to lnclud o unctlon to dstroy o body, such os.
Iiure .(
A8:& &:#$-,"45 1
We need the Body's location and angle. `%0> $8# ' I8!>&N?%2W8&"]:!%-M88/&4I8&"5*
E-8,2 , ' I8&"N?%2V7?-%45*
$3#<d,2/:!45*
Using the Vec2 position and float angle to
translate and rotate the rectangle
2/,7#-,2%4$8#N!C$8#N"5*
/82,2%46,5*
E:--4)OJ5*
#2/8.%4B5*
/%02d8&%4MhknhY5*
/%024BCBC;C<5*
$8$d,2/:!45*
@
This function removes a body from the
Box2D world.
A8:& .:--W8&"45 1
I8!>&N&%#2/8"W8&"4I8&"5*
@
Choptr 5. Physlcs Llbrorls
208
|n thls choptr`s cod downloods, lnd th sktch nomd box2d_xrcls." slng th
mthodology outllnd ln thls choptr, odd th ncssory cod to th moln ond Box tobs
to lmplmnt Box2L physlcs. 1h rsult should oppor os ln th scrnshot obov. B
mor crotlv ln how you rndr th boxs.
MO(.2&-( ?"0 MO(.2&-( ?"0
?"N S&O(9 b*O0\ F)G(2'- ?"N S&O(9 b*O0\ F)G(2'-
|n th xompl w just crotd, th W8! objcts oppor ot th mous locotlon ond oll
downwords du to Box2L`s doult grovlty orc. Whot l w wontd to lnstoll som lmmovobl
boundorls ln th Box2L world thot would block th poth o th W8! objcts [os ln th
lllustrotlon blowj?
Box2L moks thls osy or us by provldlng o mons to lock o body [ond ony ossoclotd
shopsj ln ploc. Just st th W8&"\%E objct`s typ to [nVncM.
W con odd thls otur to our Boxs xompl by wrltlng o W837&,/" closs ond hovlng och
boundory crot o lxd Box2L body.
W8&"\%E I& ' 7%; W8&"\%E45*
When BodyDef type = STATC, the Body is
locked in place.
I&N2"$% ' W8&"n"$%N[nVncM*
1h Notur o Cod [v005j
209
IJ&7:5# ?K<L G&55/16 E*J#8 "/''/16 E*(1-&)/#8
0-,## W837&,/" 1
A boundary is a simple rectangle with x, y,
width, and height.
E-8,2 !C"*
E-8,2 ;C<*
W8&" I*
W837&,/"4E-8,2 !aCE-8,2 "aC E-8,2 ;aC E-8,2 <a5 1
! ' !a*
" ' "a*
; ' ;a*
< ' <a*
Build the Box2D Body and Shape. W8&"\%E I& ' 7%; W8&"\%E45*
I&N$8#:2:87N#%24I8!>&N088/&]:!%-#n8+8/-&4!C"55*
Make it fixed by setting type to STATC! I&N2"$% ' W8&"n"$%N[nVncM*
I ' I8!>&N0/%,2%W8&"4I&5*
E-8,2 I8!>&+ ' I8!>&N#0,-,/]:!%-#n8+8/-&4;=>5*
E-8,2 I8!>&r ' I8!>&N#0,-,/]:!%-#n8+8/-&4<=>5*
]8-"?87[<,$% $# ' 7%; ]8-"?87[<,$%45*
We're just a box $#N#%2V#W8!4I8!>&+C I8!>&r5*
Using the createFixture() shortcut IN0/%,2%b:!23/%4$#C)5*
@
Since we know it can never move, we can
just draw it the old-fashioned way, using
our original variables. No need to query
Box2D.
A8:& &:#$-,"45 1
E:--4B5*
#2/8.%4B5*
/%02d8&%4MhknhY5*
/%024!C"C;C<5*
@
@
Choptr 5. Physlcs Llbrorls
2J0
?"W ! P:.I/ b*:;94./ ?"W ! P:.I/ b*:;94./
| you wont o lxd boundory thot ls o curvd suroc [os opposd to o polygonj, thls con b
ochlvd wlth th shop M<,:7[<,$%.
1h M<,:7[<,$% closs ls onothr shop llk ]8-"?87[<,$% or M:/0-%[<,$%, so to lnclud on
ln our systm, w ollow th som stps.
U'(Q #D \(+&;( 4 )*9/" U'(Q #D \(+&;( 4 )*9/"
The body does not need a position; the
EdgeShape will take care of that for us. t
also does not need a type, as it is STATC
by default.
W8&"\%E I& ' 7%; W8&"\%E45*
W8&" I8&" ' I8!>&N;8/-&N0/%,2%W8&"4I&5*
U'(Q 0D \(+&;( ',( U,4Q(" U'(Q 0D \(+&;( ',( U,4Q("
M<,:7[<,$% 0<,:7 ' 7%; M<,:7[<,$%45*
U'(Q =D P*;+&<:.( ',( U,4Q(" U'(Q =D P*;+&<:.( ',( U,4Q("
1h M<,:7[<,$% objct ls o srls o connctd vrtlcs. 1o crot th choln, w must lrst
spcly on orroy o vrtlcs [och os o `%0> objctj. |or xompl, l w wontd o strolght lln
rom th lt-hond sld o our wlndow to th rlght-hond sld, w would just nd on orroy o
two vrtlcs. [0,J50j ond [wldth,J50j. [Not thot l you wont to crot o loop whr th lrst
vrtx conncts to th lost vrtx ln o loop, you con us th M<,:7l88$ closs lnstod.j
1o crot th choln wlth th vrtlcs, th orroy ls thn possd lnto o unctlon colld
0/%,2%M<,:745.
`%0>KL A%/2:0%# ' 7%; `%0>K>L*
Adding a vertex on the right side of window A%/2:0%#KBL ' I8!>&N088/&]:!%-#n8+8/-&4BC)JB5*
Adding a vertex on the left side of window A%/2:0%#K)L ' I8!>&N088/&]:!%-#n8+8/-&4;:&2<C)JB5*
f you don't want to use the entire array, you
can specify a value less than length.
0<,:7N0/%,2%M<,:74A%/2:0%#C A%/2:0%#N-%7?2<5*
1h Notur o Cod [v005j
2JJ
U'(Q >D !''42, ',( U,4Q( '* ',( )*9/ 8&', 4 S&O':.(" U'(Q >D !''42, ',( U,4Q( '* ',( )*9/ 8&', 4 S&O':.("
A [<,$% ls not port o Box2L unlss lt ls ottochd to o body. Lvn l lt ls o lxd boundory
ond nvr movs, lt must stlll b ottochd. Just os wlth othr shops, o M<,:7[<,$% objct
con b glvn proprtls llk rstltutlon ond rlctlon wlth o b:!23/%.
Now, l w wont to lnclud o M<,:7[<,$% objct ln our sktch, w con ollow th som
strotgy os w dld wlth o lxd boundory. Lt`s wrlt o closs colld [3/E,0%.
b:!23/%\%E E& ' 7%; b:!23/%\%E45*
A fixture assigned to the ChainShape E&N#<,$% ' 0<,:7*
E&N&%7#:2" ' )*
E&NE/:02:87 ' BNH*
E&N/%#2:232:87 ' BNJ*
I8&"N0/%,2%b:!23/%4E&5*
Choptr 5. Physlcs Llbrorls
2J2
IJ&7:5# ?K=L ,"&/1O"&:# 4/'" '")## "&)-`0*-#- N#)'/0#8
Notlc how th obov closs lncluds on V//,"l:#2 to stor o srls o `%0> objcts. Lvn
though w ully lntnd to stor th coordlnots o th choln ln th choln shop ltsl, w or
chooslng th os o rdundoncy ond kplng our own llst o thos polnts os wll. Lotr,
whn w go to drow th [3/E,0% objct, w don`t hov to osk Box2L or th locotlons o th
choln shop`s vrtlcs.
0-,## [3/E,0% 1
V//,"l:#2P`%0>^ #3/E,0%*
[3/E,0%45 1
#3/E,0% ' 7%; V//,"l:#2P`%0>^45*
3 vertices in pixel coordinates #3/E,0%N,&&47%; `%0>4BC <%:?<2=>(JB55*
#3/E,0%N,&&47%; `%0>4;:&2<=>C <%:?<2=>(JB55*
#3/E,0%N,&&47%; `%0>4;:&2<C <%:?<2=>55*
M<,:7[<,$% 0<,:7 ' 7%; M<,:7[<,$%45*
Make an array of Vec2 for the ChainShape. `%0>KL A%/2:0%# ' 7%; `%0>K#3/E,0%N#:F%45L*
E8/ 4:72 : ' B* : P A%/2:0%#N-%7?2<* :((5 1
A%/2:0%#K:L ' I8!>&N088/&]:!%-#n8+8/-&4#3/E,0%N?%24:55*
@
Convert each vertex to Box2D World
coordinates.
Create the ChainShape with array of Vec2. 0<,:7N0/%,2%M<,:74A%/2:0%#C A%/2:0%#N-%7?2<5*
Attach the Shape to the Body. W8&"\%E I& ' 7%; W8&"\%E45*
W8&" I8&" ' I8!>&N;8/-&N0/%,2%W8&"4I&5*
I8&"N0/%,2%b:!23/%40<,:7C )5*
@
A8:& &:#$-,"45 1
#2/8.%+%:?<24)5*
#2/8.%4B5*
78b:--45*
Draw the ChainShape as a series of
vertices.
I%?:7[<,$%45*
E8/ 4`%0> Aq #3/E,0%5 1
A%/2%!4AN!CAN"5*
@
%7&[<,$%45*
@
@
1h Notur o Cod [v005j
2J3
Whot w nd ln #%23$45 ond &/,;45 or th [3/E,0% objct ls qult slmpl, glvn thot
Box2L toks cor o oll o th physlcs or us.
]W8!>\ I8!>&*
[3/E,0% #3/E,0%*
A8:& #%23$45 1
#:F%4JBBCHBB5*
I8!>& ' 7%; ]W8!>\42<:#5*
I8!>&N0/%,2%+8/-&45*
Make a Surface object. #3/E,0% ' 7%; [3/E,0%45*
@
A8:& &/,;45 1
I8!>&N#2%$45*
I,0.?/837&4>JJ5*
Draw the Surface. #3/E,0%N&:#$-,"45*
@
Rvlw how w lornd to drow o wov pottrn ln Choptr 3. Crot o M<,:7[<,$%
objct out o o sln wov. 1ry uslng Prlln nols [s pog J7j os wll.
sine ucte Perlin noise
MO(.2&-( ?"= MO(.2&-( ?"=
Choptr 5. Physlcs Llbrorls
2J4
?"#T P*EQ%(O S*.E- ?"#T P*EQ%(O S*.E-
Now thot w`v sn how osy lt ls to mok
slmpl gomtrlc orms ln Box2L, lt`s
lmogln thot you wont to hov o mor
complx orm, such os o llttl olln stlck
lgur.
1hr or two strotgls ln Box2L or
moklng orms thot or mor odvoncd thon o
boslc clrcl or squor. On ls to us o
]8-"?87[<,$% ln o dlrnt woy. |n our
prvlous xompls, w usd ]8-"?87[<,$%
to gnrot o rctongulor shop wlth th
#%2V#W8!45 unctlon.
1hls wos o good woy to stort bcous o th lnhrnt slmpllclty o worklng wlth rctongls.
Howvr, o ]8-"?87[<,$% objct con olso b gnrotd rom on orroy o vctors, whlch
ollows you to bulld o compltly custom shop os o srls o connctd vrtlcs. 1hls works
vry slmllorly to th M<,:7[<,$% closs.
IJ&7:5# ?K>L 9*5U6*1 8"&:#8
Iiure .
]8-"?87[<,$% $# ' 7%; ]8-"?87[<,$%45*
$#N#%2V#W8!4I8!>&+C I8!>&r5*
`%0>KL A%/2:0%# ' 7%; `%0>KDL* == V7 ,//," 8E D A%028/#
A%/2:0%#KBL ' I8!>&NA%028/]:!%-#n8+8/-&47%; `%0>46)JC >J55*
A%/2:0%#K)L ' I8!>&NA%028/]:!%-#n8+8/-&47%; `%0>4)JC B55*
A%/2:0%#K>L ' I8!>&NA%028/]:!%-#n8+8/-&47%; `%0>4>BC 6)J55*
A%/2:0%#KHL ' I8!>&NA%028/]:!%-#n8+8/-&47%; `%0>46)BC 6)B55*
Making a polygon from that array ]8-"?87[<,$% $# ' 7%; ]8-"?87[<,$%45*
$#N#%24A%/2:0%#C A%/2:0%#N-%7?2<5*
1h Notur o Cod [v005j
2J5
Whn bulldlng your own polygon ln Box2L, you must rmmbr two lmportont dtolls.
J. Y)-#) *+ N#)'/0#8T Y)-#) *+ N#)'/0#8T | you or thlnklng ln trms o plxls [os obovj th vrtlcs
should b dlnd ln countrclockwls ordr. [Whn thy or tronslotd to Box2L
World vctors, thy wlll octuolly b ln clockwls ordr slnc th vrtlcol oxls ls
llppd.j
2. ,*1N#J 8"&:#8 *15UT ,*1N#J 8"&:#8 *15UT A concov shop ls on whr th suroc curvs lnword.
Convx ls th opposlt [s lllustrotlon blowj. Not how ln o concov shop
vry lntrnol ongl must b J80 dgrs or lss. Box2L ls not copobl o
hondllng colllslons or concov shops. | you nd o concov shop, you wlll hov
to bulld on out o multlpl convx shops [mor obout thot ln o momntj.
Iiure .
Choptr 5. Physlcs Llbrorls
2J6
Now, whn lt coms tlm to dlsploy th shop ln Procsslng, w con no longr just us
/%0245 or %--:$#%45. 5lnc th shop ls bullt out o custom vrtlcs, w`ll wont to us
Procsslng`s I%?:7[<,$%45, %7&[<,$%45, ond A%/2%!45 unctlons. As w sow wlth th
M<,:7[<,$%, w could choos to stor th plxl locotlons o th vrtlcs ln our own
V//,"l:#2 or drowlng. Howvr, lt`s olso usul to s how w con osk Box2L to rport bock
to us th vrtx locotlons.
Iiure .;: A conccte shcpe ccn be drcun uith multiple contex shcpes.
A8:& &:#$-,"45 1
`%0> $8# ' I8!>&N?%2W8&"]:!%-M88/&4I8&"5*
E-8,2 , ' I8&"N?%2V7?-%45*
First we get the Fixture attached to the
Body...
b:!23/% E ' I8&"N?%2b:!23/%l:#245*
...then the Shape attached to the Fixture. ]8-"?87[<,$% $# ' 4]8-"?87[<,$%5 EN?%2[<,$%45*
/%02d8&%4MhknhY5*
$3#<d,2/:!45*
2/,7#-,2%4$8#N!C$8#N"5*
/82,2%46,5*
E:--4)OJ5*
#2/8.%4B5*
I%?:7[<,$%45*
E8/ 4:72 : ' B* : P $#N?%2`%/2%!M837245* :((5 1
`%0> A ' I8!>&NA%028/+8/-&n8]:!%-#4$#N?%2`%/2%!4:55*
A%/2%!4AN!CAN"5*
@
%7&[<,$%4MlU[h5*
$8$d,2/:!45*
@
We can loop through that array and convert
each vertex from Box2D space to pixels.
1h Notur o Cod [v005j
2J7
A polygon shop wlll gt us prtty or ln Box2L. Nvrthlss, th convx shop
rqulrmnt wlll svrly llmlt th rong o posslbllltls. 1h good nws ls thot w con
compltly llmlnot thls rstrlctlon by crotlng o slngl Box2L body out o multlpl shops!
Lt`s rturn to our llttl olln crotur ond slmplly th shop to b o thln rctongl wlth o
clrcl on top.
How con w bulld o slngl body wlth two shops? Lt`s lrst rvlw how w bullt o slngl
body wlth on shop.
5tep !. Det|ne the body.
5tep 2. Cteote the body.
Q&$A 73 E$;/.$ &+$ )+(A$6 Q&$A 73 E$;/.$ &+$ )+(A$6
Q&$A Z3 D&&(%+ &+$ )+(A$ &! &+$ "!8@6 Q&$A Z3 D&&(%+ &+$ )+(A$ &! &+$ "!8@6
5tep 5. l|no||ze the bodys moss.
Attochlng mor thon on shop to o body ls os slmpl os rpotlng stps 3 ond 4 ovr ond
ovr ogoln.
Q&$A 7(3 E$;/.$ )+(A$ 56 Q&$A 7(3 E$;/.$ )+(A$ 56
Q&$A Z(3 D&&(%+ )+(A$ 5 &! &+$ "!8@6 Q&$A Z(3 D&&(%+ )+(A$ 5 &! &+$ "!8@6
Q&$A 7"3 E$;/.$ )+(A$ X6 Q&$A 7"3 E$;/.$ )+(A$ X6
Q&$A Z"3 D&&(%+ )+(A$ X &! &+$ "!8@6 Q&$A Z"3 D&&(%+ )+(A$ X &! &+$ "!8@6
tc. tc. tc.
Lt`s s whot thls would look llk wlth octuol Box2L cod.
slng th ]8-"?87[<,$% closs, crot your own polygon dslgn [rmmbr, lt must
b concovj. 5om posslbllltls blow.
MO(.2&-( ?"> MO(.2&-( ?">
Making the body W8&"\%E I& ' 7%; W8&"\%E45*
I&N2"$% ' W8&"n"$%N\fkVdcM*
I&N$8#:2:87N#%24I8!>&N088/&]:!%-#n8+8/-&40%72%/55*
I8&" ' I8!>&N0/%,2%W8&"4I&5*
Choptr 5. Physlcs Llbrorls
2J8
1h obov looks prtty good, but sodly, l w run lt, w`ll gt th ollowlng rsult.
Whn you ottoch o shop to o body, by doult, th cntr o th shop wlll b locotd ot th
cntr o th body. But ln our cos, l w tok th cntr o th rctongl to b th cntr o
th body, w wont th cntr o th clrcl to b ost olong th y-oxls rom th body`s cntr.
Making shape 1 (the rectangle) ]8-"?87[<,$% $# ' 7%; ]8-"?87[<,$%45*
E-8,2 I8!>&+ ' I8!>&N#0,-,/]:!%-#n8+8/-&4;=>5*
E-8,2 I8!>&r ' I8!>&N#0,-,/]:!%-#n8+8/-&4<=>5*
#&N#%2V#W8!4I8!>&+C I8!>&r5*
Making shape 2 (the circle) M:/0-%[<,$% 0# ' 7%; M:/0-%[<,$%45*
0#N9a/,&:3# ' I8!>&N#0,-,/]:!%-#n8+8/-&4/5*
Attach both shapes with a fixture. I8&"N0/%,2%b:!23/%4$#C)NB5*
I8&"N0/%,2%b:!23/%40#C )NB5*
Iiure .8
1h Notur o Cod [v005j
2J9
1hls ls ochlvd by uslng th locol posltlon o o shop, occssd vlo o `%0> vorlobl colld
9a$.
1hn, whn w go to drow th body, w us both /%0245 ond %--:$#%45 wlth th clrcl
ost th som woy.
Iiure .p
Our offset in pixels `%0> 8EE#%2 ' 7%; `%0>4BC6<=>5*
Converting the vector to Box2D world 8EE#%2 ' I8!>&NA%028/]:!%-#n8+8/-&48EE#%25*
Setting the local position of the circle 0:/0-%N9a$N#%248EE#%2N!C8EE#%2N"5*
Choptr 5. Physlcs Llbrorls
220
IJ&7:5# ?K?L P(5'/:5# 8"&:#8 *1 *1# E*-U
|lnlshlng o thls sctlon, | wont to strss th ollowlng. th stu you drow ln your Procsslng
wlndow dosn`t moglcolly xprlnc physlcs slmply bcous w crotd som Box2L bodls
ond shops. 1hs xompls work bcous w vry corully motchd how w drow our
lmnts wlth how w dlnd th bodls ond shops w put lnto th Box2L world. | you
occldntolly drow your shop dlrntly, you won`t gt on rror, not rom Procsslng or rom
Box2L. Howvr, your sktch wlll look odd ond th physlcs won`t work corrctly. |or xompl,
whot l w hod wrlttn.
whn w crotd th 5hop, but.
whn lt com tlm to dlsploy th shop?
A8:& &:#$-,"45 1
`%0> $8# ' I8!>&N?%2W8&"]:!%-M88/&4I8&"5*
E-8,2 , ' I8&"N?%2V7?-%45*
/%02d8&%4MhknhY5*
$3#<d,2/:!45*
2/,7#-,2%4$8#N!C$8#N"5*
/82,2%46,5*
E:--4)OJ5*
#2/8.%4B5*
First the rectangle at (0,0) /%024BCBC;C<5*
Then the ellipse offset at (0,-h/2) %--:$#%4BC6<=>C/Q>C/Q>5*
$8$d,2/:!45*
@
`%0> 8EE#%2 ' 7%; `%0>4BC6<=>5*
%--:$#%4BC<=>C/Q>C/Q>5*
1h Notur o Cod [v005j
22J
1h rsults would look llk th lmog obov, whr clorly, th colllslons or not
unctlonlng os xpctd. 1hls ls not bcous th physlcs ls brokn, lt`s bcous w dld not
communlcot proprly wlth Box2L, lthr whn w put stu ln th moglc world or qurld
th world or locotlons.
Mok your own llttl olln blng uslng multlpl shops ottochd to o slngl body. 1ry
uslng mor thon on polygon to mok o concov shop. Rmmbr, you orn`t
llmltd to uslng th shop drowlng unctlons ln Procsslng, you con us lmogs,
colors, odd holr wlth llns, tc. 1hlnk o th Box2L shops only os skltons or your
crotlv ond ontostlcol dslgn!
MO(.2&-( ?"? MO(.2&-( ?"?
?"## S((%&;< !''42,(9db*O0\ g*&;'- ?"## S((%&;< !''42,(9db*O0\ g*&;'-
Box2L jolnts ollow you to connct on
body to onothr, nobllng mor odvoncd
slmulotlons o swlnglng pndulums, lostlc
brldgs, squlshy choroctrs, whls
splnnlng on on oxl, tc. 1hr or mony
dlrnt klnds o Box2L jolnts. |n thls
choptr w`r golng to look ot thr.
dlstonc jolnts, rvolut jolnts, ond
mous" jolnts.
Lt`s bgln wlth o dlstonc jolnt, o jolnt thot
conncts two bodls wlth o lxd lngth.
1h jolnt ls ottochd to och body ot o
spclld onchor polnt [o polnt rlotlv to
th body`s cntrj. |or ony Box2L jolnt, w
nd to ollow ths stps. 1hls, o cours,
ls slmllor to th mthodology w usd to
bulld bodls ond shops, wlth som qulrks.
Q&$A 56 [(J$ ):1$ @!: +(0$ &>! "!8/$) 1$(8@ &! 2!6 Q&$A 56 [(J$ ):1$ @!: +(0$ &>! "!8/$) 1$(8@ &! 2!6
Q&$A X6 E$;/.$ &+$ #!/.&6 Q&$A X6 E$;/.$ &+$ #!/.&6
Q&$A 76 M!.;/2:1$ &+$ #!/.&\) A1!A$1&/$) OF+(& (1$ &+$ "!8/$)G F+$1$ (1$ &+$ (.%+!1)G Q&$A 76 M!.;/2:1$ &+$ #!/.&\) A1!A$1&/$) OF+(& (1$ &+$ "!8/$)G F+$1$ (1$ &+$ (.%+!1)G
F+(& /) /&) 1$)& '$.2&+G ]) /& $'()&/% !1 1/2/8GP F+(& /) /&) 1$)& '$.2&+G ]) /& $'()&/% !1 1/2/8GP
Q&$A Z6 M1$(&$ &+$ #!/.&6 Q&$A Z6 M1$(&$ &+$ #!/.&6
Lt`s ossum w hov two ],/2:0-% objcts thot och stor o rrnc to o Box2L W8&"
objct. W`ll coll thm portlcls $) ond $>.
Iiure .:o
Choptr 5. Physlcs Llbrorls
222
OK, onto 5tp 2. Lt`s dln th jolnt.
Losy, rlght? Now lt`s tlm to conlgur th jolnt. |lrst w tll th jolnt whlch two bodls lt
conncts.
1hn w st up o rst lngth. Rmmbr, l our rst lngth ls ln plxls, w nd to convrt lt!
A dlstonc jolnt olso lncluds two optlonol sttlngs thot con mok th jolnt sot, llk o sprlng
connctlon. E/%g3%70"rF ond &,9$:7?Y,2:8.
|lnolly, w crot th jolnt.
Box2L won`t kp trock o whot klnd o jolnt w or moklng, so w hov to cost lt os o
\:#2,70%v8:72 upon crotlon.
W con crot Box2L jolnts onywhr ln our Procsslng sktch. Hr`s on xompl o how w
mlght wrlt o closs to dscrlb two Box2L bodls connctd wlth o slngl jolnt.
],/2:0-% $) ' 7%; ],/2:0-%45*
],/2:0-% $> ' 7%; ],/2:0-%45*
\:#2,70%v8:72\%E &o& ' 7%; \:#2,70%v8:72\%E45*
&o&NI8&"V ' $)NI8&"*
&o&NI8&"W ' $>NI8&"*
&o&N-%7?2< ' I8!>&N#0,-,/]:!%-#n8+8/-&4)B5*
Measured in Hz, like the frequency of
harmonic oscillation; try values between 1
and 5.
&o&NE/%g3%70"rF ' aaa*
Dampens the spring; typically a number
between 0 and 1.
&o&N&,9$:7?Y,2:8 ' aaa*
\:#2,70%v8:72 &o ' 4\:#2,70%v8:725 I8!>&N;8/-&N0/%,2%v8:724&o&5*
1h Notur o Cod [v005j
223
IJ&7:5# ?K@L ./8'&10#a*/1'
0-,## ],:/ 1
Two objects that each have a Box2D body ],/2:0-% $)*
],/2:0-% $>*
Arbitrary rest length E-8,2 -%7 ' H>*
],:/4E-8,2 !C E-8,2 "5 1
Problems can result if the bodies are
initialized at the same location. $) ' 7%; ],/2:0-%4!C"5*
$> ' 7%; ],/2:0-%4!(/,7&8946)C)5C"(/,7&8946)C)55*
Making the joint! \:#2,70%v8:72\%E &o& ' 7%; \:#2,70%v8:72\%E45*
&o&NI8&"V ' $)NI8&"*
&o&NI8&"W ' $>NI8&"*
&o&N-%7?2< ' I8!>&N#0,-,/]:!%-#n8+8/-&4-%75*
&o&NE/%g3%70"rF ' B* == n/" , A,-3% -%## 2<,7 J
&o&N&,9$:7?Y,2:8 ' B* == Y,7?%# I%2;%%7 B ,7& )
\:#2,70%v8:72 &o ' 4\:#2,70%v8:725 I8!>&N;8/-&N0/%,2%v8:724&o&5*
@
A8:& &:#$-,"45 1
`%0> $8#) ' I8!>&N?%2W8&"]:!%-M88/&4$)NI8&"5*
`%0> $8#> ' I8!>&N?%2W8&"]:!%-M88/&4$>NI8&"5*
#2/8.%4B5*
-:7%4$8#)N!C$8#)N"C$8#>N!C$8#>N"5*
$)N&:#$-,"45*
$>N&:#$-,"45*
@
@
Make the joint. Note that we aren't storing a
reference to the joint anywhere! We might
need to someday, but for now it's OK.
Choptr 5. Physlcs Llbrorls
224
Anothr jolnt you con crot ln Box2L ls o
tevo|ute o|nt. A rvolut jolnt conncts two
Box2L bodls ot o common onchor polnt,
whlch con olso b rrrd to os o hlng."
1h jolnt hos on ongl" thot dscrlbs th
rlotlv rototlon o och body. 1o us o
rvolut jolnt, w ollow th som stps w
dld wlth th dlstonc jolnt.
Crot o slmulotlon o o brldg by uslng dlstonc jolnts to connct o squnc o
clrcls [or rctonglsj os lllustrotd to th rlght. Asslgn o dnslty o zro to lock th
ndpolnts ln ploc. Lxprlmnt wlth dlrnt volus to mok th brldg mor or lss
sprlngy." |t should olso b notd thot th jolnts thmslvs hov no physlcol gomtry,
so ln ordr or your brldg not to hov hols, spoclng btwn th nods wlll b
lmportont.
MO(.2&-( ?"K MO(.2&-( ?"K
Iiure .::
U'(Q #D ]43( -:.( /*: ,4I( '8* )*9&(- .(49/ '* <*" U'(Q #D ]43( -:.( /*: ,4I( '8* )*9&(- .(49/ '* <*"
Lt`s ossum w hov two W8! objcts, och o whlch stors o rrnc to o Box2L body.
W8! I8!) ' 7%; W8!45*
W8! I8!> ' 7%; W8!45*
1h Notur o Cod [v005j
225
U'(Q 0D \(+&;( ',( G*&;'" U'(Q 0D \(+&;( ',( G*&;'"
Now w wont o Y%A8-32%v8:72\%E objct.
Y%A8-32%v8:72\%E /o& ' 7%; Y%A8-32%v8:72\%E45*
U'(Q =D P*;+&<:.( ',( G*&;'H- Q.*Q(.'&(-" U'(Q =D P*;+&<:.( ',( G*&;'H- Q.*Q(.'&(-"
1h most lmportont proprtls o o rvolut jolnt or th two bodls lt conncts os wll os
thlr mutuol onchor polnt [l.. whr thy or connctdj. 1hy or st wlth th unctlon
:7:2:,-:F%45.
Notlc how th lrst two orgumnts spcly th bodls ond th scond polnt spclls th
onchor, whlch ln thls cos ls locotd ot th cntr o th lrst body.
An xcltlng otur o o Y%A8-32%v8:72 objct ls thot you con motorlz lt so lt splns
outonomously. |or xompl.
1h motor con b nobld ond dlsobld whll th progrom ls runnlng.
|lnolly, th oblllty or o rvolut jolnt to spln con b constrolnd btwn two ongls. [By
doult, lt con rotot o ull 360 dgrs, or n+Ua]c rodlons.j
/o&N:7:2:,-:F%4I8!)NI8&"C I8!>NI8&"C I8!)NI8&"N?%2+8/-&M%72%/455*
Turn on the motor. /o&N%7,I-%d828/ ' 2/3%*
How fast is the motor? /o&N9828/[$%%& ' ]cQ>*
How powerful is the motor? /o&N9,!d828/n8/g3% ' )BBBNB*
/o&N%7,I-%l:9:2 ' 2/3%*
/o&N-8;%/V7?-% ' 6]c=X*
/o&N3$$%/V7?-% ' ]c=X*
U'(Q >D P.(4'( ',( G*&;' U'(Q >D P.(4'( ',( G*&;'
Lt`s tok o look ot oll o ths stps togthr ln o closs colld +:7&9:--, whlch conncts
two boxs wlth o rvolut jolnt. |n thls cos, I8!) hos o dnslty o zro, so only I8!> splns
oround o lxd polnt.
Y%A8-32%v8:72 o8:72 ' 4Y%A8-32%v8:725 I8!>&N;8/-&N0/%,2%v8:724/o&5*
Choptr 5. Physlcs Llbrorls
226
IJ&7:5# ?KAL O:/11/16 M/1-7/55
0-,## +:7&9:-- 1
Our "Windmill is two boxes and one joint. Y%A8-32%v8:72 o8:72*
W8! I8!)*
W8! I8!>*
+:7&9:--4E-8,2 !C E-8,2 "5 1
n this example, the Box class expects a
boolean argument that will be used to
determine if the Box is fixed or not. See
website for the Box class code.
I8!) ' 7%; W8!4!C"C)>BC)BCE,-#%5*
I8!> ' 7%; W8!4!C"C)BCDBC2/3%5*
Y%A8-32%v8:72\%E /o& ' 7%; Y%A8-32%v8:72\%E45*
/o&N:7:2:,-:F%4I8!)NI8&"C I8!>NI8&"C I8!)NI8&"N?%2+8/-&M%72%/455*
The joint connects two bodies and is
anchored at the center of the first body.
A motor! /o&N9828/[$%%& ' ]cQ>*
/o&N9,!d828/n8/g3% ' )BBBNB*
/o&N%7,I-%d828/ ' 2/3%*
o8:72 ' 4Y%A8-32%v8:725 I8!>&N;8/-&N0/%,2%v8:724/o&5*
@ Create the Joint.
Turning the motor on or off A8:& 28??-%d828/45 1
I88-%,7 9828/#2,23# ' o8:72N:#d828/h7,I-%&45*
o8:72N%7,I-%d828/4S9828/#2,23#5*
@
1h Notur o Cod [v005j
227
1h lost jolnt w`ll look ot ls o mous jolnt. A mous jolnt ls typlcolly usd or movlng o body
wlth th mous. Howvr, lt con olso b usd to drog on objct oround th scrn
occordlng to som orbltrory x ond y. 1h jolnt unctlons by pulllng th body towords o
torgt" posltlon.
Bor w look ot th d83#%v8:72 objct ltsl, lt`s osk ourslvs why w vn nd lt ln
th lrst ploc. | you look ot th Box2L documntotlon, thr ls o unctlon colld
#%2n/,7#E8/945 thot spcllcolly sts th posltlon o th body`s orlgln ond rototlon
[rodlonsj." | o body hos o posltlon, con`t w just osslgn th body`s posltlon to th mous?
Whll thls wlll ln oct mov th body, lt wlll olso hov th unortunot rsult o broklng th
physlcs. Lt`s lmogln you bullt o tlportotlon mochln thot ollows you to tlport rom
your bdroom to your kltchn [good or lot-nlght snocklngj. Now, go ohod ond rwrlt
Nwton`s lows o motlon to occount or th posslblllty o tlportotlon. Not so osy, rlght?
Box2L hos th som problm. | you monuolly osslgn th locotlon o on body, lt`s llk soylng
tlport thot body" ond Box2L no longr knows how to comput th physlcs proprly.
A8:& &:#$-,"45 1
I8!)N&:#$-,"45*
I8!>N&:#$-,"45*
@
@
s o rvolut jolnt or th whls o o
cor. s motors so thot th cor drlvs
outonomously. 1ry uslng o choln shop
or th rood`s suroc.
MO(.2&-( ?"L MO(.2&-( ?"L
`%0> 983#% ' I8!>&N#0/%%7n8+8/-&4!C"5*
I8&"N#%2n/,7#E8/94983#%CB5*
Choptr 5. Physlcs Llbrorls
228
Howvr, Box2L dos ollow you to tl o rop to yoursl ond gt o rlnd o yours to stond ln
th kltchn ond drog you thr. 1hls ls whot th d83#%v8:72 dos. |t`s llk o strlng you ottoch
to o body ond pull towords o torgt.
Lt`s look ot moklng thls jolnt, ossumlng w hov o W8! objct colld I8!. 1hls cod wlll look
ldntlcol to our dlstonc jolnt wlth on smoll dlrnc.
5o, whot`s thls lln o cod oll obout?
Wll, os w`v stotd, o jolnt ls o connctlon btwn two bodls. Wlth o mous jolnt, w`r
soylng thot th scond body ls, wll, th ground. Hmm. Whot th hck ls th gtound ln Box2L?
On woy to lmogln lt ls to thlnk o th scrn os th ground. Whot w`r dolng ls moklng o
jolnt thot conncts o rctongl drown on th wlndow wlth th Procsslng wlndow ltsl. And
th polnt ln th wlndow to whlch th connctlon ls tld ls o movlng torgt.
Onc w hov o mous jolnt, w`ll wont to updot th torgt locotlon contlnuolly whll th
sktch ls runnlng.
1o mok thls work ln on octuol Procsslng sktch, w`ll wont to hov th ollowlng.
J. T!K %'()) T!K %'())An objct thot rrncs o Box2L body.
2. QA1/.2 %'()) QA1/.2 %'())An objct thot monogs th mous jolnt thot drogs th W8! objct
oround.
Just like before, define the Joint. d83#%v8:72\%E 9& ' 7%; d83#%v8:72\%E45*
Whoa, this is new! 51-6813h " 68I>1-G$/r)84#1l813*+,
Attach the Box body. 9&NI8&"W ' I8!NI8&"*
Set properties. 9&N9,!b8/0% ' JBBBNB*
9&NE/%g3%70"rF ' JNB*
9&N&,9$:7?Y,2:8 ' BNp*
Create the joint. d83#%v8:72 983#%v8:72 ' 4d83#%v8:725
I8!>&N;8/-&N0/%,2%v8:7249&5*N
51-6813h " 68I>1-G$/r)84#1l813*+,
`%0> 983#%+8/-& ' I8!>&N088/&]:!%-#n8+8/-&4983#%eC983#%f5*
983#%v8:72N#%2n,/?%24983#%+8/-&5*
1h Notur o Cod [v005j
229
3. [(/. &(" [(/. &("Whnvr 983#%]/%##%&45 ls colld, th mous jolnt ls crotd,
whnvr 983#%Y%-%,#%&45 ls colld, th mous jolnt ls dstroyd. 1hls ollows us
to lntroct wlth o body only whn th mous ls prssd.
Lt`s tok o look ot th moln tob. You con lnd th rst o th cod or th W8! ond [$/:7?
closss vlo th book wbslt.
IJ&7:5# ?KBL P*(8#a*/1' -#7*18')&'/*1
]W8!>\ I8!>&*
One Box W8! I8!*
Object to manage MouseJoint [$/:7? #$/:7?*
A8:& #%23$45 1
#:F%4DBBCHBB5*
I8!>& ' 7%; ]W8!>\42<:#5*
I8!>&N0/%,2%+8/-&45*
I8! ' 7%; W8!4;:&2<=>C<%:?<2=>5*
The MouseJoint is really null until we click
the mouse.
#$/:7? ' 7%; [$/:7?45*
@
A8:& 983#%]/%##%&45 1
Was the mouse clicked inside the Box? :E 4I8!N0872,:7#4983#%eC 983#%f55 1
f so, attach the MouseJoint. #$/:7?NI:7&4983#%eC983#%fCI8!5*
@
@
A8:& 983#%Y%-%,#%&45 1
Choptr 5. Physlcs Llbrorls
230
|t`s worth notlng thot whll th tchnlqu or drogglng on objct oround uslng o d83#%v8:72 ls
usul, Box2L olso ollows o body to hov o tckhdVncM typ.
Klnmotlc bodls con b controlld by th
usr by sttlng thlr vloclty dlrctly. |or
xompl, lt`s soy you wont on objct to
ollow o torgt [llk your mousj. You could
crot o vctor thot polnts rom o body`s
locotlon to o torgt.
When the mouse is released, we're done
with the MouseJoint.
#$/:7?N&%#2/8"45*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
I8!>&N#2%$45*
We must always update the MouseJoint's
target.
#$/:7?N3$&,2%4983#%eC983#%f5*
I8!N&:#$-,"45*
#$/:7?N&:#$-,"45*
@
s o mous jolnt to mov o Box2L body oround th scrn occordlng to on olgorlthm
or lnput othr thon th mous. |or xompl, osslgn lt o locotlon occordlng to Prlln
nols or ky prsss. Or bulld your own controllr uslng on Ardulno
[http.//www.ordulno.cc/j.
MO(.2&-( ?"N MO(.2&-( ?"N
W8&"\%E I& ' 7%; W8&"\%E45*
Setting the body type to Kinematic I&N2"$% ' W8&"n"$%NtckhdVncM*
Iiure .:z
`%0> $8# ' I8&"N?%2+8/-&M%72%/45*
`%0> 2,/?%2 ' I8!>&N088/&]:!%-#n8+8/-&4983#%eC983#%f5*
A vector pointing from the body position to
the Mouse
`%0> A ' 2,/?%2N#3I4$8#5*
1h Notur o Cod [v005j
23J
Onc you hov thot vctor, you could osslgn lt to th body`s vloclty so thot lt movs to th
torgt.
You con olso do th som wlth ongulor vloclty [or lov lt olon ond ollow th physlcs to
tok ovrj.
|t ls lmportont to not thot klnmotlc bodls do not collld wlth othr klnmotlc or stotlc
bodls. |n ths coss, th mous jolnt strotgy ls prrobl.
Assigning a body's velocity directly,
overriding physics!
I8&"N#%2l:7%,/`%-80:2"4A5*
Rdo Lxrcls 5.8, but us o klnmotlc body lnstod.
MO(.2&-( ?"W MO(.2&-( ?"W
?"#0 b.&;<&;< C' !%% b423 f*E( '* S*.2(- ?"#0 b.&;<&;< C' !%% b423 f*E( '* S*.2(-
|n Choptr 2, w spnt o lot o tlm thlnklng obout bulldlng nvlronmnts wlth multlpl
orcs. An objct mlght rspond to grovltotlonol ottroctlon, wlnd, olr rslstonc, tc. Clorly
thr or orcs ot work ln Box2L os w wotch rctongls ond clrcls spln ond ly oround
th scrn. But so or, w`v only hod th oblllty to monlpulot o slngl globol
orcgrovlty.
| w wont to us ony o our Choptr 2 tchnlqus wlth Box2L, w nd look no urthr thon
our trusty ,$$-"b8/0%45 unctlon. |n our d8A%/ closs w wrot o unctlon colld
,$$-"b8/0%45, whlch rclvd o vctor, dlvldd lt by moss, ond occumulotd lt lnto th
movr`s occlrotlon. Wlth Box2L, th som unctlon xlsts, but w don`t nd to wrlt lt
ourslvs. |nstod, w con coll th Box2L body`s ,$$-"b8/0%45 unctlon!
I8!>& ' 7%; ]W8!>\42<:#5*
I8!>&N0/%,2%+8/-&45*
Setting the global gravity force I8!>&N#%2Z/,A:2"4BC 6>B5*
0-,## W8! 1
W8&" I8&"*
A8:& ,$$-"b8/0%4`%0> E8/0%5 1
`%0> $8# ' I8&"N?%2+8/-&M%72%/45*
Calling the Body's applyForce() function I8&"N,$$-"b8/0%4E8/0%C $8#5*
@
@
Choptr 5. Physlcs Llbrorls
232
Hr w or rclvlng o orc vctor ond posslng lt olong to th Box2L W8&" objct. 1h ky
dlrnc ls thot Box2L ls o mor sophlstlcotd ngln thon our xompls rom Choptr 2.
Our orllr orcs xompls ossumd thot th orc wos olwoys opplld ot th movr`s cntr.
Hr w gt to spcly xoctly whr on th body th orc ls opplld. |n th obov cod,
w`r just opplylng lt to th cntr by osklng th body or lts cntr, but thls could b
odjustd.
Lt`s soy w wontd to us o grovltotlonol ottroctlon orc. Rmmbr th cod w wrot bock
ln Choptr 2 ln our V22/,028/ closs?
W con rwrlt th xoct som unctlon uslng `%0> lnstod ond us lt ln o Box2L xompl.
Not how or our orc colculotlon w con stoy compltly wlthln th Box2L coordlnot
systm ond nvr thlnk obout plxls.
]`%028/ ,22/,024d8A%/ 95 1
]`%028/ E8/0% ' ]`%028/N#3I4-80,2:87C9N-80,2:875*
E-8,2 &:#2,70% ' E8/0%N9,?45*
&:#2,70% ' 087#2/,:74&:#2,70%CJNBC>JNB5*
E8/0%N78/9,-:F%45*
E-8,2 #2/%7?2< ' 4? Q 9,## Q 9N9,##5 = 4&:#2,70% Q &:#2,70%5*
E8/0%N93-24#2/%7?2<5*
/%23/7 E8/0%*
@
`%0> ,22/,024d8A%/ 95 1
We have to ask Box2D for the locations first! `%0> $8# ' I8&"N?%2+8/-&M%72%/45*
`%0> 98A%/]8# ' 9NI8&"N?%2+8/-&M%72%/45*
`%0> E8/0% ' $8#N#3I498A%/]8#5*
E-8,2 &:#2,70% ' E8/0%N-%7?2<45*
&:#2,70% ' 087#2/,:74&:#2,70%C)CJ5*
E8/0%N78/9,-:F%45*
E-8,2 #2/%7?2< ' 4Z Q ) Q 9NI8&"N9a9,##5 = 4&:#2,70% Q &:#2,70%5*
Remember, it's mulLocal() for Vec2. E8/0%N93-l80,-4#2/%7?2<5*
/%23/7 E8/0%*
@
1h Notur o Cod [v005j
233
1ok ony xompl you mod prvlously uslng o orc colculotlon ond brlng thot orc
colculotlon lnto Box2L.
MO(.2&-( ?"#T MO(.2&-( ?"#T
?"#= P*%%&-&*; MI(;'- ?"#= P*%%&-&*; MI(;'-
Now w`v sn o survy o whot con b don wlth Box2L. 5lnc thls book ls not colld
1h Notur o Box2L," lt`s not my lntntlon to covr vry slngl posslbl otur o th
Box2L ngln. But hopully by looklng ot th boslcs o bulldlng bodls, shops, ond jolnts,
whn lt coms tlm to us on ospct o Box2L thot w hovn`t covrd, th skllls w`v
golnd hr wlll mok thot procss consldrobly lss polnul. 1hr ls on mor otur o
Box2L, howvr, thot | do thlnk ls worth covrlng.
Lt`s osk o qustlon you`v llkly bn wondrlng obout.
hot |t l wont someth|ng to hoppen when two Box2D bod|es co|||de? l meon, dont get me
wtonglm tht|||ed thot Box2D |s hond||ng o|| ot the co|||s|ons tot me. But |t |t to|es cote ot
evetyth|ng tot me, how om l supposed to |now when th|ngs ote hoppen|ng?
Your lrst thoughts whn consldrlng on vnt durlng whlch two objcts collld mlght b os
ollows. Wll, l | know oll th bodls ln th systm, ond | know whr thy or oll locotd,
thn | con just stort comporlng th locotlons, s whlch ons or lntrsctlng, ond
dtrmln thot thy`v collldd. 1hot`s o nlc thought, but hllo??!? 1h whol polnt o uslng
Box2L ls thot Box2L wlll tok cor o thot or us. | w or golng to do th gomtry to tst
or lntrsctlon ourslvs, thn oll w`r dolng ls r-lmplmntlng Box2L.
O cours, Box2L hos thought o thls problm bor. |t`s o prtty common on. Atr oll, l
you lntnd to mok o bojllllon dollors slllng som gom colld Angry Blrds, you bttr wll
mok somthlng hoppn whn on lll-tmprd plgon smoshs lnto o cordboord box.
Box2L olrts you to momnts o colllslon wlth somthlng colld on lntroc." |t`s worth
lornlng obout lntrocs, on odvoncd otur o objct-orlntd progrommlng. You con
Choptr 5. Physlcs Llbrorls
234
tok o look ot th Jovo |ntroc 1utorlol [http.//downlood.orocl.com/jovos/tutorlol/jovo/
concpts/lntroc.htmlj os wll os th JBox2L M872,02l:#2%7%/ closs. [| hov olso lncludd
on xompl on th wbslt thot dmonstrots uslng th lntroc dlrctly.j
| you or uslng PBox2L, os w or hr, you don`t nd to lmplmnt your own lntroc.
Ltctlng colllslon vnts ls don through o collbock unctlon. Much llk 983#%]/%##%&45 ls
trlggrd whn th mous ls prssd, I%?:7M872,0245 ls trlggrd whn two shops collld.
Bor th obov wlll work, you must lrst lt PBox2L know you lntnd to llstn or colllslons.
[1hls ollows th llbrory to rduc ovrhod by doult, lt won`t bothr llstnlng l lt dosn`t
hov to.j
1hr or our colllslon vnt collbocks.
J. I%?:7M872,0245 1rlggrd whnvr two shops lrst com lnto contoct wlth och
othr.
2. %7&M872,0245 1rlggrd ovr ond ovr ogoln os long os shops contlnu to b ln
contoct.
3. $/%[8-A%45 1rlggrd bor Box2L solvs th outcom o th colllslon, l..
bor I%?:7M872,0245. |t con b usd to dlsobl o colllslon l ncssory.
4. $8#2[8-A%45 1rlggrd otr th outcom o th colllslon ls solvd. |t ollows you
to gothr lnormotlon obout thot solutlon" [known os on lmpuls"j.
1h dtolls bhlnd $/%[8-A%45 ond $8#2[8-A%45 or byond th scop o thls book,
howvr, w or golng to tok o clos look ot I%?:7M872,0245, whlch wlll covr th mojorlty
o convntlonol coss ln whlch you wont to trlggr on octlon whn o colllslon occurs.
%7&M872,0245 works ldntlcolly to I%?:7M872,0245, th only dlrnc blng thot lt occurs
th momnt bodls sporot.
The mousePressed event with which we are
comfortable.
A8:& 983#%]/%##%&45 1
$/:72-74Tn<% 983#% ;,# $/%##%&ST5*
@
What our "beginContact" event looks like. A8:& I%?:7M872,024M872,02 0$5 1
$/:72-74T[89%2<:7? 08--:&%& :7 2<% W8!>\ +8/-&ST5*
@
A8:& #%23$45 1
I8!>& ' 7%; ]W8!>\42<:#5*
I8!>&N0/%,2%+8/-&45*
Add this line if you want to listen for
collisions.
I8!>&N-:#2%7b8/M8--:#:87#45*
@
1h Notur o Cod [v005j
235
I%?:7M872,0245 ls wrlttn os ollows.
Notlc thot th unctlon obov lncluds on orgumnt o typ M872,02. A M872,02 objct
lncluds oll th doto ossoclotd wlth o colllslonth gomtry ond th orcs. Lt`s soy w
hov o Procsslng sktch wlth ],/2:0-% objcts thot stor o rrnc to o Box2L body.
Hr ls th procss w or golng to ollow.
A8:& I%?:7M872,024M872,02 0$5 1
@
U'(Q #D P*;'42'` 2*:%9 /*: '(%% E( 8,4' '8* ',&;<- 2*%%&9(97 U'(Q #D P*;'42'` 2*:%9 /*: '(%% E( 8,4' '8* ',&;<- 2*%%&9(97
Now, whot hos collldd hr? |s lt th bodls? 1h shops? 1h lxturs? Box2L dtcts
colllslons btwn shops, otr oll, ths or th ntltls thot hov gomtry. Howvr,
bcous shops or ottochd to bodls wlth lxturs, whot w rolly wont to osk Box2L ls.
Could you tll m whlch two lxturs collldd?"
The contact stores the fixtures as A and B. b:!23/% E) ' 0$N?%2b:!23/%V45*
b:!23/% E> ' 0$N?%2b:!23/%W45*
U'(Q 0D S&O':.(-` 2*:%9 /*: '(%% E( 8,&2, )*9/ /*: 4.( 4''42,(9 '*7 U'(Q 0D S&O':.(-` 2*:%9 /*: '(%% E( 8,&2, )*9/ /*: 4.( 4''42,(9 '*7
getBody() gives us the body to which the
Fixture is attached.
W8&" I) ' E)N?%2W8&"45*
W8&" I> ' E>N?%2W8&"45*
U'(Q =D b*9&(-` 2*:%9 /*: '(%% E( 8,&2, 54.'&2%(- /*: 4.( 4--*2&4'(9 U'(Q =D b*9&(-` 2*:%9 /*: '(%% E( 8,&2, 54.'&2%(- /*: 4.( 4--*2&4'(9
8&',7 8&',7
OK, thls ls th hordr port. Atr oll, Box2L dosn`t know onythlng obout our cod. 5ur, lt ls
dolng oll sorts o stu to kp trock o th rlotlonshlps btwn shops ond bodls ond
jolnts, but lt`s up to us to monog our own objcts ond thlr ossoclotlons wlth Box2L
lmnts. Lucklly or us, Box2L provlds o unctlon thot ollows us to ottoch our Procsslng
objct [o ],/2:0-%j to o Box2L body vlo th #%2u#%/\,2,45 ond ?%2u#%/\,2,45 mthods.
Lt`s tok o look ot th constructor ln our ],/2:0-% closs whr th body ls mod. W or
xpondlng our body-moklng procdur by on lln o cod, notd blow.
Choptr 5. Physlcs Llbrorls
236
Lotr, ln our ,&&M872,0245 unctlon, onc w know th body, w con occss th ],/2:0-%
objct wlth ?%2u#%/\,2,45.
IJ&7:5# ?KCL ,*55/8/*1_/8'#1/16
0-,## ],/2:0-% 1
W8&" I8&"*
],/2:0-%4E-8,2 !C E-8,2 "C E-8,2 /5 1
W8&"\%E I& ' 7%; W8&"\%E45*
I&N$8#:2:87 ' I8!>&N088/&]:!%-#n8+8/-&4!C "5*
I&N2"$% ' W8&"n"$%N\fkVdcM*
I8&" ' I8!>&N0/%,2%W8&"4I&5*
M:/0-%[<,$% 0# ' 7%; M:/0-%[<,$%45*
0#N9a/,&:3# ' I8!>&N#0,-,/]:!%-#n8+8/-&4/5*
I8&"N0/%,2%b:!23/%4E&C)5*
"this" refers to this Particle object. We are
telling the Box2D Body to store a reference
to this Particle that we can access later.
6813-.$/s.$)Z&/&*/H2.+,
@
A8:& I%?:7M872,024M872,02 0$5 1
b:!23/% E) ' 0$N?%2b:!23/%V45*
b:!23/% E> ' 0$N?%2b:!23/%W45*
W8&" I) ' E)N?%2W8&"45*
W8&" I> ' E>N?%2W8&"45*
When we pull the "user data object out of
the Body object, we have to remind our
program that it is a Particle object. Box2D
doesn't know this.
],/2:0-% $) ' 4],/2:0-%5 I)N?%2u#%/\,2,45*
],/2:0-% $> ' 4],/2:0-%5 I>N?%2u#%/\,2,45*
Once we have the particles, we can do
anything to them. Here we just call a
function that changes their color.
$)N0<,7?%45*
$>N0<,7?%45*
@
1h Notur o Cod [v005j
237
Now, ln mony coss, w connot ossum thot th objcts thot collldd or oll ],/2:0-%
objcts. W mlght hov o sktch wlth W837&,/" objcts, ],/2:0-% objcts, W8! objcts, tc.
5o otn w wlll hov to qury th usr doto" ond lnd out whot klnd o objct lt ls bor
procdlng.
|t should olso b notd thot du to how Box2L trlggrs ths collbocks, you connot crot
or dstroy Box2L ntltls lnsld o I%?:7M872,0245, %7&M872,0245, $/%[8-A%45, or
$8#2[8-A%45. | you wont to do thls, you`ll nd to st o vorlobl lnsld on objct
[somthlng llk. 9,/.b8/\%-%2:87 ' 2/3%j, whlch you chck durlng &/,;45 ond thn
dlt objcts.
Getting a generic object UIo%02 8) ' I)N?%2u#%/\,2,45*
Asking that object if it's a Particle :E 48)N?%2M-,##45 '' ],/2:0-%N0-,##5 1
],/2:0-% $ ' 4],/2:0-%5 8)*
$N0<,7?%45*
@
Consldr how polymorphlsm could hlp ln th obov cos. Bulld on xompl ln whlch
svrol closss xtnd on closs ond thror llmlnot th nd or such tstlng.
MO(.2&-( ?"## MO(.2&-( ?"##
Crot o slmulotlon ln whlch ],/2:0-% objcts dlsoppor whn thy collld wlth on
onothr. s th mthodology | just dscrlbd.
MO(.2&-( ?"#0 MO(.2&-( ?"#0
?"#> ! b.&(+ C;'(.%:9(dC;'(<.4'&*; ](',*9- ?"#> ! b.&(+ C;'(.%:9(dC;'(<.4'&*; ](',*9-
Hos th ollowlng vr hoppnd to you? You`r ot o oncy cocktoll porty rgollng your
rlnds wlth toll tols o sotwor physlcs slmulotlons. 5omon plps up. Lnchontlng! But
whot lntgrotlon mthod or you uslng?" Whot?!" you thlnk to yoursl. |ntgrotlon?"
Moyb you`v hord th trm bor. Along wlth dlrntlotlon," lt`s on o th two moln
oprotlons ln colculus. Rlght, colculus. 1h good nws ls, w`v gottn through obout 90
o th motrlol ln thls book rlotd to physlcs slmulotlon ond w hovn`t rolly ndd to
dlv lnto colculus. But os w`r comlng clos to lnlshlng thls toplc, lt`s worth toklng o
momnt to xomln th colculus bhlnd whot w hov bn dolng ond how lt rlots to th
mthodology ln crtoln physlcs llbrorls [llk Box2L ond th upcomlng toxlcllbsj.
Choptr 5. Physlcs Llbrorls
238
Lt`s bgln by onswrlng th qustlon. Whot dos lntgrotlon hov to do wlth locotlon,
vloclty, ond occlrotlon?" Wll, lrst lt`s dln 8/;;$1$.&/(&/!. 8/;;$1$.&/(&/!., th procss o lndlng o
drlvotlv." 1h drlvotlv o o unctlon ls o mosur o how o unctlon chongs ovr tlm.
Consldr locotlon ond lts drlvotlv. Locotlon ls o polnt ln spoc, whll vloclty ls chong ln
locotlon ovr tlm. 1hror, vloclty con b dscrlbd os th drlvotlv" o locotlon. Whot ls
occlrotlon? 1h chong ln vloclty ovr tlml.. th drlvotlv" o vloclty.
Now thot w undrstond th drlvotlv [dlrntlotlonj, w con dln th lntgrol [lntgrotlonj
os th lnvrs o th drlvotlv. |n othr words, th lntgrol o on objct`s vloclty ovr tlm
tlls us th objct`s nw locotlon whn thot tlm prlod nds. Locotlon ls th lntgrol o
vloclty, ond vloclty ls th lntgrol o occlrotlon. 5lnc our physlcs slmulotlon ls oundd
upon th procss o colculotlng occlrotlon bosd on orcs, w nd lntgrotlon to lgur
out whr th objct ls otr o crtoln prlod o tlm [llk on rom o onlmotlon!j
5o w`v bn dolng lntgrotlon oll olong! |t looks llk thls.
1h obov mthodology ls known os Lulr lntgrotlon [nomd or th mothmotlclon Lonhord
Lulr, pronouncd Ollr"j or th Lulr mthod. |t`s ssntlolly th slmplst orm o lntgrotlon
ond vry osy to lmplmnt ln our cod [s th two llns obov!j Howvr, lt ls not
ncssorlly th most lclnt orm, nor ls lt clos to blng th most occurot. Why ls Lulr
lnoccurot? Lt`s thlnk obout lt thls woy. Whn you drlv o cor down th rood prsslng th gos
pdol wlth your oot ond occlrotlng, dos th cor slt ln on locotlon ot tlm quols on
scond, thn dlsoppor ond suddnly roppor ln o nw locotlon ot tlm quols two sconds,
ond do th som thlng or thr sconds, ond our, ond lv? No, o cours not. 1h cor movs
contlnuously down th rood. But whot`s hoppnlng ln our Procsslng sktch? A clrcl ls ot on
locotlon ot rom 0, onothr ot rom J, onothr ot rom 2. 5ur, ot thlrty roms pr scond,
w`r slng th llluslon o motlon. But w only colculot o nw locotlon vry k unlts o tlm,
whros th rol world ls prctly contlnuous. 1hls rsults ln som lnoccurocls, os shown ln
th dlogrom blow.
A%-80:2"N,&&4,00%-%/,2:875*
-80,2:87N,&&4A%-80:2"5*
1h Notur o Cod [v005j
239
1h rol world" ls th curv, Lulr slmulotlon ls th srls o lln sgmnts.
On optlon to lmprov on Lulr ls to us smollr tlmstpslnstod o onc pr rom, w
could rcolculot on objct`s locotlon twnty tlms pr rom. But thls lsn`t proctlcol, our
sktch would thn run too slowly.
| stlll bllv thot Lulr ls th bst mthod or lornlng th boslcs, ond lt`s olso prctly
odquot or most o th projcts w mlght mok ln Procsslng. Anythlng w los ln
lclncy or lnoccurocy w mok up ln os o us ond undrstondoblllty. |or bttr
occurocy, Box2L uss somthlng colld symplctlc Lulr [http.//n.wlklpdlo.org/wlkl/
5ymplctlc_Lulr_mthodj, or sml-xpllclt Lulr, o sllght modllcotlon o Lulr.
1hr ls olso on lntgrotlon mthod colld Rung-Kutto [nomd or Grmon mothmotlclons
C. Rung ond M. W. Kuttoj, whlch ls usd ln som physlcs nglns.
A vry populor lntgrotlon mthod thot our nxt physlcs llbrory uss ls known os Vrlt
lntgrotlon." A slmpl woy to dscrlb Vrlt lntgrotlon ls to thlnk o our typlcol motlon
olgorlthm wlthout vloclty. Atr oll, w don`t rolly nd to stor th vloclty. | w olwoys
know whr on objct wos ot on polnt ln tlm ond whr lt ls now, w con xtropolot lts
vloclty. Vrlt lntgrotlon dos prclsly thls, though lnstod o hovlng o vorlobl or
vloclty, lt colculots vloclty whll th progrom ls runnlng. Vrlt lntgrotlon ls portlculorly
wll sultd or portlcl systms, spclolly portlcl systms wlth sprlng connctlons
btwn th portlcls. W don`t nd to worry obout th dtolls bcous toxlcllbs, os w`ll
s blow, toks cor o thm or us. Howvr, l you or lntrstd, hr ls th smlnol
popr on Vrlt physlcs, rom whlch just obout vry Vrlt computr grophlcs slmulotlon ls
drlvd. "Advoncd Choroctr Physlcs" [http.//www.gomosutro.com/rsourc_guld/
20030J2J/jocobson_pv.htmj. And o cours, you con lnd out mor obout Vrlt lntgrotlon
rom Wlklpdlo [http.//n.wlklpdlo.org/wlkl/Vrlt_lntgrotlonj.
Iiure .:
Choptr 5. Physlcs Llbrorls
240
?"#? R(.%(' 5,/-&2- 8&', '*O&2%&)- ?"#? R(.%(' 5,/-&2- 8&', '*O&2%&)-
|rom toxlcllbs.org.
"tox|c||bs |s on |ndependent, open soutce ||btoty co||ect|on tot computot|ono| des|gn tos|s
w|th !ovo 8 ltocess|ng deve|oped by kotsten "tox|" 5chm|dt (thus totI. 7he c|osses ote
putposetu||y |ept to|t|y genet|c |n otdet to mox|m|ze te-use |n d|ttetent contexts tong|ng ttom
genetot|ve des|gn, on|mot|on, |ntetoct|on/|ntettoce des|gn, doto v|suo||zot|on to otch|tectute
ond d|g|to| tobt|cot|on, use os teoch|ng too| ond mote."
|n othr words, w should thonk our lucky stors or toxlcllbs. W or only golng to ocus on o
w xompls rlotd to Vrlt physlcs, but toxlcllbs lncluds o sult o othr wondrul
pockogs thot hlp wlth oudlo, color, gomtry, ond mor. |n portlculor, l you or looklng to
work wlth orm ond obrlcotlon ln Procsslng, tok o look ot th gomtry pockog. Lmos
con b ound ot Opn Procsslng [http.//www.opnprocsslng.org/portol/?usr|L4530j.
W should not thot toxlcllbs wos dslgnd spcllcolly or us wlth Procsslng. 1hls ls grot
nws. 1h troubl w hod wlth moklng Box2L work ln Procsslng [multlpl coordlnot
systms, Box2L vs. JBox2L vs. PBox2Lj ls not on lssu hr. toxlcllbs ls o llbrory thot you just
downlood, stlck ln your llbrorls oldr, ond us. And th coordlnot systm thot w`ll us or
th physlcs ngln ls th coordlnot systm o Procsslng, so no tronslotlng bock ond orth. |n
oddltlon, toxlcllbs ls not llmltd to o 2L world, oll o th physlcs slmulotlons ond unctlons
work ln both two ond thr dlmnslons. 5o how do you dcld whlch llbrory you should us?
Box2L or toxlcllbs? | you oll lnto on o th ollowlng two cotgorls, your dclslon ls o blt
oslr.
;K PU :)*^#0' /1N*5N#8 0*55/8/*18K F "&N# 0/)05#8b 8c(&)#8b &1- *'"#) 8')&16#5U 8"&:#- *E^#0'8 ;K PU :)*^#0' /1N*5N#8 0*55/8/*18K F "&N# 0/)05#8b 8c(&)#8b &1- *'"#) 8')&16#5U 8"&:#- *E^#0'8
'"&' 31*03 #&0" *'"#) &)*(1- &1- E*(10# *++ #&0" *'"#)K '"&' 31*03 #&0" *'"#) &)*(1- &1- E*(10# *++ #&0" *'"#)K
|n thls cos, you or golng to nd Box2L. toxlcllbs dos not hondl colllslons.
<K PU :)*^#0' /1N*5N#8 5*'8 *+ :&)'/05#8 +5U/16 &)*(1- '"# 80)##1K O*7#'/7#8 '"#U &'')&0' <K PU :)*^#0' /1N*5N#8 5*'8 *+ :&)'/05#8 +5U/16 &)*(1- '"# 80)##1K O*7#'/7#8 '"#U &'')&0'
#&0" *'"#)K O*7#'/7#8 '"#U )#:#5 #&0" *'"#)K 21- 8*7#'/7#8 '"#U &)# 0*11#0'#- 4/'" #&0" *'"#)K O*7#'/7#8 '"#U )#:#5 #&0" *'"#)K 21- 8*7#'/7#8 '"#U &)# 0*11#0'#- 4/'"
8:)/168K 8:)/168K
|n thls cos, toxlcllbs ls llkly your bst cholc. |t ls slmplr to us thon Box2L ond portlculorly
wll sultd to connctd systms o portlcls. toxlcllbs ls olso vry hlgh prormonc, du to
th spd o th Vrlt lntgrotlon olgorlthm [not to mntlon th oct thot th progrom gts to
lgnor oll o th colllslon gomtryj.
Hr ls o llttl chort thot covrs som o th oturs or och physlcs llbrory.
1h Notur o Cod [v005j
24J
G#&'()# G#&'()# S*J<. S*J<. '*J/05/E8 Q#)5#'9"U8/08 '*J/05/E8 Q#)5#'9"U8/08
Colllslon gomtry Ys No
3L physlcs No Ys
Portlcl ottroctlon /
rpulslon orcs
No Ys
5prlng connctlons Ys Ys
Othr connctlons. rvolut,
pully, gor, prlsmotlc
Ys No
Motors Ys No
|rlctlon Ys No
e(''&;< '*O&2%&)- e(''&;< '*O&2%&)-
Lvrythlng you nd to downlood ond lnstoll toxlcllbs con b ound ot.
toxlcllbs [http.//toxlcllbs.org/j
Whn you downlood th llbrory, you`ll notlc thot lt coms wlth lght moduls [l.. sub-
oldrsj, och o llbrory ln lts own rlght. |or th xompls ln thls choptr, you wlll only nd
vrltphyslcs" ond toxlcllbscor", howvr, | rcommnd you tok o look ot ond consldr
uslng oll o th moduls!
Onc you hov th llbrory lnstolld to your Procsslng llbrory oldr
[http.//wlkl.procsslng.org/w/How_to_|nstoll_o_Contrlbutd_Llbroryj, you or rody to stort
looklng ot th ollowlng xompls.
P*.( M%(E(;'- *+ R(.%('5,/-&2- P*.( M%(E(;'- *+ R(.%('5,/-&2-
W spnt o lot o tlm worklng through th cor lmnts o o Box2L world. world, body,
shop, jolnt. 1hls glvs us o hod stort on undrstondlng toxlcllbs, slnc lt ollows o slmllor
structur.
Choptr 5. Physlcs Llbrorls
242
S*J<. S*J<. '*J/05/E8 Q#)5#'9"U8/08 '*J/05/E8 Q#)5#'9"U8/08
World VrltPhyslcs
Body VrltPortlcl
5hop
Nothlng! toxlcllbs dos not hondl shop
gomtry
|lxtur
Nothlng! toxlcllbs dos not hondl shop
gomtry
Jolnt Vrlt5prlng
R(2'*.- 8&', '*O&2%&)- R(2'*.- 8&', '*O&2%&)-
Hr w go ogoln. Rmmbr oll thot tlm w spnt lornlng th lns ond outs o th ]`%028/
closs? 1hn rmmbr how whn w got to Box2L, w hod to tronslot oll thos concpts to o
Box2L vctor closs. `%0>? Wll, lt`s tlm to do lt ogoln. toxlcllbs olso lncluds lts own vctor
closss, on or two dlmnslons ond on or thr. `%0>\ ond `%0H\.
Agoln, toxlcllbs vctors or th som concptuolly, but w nd to lorn o blt o nw syntox.
You con lnd oll o th documntotlon or ths vctor closss hr.
Vc2L [http.//toxlcllbs.org/docs/cor/toxl/gom/Vc2L.htmlj
Vc3L [http.//toxlcllbs.org/docs/cor/toxl/gom/Vc3L.htmlj
And lt`s just rvlw som o th boslc vctor moth oprotlons wlth ]`%028/ tronslotd to
`%0>\ [w`r stlcklng wlth 2L or slmpllclty`s sokj.
9Q#0'*) 9Q#0'*) Q#0<. Q#0<.
]`%028/ , ' 7%; ]`%028/4)C6)5*
]`%028/ I ' 7%; ]`%028/4HCD5*
,N,&&4I5*
`%0>\ , ' 7%; `%0>\4)C6)5*
`%0>\ I ' 7%; `%0>\4HCD5*
,N,&&[%-E4I5*
]`%028/ , ' 7%; ]`%028/4)C6)5*
]`%028/ I ' 7%; ]`%028/4HCD5*
]`%028/ 0 ' ]`%028/N,&&4,CI5*
`%0>\ , ' 7%; `%0>\4)C6)5*
`%0>\ I ' 7%; `%0>\4HCD5*
`%0>\ 0 ' ,N,&&4I5*
]`%028/ , ' 7%; ]`%028/4)C6)5*
E-8,2 9 ' ,N9,?45*
,N78/9,-:F%45*
`%0>\ , ' 7%; `%0>\4)C6)5*
E-8,2 9 ' ,N9,?7:23&%45*
,N78/9,-:F%45*
1h Notur o Cod [v005j
243
b:&%9&;< ',( '*O&2%&)- Q,/-&2- 8*.%9 b:&%9&;< ',( '*O&2%&)- Q,/-&2- 8*.%9
1h lrst thlng w nd to do to crot o toxlcllbs physlcs world ln our xompls ls lmport
th llbrory ltsl.
1hn w`ll nd o rrnc to our physlcs world, o `%/-%2]<"#:0# or `%/-%2]<"#:0#>\
objct [dpndlng on whthr w or worklng ln two or thr dlmnslonsj. 1h xompls ln
thls choptr wlll oprot ln 2L only or slmpllclty, but thy could oslly b xtndd lnto 3L
[ond 3L vrslons or ovollobl wlth th choptr downloodj.
Onc you hov your `%/-%2]<"#:0# objct, you con st som globol proprtls or your
world. |or xompl, l you wont lt to hov hord boundorls post whlch objcts connot trovl,
you con st lts llmlts.
|n oddltlon, you con odd grovlty to th physlcs world wlth o Z/,A:2"W%<,A:8/ objct. A
grovlty bhovlor rqulrs o vctorhow strong ond ln whot dlrctlon ls th grovlty?
|lnolly, ln ordr to colculot th physlcs o th world ond mov th objcts ln th world, w
hov to coll 3$&,2%45. 1yplcolly thls would hoppn onc pr rom ln &/,;45.
mporting the libraries :9$8/2 28!:N$<"#:0#>&NQ*
:9$8/2 28!:N$<"#:0#>&NI%<,A:8/#NQ*
:9$8/2 28!:N?%89NQ*
`%/-%2]<"#:0#>\ $<"#:0#*
A8:& #%23$45 1
Creating a toxiclibs Verlet physics world $<"#:0#'7%; `%/-%2]<"#:0#>\45*
$<"#:0#N#%2+8/-&W837&#47%; Y%024BCBC;:&2<C<%:?<255*
$<"#:0#N,&&W%<,A:8/47%; Z/,A:2"W%<,A:8/47%; `%0>\4BCBNJ555*
@
A8:& &/,;45 1
This is the same as Box2D's "step()
function
$<"#:0#N3$&,2%45*
@
?"#K 54.'&2%(- 4;9 UQ.&;<- &; '*O&2%&)- ?"#K 54.'&2%(- 4;9 UQ.&;<- &; '*O&2%&)-
|n th Box2L xompls, w sow how w con crot our own closs [colld, soy, ],/2:0-%j
ond lnclud o rrnc to o Box2L body.
Choptr 5. Physlcs Llbrorls
244
1hls tchnlqu ls somwhot rdundont slnc Box2L ltsl kps trock o oll o th bodls ln lts
world. Howvr, lt ollows us to monog whlch body ls whlch [ond thror how och body ls
drownj wlthout hovlng to rly on ltrotlng through Box2L`s lntrnol llsts.
Lt`s look ot how w mlght tok th som opprooch wlth th closs `%/-%2],/2:0-%>\ ln
toxlcllbs. W wont to mok our own ],/2:0-% closs so thot w con drow our portlcls o crtoln
woy ond lnclud ony custom proprtls. W`d probobly wrlt our cod os ollows.
Looklng ot th obov, w should lrst b thrllld to notlc thot drowlng th portlcl ls os slmpl
os grobblng th x ond y ond uslng thm. No owkword convrslons btwn coordlnot
systms hr slnc toxlcllbs ls dslgnd to thlnk ln plxls. 5cond, you mlght notlc thot thls
],/2:0-% closs`s sol purpos ls to stor o rrnc to o `%/-%2],/2:0-%>\ objct. 1hls
hlnts ot somthlng. Rmmbr our dlscusslon o lnhrltonc bock ln Choptr 4. Portlcl
5ystms? Whot ls o ],/2:0-% objct othr thon on ougmntd" `%/-%2],/2:0-%? Why
bothr moklng o vrlt portlcl lnsld o portlcl whn w could slmply %!2%7&
`%/-%2],/2:0-%?
0-,## ],/2:0-% 1
W8&" I8&"*
0-,## ],/2:0-% 1
Our Particle has a reference to a
VerletParticle.
`%/-%2],/2:0-%>\ $*
],/2:0-%4`%0>\ $8#5 1
A VerletParticle needs an initial location (an
x and y).
$ ' 7%; `%/-%2],/2:0-%>\4$8#5*
@
A8:& &:#$-,"45 1
E:--4BC)JB5*
#2/8.%4B5*
When it comes time to draw the Particle, we
ask the VerletParticle for its x and y
coordinates.
%--:$#%4$N!C$N"C)GC)G5*
@
@
0-,## ],/2:0-% %!2%7&# `%/-%2],/2:0-%>\ 1
],/2:0-%4`%0>\ -805 1
Calling super() so that the object is
initialized properly
#3$%/4-805*
@
We want this to be just like a VerletParticle,
only with a display() method.
A8:& &:#$-,"45 1
E:--4)OJ5*
#2/8.%4B5*
1h Notur o Cod [v005j
245
Rmmbr our multl-stp procss wlth th Box2L xompls? W hod to osk th body or lts
locotlon, thn convrt thot locotlon to plxls, thn us thot locotlon ln o drowlng unctlon.
Now, bcous w hov lnhrltd vrythlng rom th `%/-%2],/2:0-% closs, our only stp
ls to drow th shop ot ! ond "!
|ncldntolly, lt`s lntrstlng to not thot th `%/-%2],/2:0-%>\ closs ls o subcloss o `%0>\.
5o ln oddltlon to lnhrltlng vrythlng rom `%/-%2],/2:0-%>\, our ],/2:0-% closs octuolly
hos oll o th `%0>\ unctlons ovollobl os wll.
W con now crot portlcls onywhr wlthln our sktch.
Just moklng o portlcl lsn`t nough, howvr. W hov to mok sur w tll our physlcs
world obout thm wlth th ,&&],/2:0-%45 unctlon.
| you look ot th toxlcllbs documntotlon, you`ll s thot th ,&&],/2:0-%45 xpcts o
`%/-%2],/2:0-%>\ objct.
,&&],/2:0-%4`%/-%2],/2:0-%>\ $,/2:0-%5
And how con w thn poss lnto th unctlon our own ],/2:0-% objct? Rmmbr thot
othr tnt o objct-orlntd progrommlngpolymorphlsm? Hr, bcous our ],/2:0-%
closs %!2%7&# `%/-%2],/2:0-%>\, w con choos to trot our portlcl ln two dlrnt
woysos o ],/2:0-% or os o `%/-%2],/2:0-%>\. 1hls ls on lncrdlbly powrul otur o
objct-orlntd progrommlng. | w bulld our custom closss bosd on closss rom
toxlcllbs, w con us our objcts ln conjunctlon wlth oll o th unctlons toxlcllbs hos to
or.
|n oddltlon to th `%/-%2],/2:0-% closs, toxlcllbs hos o st o closss thot ollow you to
connct portlcls wlth sprlng orcs. 1hr or thr typs o sprlngs ln toxlcllbs.
- `%/-%2[$/:7?. 1hls closs crots o sprlngy connctlon btwn two portlcls ln
spoc. A sprlng`s proprtls con b conlgurd ln such o woy os to crot o stl
stlck-llk connctlon or o hlghly lostlc strtchy connctlon. A portlcl con olso b
lockd so thot only on nd o th sprlng con mov.
We've inherited x and y from VerletParticle! %--:$#%4!C"C)GC)G5*
@
@
],/2:0-% $) ' 7%; ],/2:0-%47%; `%0>\4)BBC>B55*
],/2:0-% $> ' 7%; ],/2:0-%47%; `%0>\4)BBC)XB55*
$<"#:0#N,&&],/2:0-%4$)5*
$<"#:0#N,&&],/2:0-%4$>5*
Choptr 5. Physlcs Llbrorls
246
- `%/-%2M87#2/,:7%&[$/:7?. A `%/-%2M87#2/,:7%&[$/:7? objct ls o sprlng whos
moxlmum dlstonc con b llmltd. 1hls con hlp th whol sprlng systm ochlv
bttr stoblllty.
- `%/-%2d:7\:#2,70%[$/:7?. A `%/-%2d:7\:#2,70%[$/:7? objct ls o sprlng thot
only norcs lts rst lngth l th currnt dlstonc ls lss thon lts rst lngth. 1hls ls
hondy l you wont to nsur objcts or ot lost o crtoln dlstonc rom och othr,
but don`t cor l th dlstonc ls blggr thon th norcd mlnlmum.
1h lnhrltonc ond polymorphlsm tchnlqu w mployd ln th prvlous sctlon olso
provs to b usul whn crotlng sprlngs. A sprlng xpcts two portlcls whn lt ls crotd.
And ogoln, bcous our ],/2:0-% closs %!2%7&# `%/-%2],/2:0-%, o `%/-%2[$/:7? objct
wlll occpt our ],/2:0-% objcts possd lnto th constructor. Lt`s tok o look ot som
xompl cod thot ossums th xlstnc o our two prvlous portlcls $) ond $> ond crots
o connctlon btwn thm wlth o glvn rst lngth ond strngth.
Just os wlth portlcls, ln ordr or th connctlon to octuolly b port o th physlcs world, w
nd to xpllcltly odd lt.
What is the rest length of the spring? E-8,2 -%7 ' XB*
How strong is the spring? E-8,2 #2/%7?2< ' BNB)*
`%/-%2[$/:7?>\ #$/:7?'7%; `%/-%2[$/:7?>\4$)C$>C-%7C#2/%7?2<5*
$<"#:0#N,&&[$/:7?4#$/:7?5*
?"#L 5:''&;< C' !%% @*<(',(.D ! U&EQ%( C;'(.42'&I( ?"#L 5:''&;< C' !%% @*<(',(.D ! U&EQ%( C;'(.42'&I(
UQ.&;< UQ.&;<
On thlng w sow wlth Box2L ls thot th physlcs slmulotlon brok down whn w ovrrod lt
ond monuolly st th locotlon o o body. Wlth toxlcllbs, w don`t hov thls problm. | w wont
to mov th locotlon o o portlcl, w con slmply st lts x ond y locotlon monuolly. Howvr,
bor w do so, lt`s gnrolly o good ldo to coll th -80.45 unctlon.
-80.45 ls typlcolly usd to lock o portlcl ln ploc ond ls ldntlcol to sttlng o Box2L body`s
dnslty to 0. Howvr, hr w or golng to show how to lock o portlcl tmpororlly, mov lt,
ond thn unlock lt so thot lt contlnus to mov occordlng to th physlcs slmulotlon. Lt`s soy
you wont to mov o glvn portlcl whnvr you cllck th mous.
:E 4983#%]/%##%&5 1
1h Notur o Cod [v005j
247
And now w`r rody to put oll o ths lmnts togthr ln o slmpl xompl thot
conncts two portlcls wlth o sprlng. On portlcl ls lockd ln ploc, ond th othr con b
movd by drogglng th mous. Not thot thls xompl ls vlrtuolly ldntlcol to Lxompl 3.JJ
[s pog J39j.
IJ&7:5# ?K;DL O/7:5# O:)/16 4/'" '*J/05/E8
First lock the particle, then set the x and y,
then unlock() it.
$>N-80.45*
$>N! ' 983#%e*
$>N" ' 983#%f*
$>N37-80.45*
@
:9$8/2 28!:N$<"#:0#>&NQ*
:9$8/2 28!:N$<"#:0#>&NI%<,A:8/#NQ*
:9$8/2 28!:N?%89NQ*
`%/-%2]<"#:0#>\ $<"#:0#*
],/2:0-% $)*
],/2:0-% $>*
A8:& #%23$45 1
#:F%4>BBC>BB5*
Creating a physics world $<"#:0#'7%; `%/-%2]<"#:0#>\45*
$<"#:0#N,&&W%<,A:8/47%; Z/,A:2"W%<,A:8/>\47%; `%0>\4BCBNJ555*
$<"#:0#N#%2+8/-&W837&#47%; Y%024BCBC;:&2<C<%:?<255*
Creating two Particles $) ' 7%; ],/2:0-%47%; `%0>\4)BBC>B55*
$> ' 7%; ],/2:0-%47%; `%0>\4)BBC)XB55*
Locking Particle 1 in place $)N-80.45*
`%/-%2[$/:7?>\ #$/:7?'7%; `%/-%2[$/:7?>\4$)C$>CXBCBNB)5*
Creating one Spring
Choptr 5. Physlcs Llbrorls
248
Must add everything to the world $<"#:0#N,&&],/2:0-%4$)5*
$<"#:0#N,&&],/2:0-%4$>5*
$<"#:0#N,&&[$/:7?4#$/:7?5*
@
A8:& &/,;45 1
Must update the physics $<"#:0#N3$&,2%45*
I,0.?/837&4>JJ5*
Drawing everything -:7%4$)N!C$)N"C$>N!C$>N"5*
$)N&:#$-,"45*
$>N&:#$-,"45*
:E 4983#%]/%##%&5 1
Moving a Particle according to the mouse $>N-80.45*
$>N! ' 983#%e*
$>N" ' 983#%f*
$>N37-80.45*
@
@
How cute is our simple Particle class?! 0-,## ],/2:0-% %!2%7&# `%/-%2],/2:0-%>\ 1
],/2:0-%4`%0>\ -805 1
#3$%/4-805*
@
A8:& &:#$-,"45 1
E:--4)OJ5*
#2/8.%4B5*
%--:$#%4!C"C)GC)G5*
@
@
?"#N P*;;(2'(9 U/-'(E- 54.' CD U'.&;< ?"#N P*;;(2'(9 U/-'(E- 54.' CD U'.&;<
1h obov xompl, two portlcls connctd wlth o slngl sprlng, ls th cor bulldlng block
or whot toxlcllbs` physlcs ls portlculorly wll sultd or. sot body slmulotlons. |or xompl, o
strlng con b slmulotd by connctlng o lln o portlcls wlth sprlngs. A blonkt con b
slmulotd by connctlng o grld o portlcls wlth sprlngs. And o cut, cuddly, squlshy cortoon
choroctr con b slmulotd by o custom loyout o portlcls connctd wlth sprlngs.
1h Notur o Cod [v005j
249
Lt`s bgln by slmulotlng o sot pndulum"o bob honglng rom o strlng, lnstod o o rlgld
orm llk w hod ln Choptr 3 [s pog J3Jj. Lt`s us th "strlng" ln |lgur 5.J4 obov os
our modl.
|lrst, w`ll nd o llst o portlcls [lt`s us th som ],/2:0-% closs w bullt ln th prvlous
xomplj.
Now, lt`s soy w wont to hov 20 portlcls, oll spocd J0 plxls oport.
W con loop rom : quols 0 oll th woy up to 20, wlth och portlcl`s y locotlon st to : Q
)B so thot th lrst portlcl ls ot (0,!0I, th scond ot (0,20I, th thlrd ot (0,30I, tc.
Iiure .:(
V//,"l:#2P],/2:0-%^ $,/2:0-%# ' 7%; V//,"l:#2P],/2:0-%^45*
Iiure .:
E-8,2 -%7 ' )B*
E-8,2 739],/2:0-%# ' >B*
E8/4:72 :'B* : P 739]8:72#* :((5 1
Spacing them out along the x-axis ],/2:0-% $,/2:0-%'7%; ],/2:0-%4:Q-%7C)B5*
Add the particle to our list. $<"#:0#N,&&],/2:0-%4$,/2:0-%5*
Choptr 5. Physlcs Llbrorls
250
Lvn though lt`s o blt rdundont, w`r golng to odd th portlcl to both th toxlcllbs physlcs
world ond to our own llst. |n cos w vntuolly hov multlpl strlngs, thls wlll ollow us to
know whlch portlcls or connctd to whlch strlngs.
Now or th un port. |t`s tlm to connct oll th portlcls. Portlcl J wlll b connctd to
portlcl 0, portlcl 2 to portlcl J, 3 to 2, 4 to 3, tc.
|n othr words, portlcl : nds to b connctd to portlcl :6) [xcpt or whn : quols
zroj.
Now, whot l w wont th strlng to hong rom o lxd polnt? W con lock on o th
portlclsth lrst, th lost, th mlddl on, tc. Hr`s how w would occss th lrst portlcl
[ln th V//,"l:#2j ond lock lt.
And l w wont to drow oll th portlcls os blng connctd wlth o lln, olong wlth o clrcl or
th lost portlcl, w con us I%?:7[<,$%45, %7&[<,$%45, ond A%/2%!45, occsslng th
portlcl locotlons rom our V//,"l:#2.
Add the particle to the physics world. $,/2:0-%#N,&&4$,/2:0-%5*
@
Iiure .:
:E 4: S' B5 1
First we need a reference to the previous
particle.
],/2:0-% $/%A:83# ' $,/2:0-%#N?%24:6)5*
`%/-%2[$/:7?>\ #$/:7? ' 7%; `%/-%2[$/:7?>\4$,/2:0-%C$/%A:83#C-%7C#2/%7?2<5*
Then we make a spring connection between
the particle and the previous particle with a
rest length and strength (both floats).
We must not forget to add the spring to the
physics world.
$<"#:0#N,&&[$/:7?4#$/:7?5*
@
],/2:0-% <%,&'$,/2:0-%#N?%24B5*
<%,&N-80.45*
1h Notur o Cod [v005j
25J
IJ&7:5# ?K;;L O*+' 84/16/16 :#1-(5(7
1h ull cod ovollobl wlth th choptr downlood olso dmonstrots how to drog th toll
portlcl wlth th mous.
#2/8.%4B5*
78b:--45*
I%?:7[<,$%45*
E8/ 4],/2:0-% $ q $,/2:0-%#5 1
Each particle is one point in the line. A%/2%!4$N!C$N"5*
@
%7&[<,$%45*
],/2:0-% 2,:- ' $,/2:0-%#N?%24739]8:72#6)5*
This draws the last particle as a circle. 2,:-N&:#$-,"45*
Crot o honglng cloth slmulotlon uslng th tchnlqu obov, but connct oll th
portlcls wlth o grld os dmonstrotd ln th scrnshot blow.
MO(.2&-( ?"#= MO(.2&-( ?"#=
Choptr 5. Physlcs Llbrorls
252
?"#W P*;;(2'(9 U/-'(E- 54.' CCD S*.2(Z\&.(2'(9 ?"#W P*;;(2'(9 U/-'(E- 54.' CCD S*.2(Z\&.(2'(9
e.4Q, e.4Q,
Hov you vr ncountrd th ollowlng scnorlo?
| hov o whol bunch o stu | wont to drow on th scrn ond | wont oll thot stu to b
spocd out vnly ln o nlc, not, orgonlzd monnr. Othrwls | hov troubl slplng ot
nlght."
1hls ls not on uncommon problm ln computotlonol dslgn. On solutlon ls typlcolly rrrd
to os o orc-dlrctd groph." A orc-dlrctd groph ls o vlsuollzotlon o lmntslt`s coll
thm nods"ln whlch th posltlons o thos nods or not monuolly osslgnd. Rothr, th
nods orrong thmslvs occordlng to o st o orcs. Whll ony orcs con b usd, o
typlcol xompl lnvolvs sprlng orcs. And so toxlcllbs ls prct or thls scnorlo.
How do w lmplmnt th obov?
|lrst, w`ll nd o k8&% closs. 1hls ls th osy port, lt con %!2%7& `%/-%2],/2:0-%>\. Rolly,
thls ls just whot w dld bor, only w`r colllng lt k8&% now lnstod o ],/2:0-%.
Nxt w con wrlt o closs colld M-3#2%/, whlch wlll dscrlb o llst o nods.
0-,## k8&% %!2%7&# `%/-%2],/2:0-%>\ 1
k8&%4`%0>\ $8#5 1
#3$%/4$8#5*
@
A8:& &:#$-,"45 1
E:--4BC)JB5*
#2/8.%4B5*
%--:$#%4!C"C)GC)G5*
@
@
1h Notur o Cod [v005j
253
Lt`s ossum w oddd o &:#$-,"45 unctlon to drow oll th nods ln th clustr ond
crotd o M-3#2%/ objct ln #%23$45 ond dlsployd lt ln &/,;45. | w ron th sktch os ls,
nothlng would hoppn. Why? Bcous w orgot th whol orc-dlrctd groph port! W
nd to connct vry slngl nod to vry othr nod wlth o orc. But whot xoctly do w
mon by thot? Lt`s ossum w hov our k8&% objcts. 0, J, 2 ond 3. Hr or our
connctlons.
? :8##$:/$1 /8 D
? :8##$:/$1 /8 >
? :8##$:/$1 /8 E
D :8##$:/$1 /8 >
D :8##$:/$1 /8 E
> :8##$:/$1 /8 E
Notlc two lmportont dtolls obout our connctlon llst.
- ^! .!8$ /) %!..$%&$8 &! /&)$';6 ^! .!8$ /) %!..$%&$8 &! /&)$';6 W don`t hov 0 connctd to 0 or J connctd to
J.
- F$ 8!.\& .$$8 &! 1$A$(& %!..$%&/!.) /. 1$0$1)$6 F$ 8!.\& .$$8 &! 1$A$(& %!..$%&/!.) /. 1$0$1)$6 |n othr words, l w`v olrody
sold 0 ls connctd to J, w don`t nd to soy J ls connctd to 0 bcous, wll, lt
olrody ls!
5o how do w wrlt cod to mok ths connctlons or N numbr o nods?
Look ot th lt column. |t rods. 000 JJ 22. 5o w know w nd to occss och nod ln
th llst rom 0 to N-J.
0-,## M-3#2%/ 1
V//,"l:#2Pk8&%^ 78&%#*
We'll use this variable for the rest length
between all the nodes.
E-8,2 &:,9%2%/*
M-3#2%/4:72 7C E-8,2 &C `%0>\ 0%72%/5 1
78&%# ' 7%; V//,"l:#2Pk8&%^45*
&:,9%2%/ ' &*
E8/ 4:72 : ' B* : P 7* :((5 1
78&%#N,&&47%; k8&%40%72%/N,&&4`%0>\N/,7&89`%028/45555*
@
@
Here's a funny little detail. We're going to
have a problem if all the Node objects start
in exactly the same location. So we add a
random vector to the center location so that
each Node is slightly offset.
E8/ 4:72 : ' B* : P 78&%#N#:F%456)* :((5 1
`%/-%2],/2:0-%>\ 7: ' 78&%#N?%24:5*
Choptr 5. Physlcs Llbrorls
254
Now, w know w nd to connct nod 0 to nods J,2,3. |or nod J. 2,3. |or nod 2. 3. 5o
or vry nod l, w must loop rom lJ untll th nd o th llst.
Wlth vry two k8&%s w lnd, oll w hov to do thn ls mok o sprlng.
Assumlng thos connctlons or mod ln th M-3#2%/ constructor, w con now crot o
clustr ln our moln tob ond s th rsults!
IJ&7:5# ?K;<L ,5(8'#)
Look how we start j at i + 1. 98) *2#/ t " 2KD, t S #81$.-.2]$*+, tKK+ O
`%/-%2],/2:0-%>\ 7o ' 78&%#N?%24o5*
The Spring connects Nodes "ni and "nj. $<"#:0#N,&&[$/:7?47%;
`%/-%2[$/:7?>\47:C7oC&:,9%2%/CBNB)55*
@
@
:9$8/2 28!:N?%89NQ*
:9$8/2 28!:N$<"#:0#>&NQ*
`%/-%2]<"#:0#>\ $<"#:0#*
M-3#2%/ 0-3#2%/*
A8:& #%23$45 1
#:F%4HBBCHBB5*
$<"#:0#'7%; `%/-%2]<"#:0#>\45*
0-3#2%/ ' 7%; M-3#2%/4XC)BBC7%; `%0>\4;:&2<=>C<%:?<2=>55*
@
A8:& &/,;45 1
$<"#:0#N3$&,2%45*
I,0.?/837&4>JJ5*
Make a cluster.
1h Notur o Cod [v005j
255
Draw the cluster. 0-3#2%/N&:#$-,"45*
@
s th M-3#2%/ structur os o sklton or o cut, cuddly, squlshy crotur [ lo
Noklo |rlnds"j. Add grovlty ond olso ollow th crotur to b droggd wlth th
mous.
MO(.2&-( ?"#> MO(.2&-( ?"#>
Lxpond th orc-dlrctd groph to hov mor thon on M-3#2%/ objct. s o
`%/-%2d:7\:#2,70%[$/:7?>\ objct to connct clustr to clustr.
MO(.2&-( ?"#? MO(.2&-( ?"#?
?"0T !''.42'&*; 4;9 Y(Q:%-&*; b(,4I&*.- ?"0T !''.42'&*; 4;9 Y(Q:%-&*; b(,4I&*.-
Whn w lookd ot oddlng on ottroctlon orc to Box2L, w ound thot th Box2L W8&"
closs lncludd on ,$$-"b8/0%45 unctlon. All w ndd to do wos colculot th ottroctlon
orc [|orc G ' mossJ ' moss2 / dlstonc squordj os o vctor ond opply lt to th body.
toxlcllbs `%/-%2],/2:0-% closs olso lncluds o unctlon colld ,&&b8/0%45 thot w con us
to opply ony colculotd orc to o portlcl.
Howvr, toxlcllbs olso toks thls ldo on stp urthr by ollowlng us to ottoch som
common orcs [lt`s coll thm bhovlors"j to portlcls, colculotlng thm ond opplylng thm
or us! |or xompl, l w ottoch on V22/,02:87W%<,A:8/ objct to o portlcl, thn oll othr
portlcls ln th physlcs world wlll b ottroctd to thot portlcl.
Choptr 5. Physlcs Llbrorls
256
Lt`s soy w hov o ],/2:0-% closs [thot %!2%7&# `%/-%2],/2:0-%j.
Onc w`v mod o ],/2:0-% objct, w con crot on V22/,02:87W%<,A:8/ objct
ossoclotd wlth thot portlcl.
Notlc how th bhovlor ls crotd wlth two poromtrs&:#2,70% ond #2/%7?2<. 1h
dlstonc spclls th rong wlthln whlch th bhovlor wlll b opplld. |or xompl, ln th
obov scnorlo, only othr portlcls wlthln twnty plxls wlll l th ottroctlon orc. 1h
strngth, o cours, spclls how strong th orc ls.
|lnolly, ln ordr or th orc to b octlvotd, th bhovlor nds to b oddd to th physlcs
world.
1hls mons vrythlng thot llvs ln th physlcs slmulotlon wlll olwoys b ottroctd to thot
portlcl, os long os lt ls wlthln th dlstonc thrshold.
Lvn though toxlcllbs dos not hondl colllslons, you con crot o colllslon-llk ct by
oddlng o rpulslv bhovlor to och ond vry portlcl [so thot vry portlcl rpls vry
othr portlclj. Lt`s look ot how w mlght modly our ],/2:0-% closs to do thls.
W could now rcrot our ottroctlon xompl by hovlng o slngl V22/,028/ objct thot
xrts on ottroctlon bhovlor ovr th ntlr wlndow.
],/2:0-% $ ' 7%; ],/2:0-%47%; `%0>\4>BBC>BB55*
E-8,2 &:#2,70% ' >B*
E-8,2 #2/%7?2< ' BN)*
V22/,02:87W%<,A:8/ I%<,A:8/ ' 7%; V22/,02:87W%<,A:8/4$C &:#2,70%C #2/%7?2<5*
$<"#:0#N,&&W%<,A:8/4I%<,A:8/5*
0-,## ],/2:0-% %!2%7&# `%/-%2],/2:0-%>\ 1
We've added a radius to every Particle. E-8,2 /*
],/2:0-% 4`%0>\ -805 1
#3$%/4-805*
/ ' D*
$<"#:0#N,&&W%<,A:8/47%; V22/,02:87W%<,A:8/42<:#C /QDC 6)55*
@
A8:& &:#$-," 45 1
E:-- 4>JJ5*
#2/8.% 4>JJ5*
%--:$#% 4!C "C /Q>C /Q>5*
@
@
Every time a Particle is made, an
AttractionBehavior is generated and added
to the physics world. Note that when the
strength is negative, it's a repulsive force!
1h Notur o Cod [v005j
257
IJ&7:5# ?K;=L 2'')&0'/*1ZH#:(58/*1
0-,## V22/,028/ %!2%7&# `%/-%2],/2:0-%>\ 1
E-8,2 /*
V22/,028/ 4`%0>\ -805 1
#3$%/ 4-805*
/ ' >D*
$<"#:0#N,&&W%<,A:8/47%; V22/,02:87W%<,A:8/42<:#C ;:&2<C BN)55*
@
A8:& &:#$-," 45 1
E:--4B5*
%--:$#% 4!C "C /Q>C /Q>5*
@
@
The AttractionBehavior "distance equals
the width so that it covers the entire
window.
Crot on objct thot both ottrocts ond rpls. Whot l lt ottrocts ony portlcl thot ls or
owoy but rpls thos portlcls ot o short dlstonc?
MO(.2&-( ?"#K MO(.2&-( ?"#K
s V22/,02:87W%<,A:8/ ln conjunctlon wlth sprlng orcs.
MO(.2&-( ?"#L MO(.2&-( ?"#L
Choptr 5. Physlcs Llbrorls
258
@,( M2*-/-'(E 5.*G(2' @,( M2*-/-'(E 5.*G(2'
U'(Q ? MO(.2&-(D
@43( /*:. -/-'(E *+ 2.(4':.(- +.*E U'(Q > 4;9 :-( 4 Q,/-&2- (;<&;( '* 9.&I( ',(&.
E*'&*; 4;9 )(,4I&*.-" U*E( Q*--&)&%&'&(-D
h [-( b*O0\ '* 4%%*8 2*%%&-&*;- )('8((; 2.(4':.(-" P*;-&9(. '.&<<(.&;<
(I(;'- 8,(; 2.(4':.(- 2*%%&9("
h [-( b*O0\ '* 4:<E(;' ',( 9(-&<; *+ /*:. 2.(4':.(-" b:&%9 4 -3(%('*; 8&',
9&-'4;2( G*&;'- *. E43( 4QQ(;94<(- 8&', .(I*%:'( G*&;'-"
h [-( '*O&2%&)- '* 4:<E(;' ',( 9(-&<; *+ /*:. 2.(4':.(" [-( 4 2,4&; *+
'*O&2%&)- Q4.'&2%(- +*. '(;'42%(- *. 4 E(-, *+ -Q.&;<- 4- 4 -3(%('*;"
h [-( '*O&2%&)- '* 499 4''.42'&*; 4;9 .(Q:%-&*; )(,4I&*.- '* /*:. 2.(4':.(-"
h [-( -Q.&;< ^*. G*&;'_ 2*;;(2'&*;- )('8((; *)G(2'- '* 2*;'.*% ',(&.
&;'(.42'&*;-" P.(4'( 4;9 9(%('( ',(-( -Q.&;<- *; ',( +%/" P*;-&9(. E43&;<
',(-( 2*;;(2'&*;- I&-&)%( *. &;I&-&)%( '* ',( I&(8(."
1h Notur o Cod [v005j
259
,"&:'#) @K ,"&:'#) @K
2('*1*7*(8 26#1'8 2('*1*7*(8 26#1'8
This is cn exercise in jictioncl science, or science jiction, ij ou lile thct
better.
! F$?&,4-,0 /2$-4&,K&27
Bllv lt or not, thr ls o purpos. Wll, ot lost thr`s o purpos to th lrst lv choptrs
o thls book. W could stop rlght hr, otr oll, w`v lookd ot svrol dlrnt woys o
modllng motlon ond slmulotlng physlcs. Angry Blrds, hr w com!
5tlll, lt`s thlnk or o momnt. Why or w hr? 1h notute o cod, rlght? Whot hov w
bn dslgnlng so or? |nonlmot objcts. Lllss shops slttlng on our scrns thot lop
oround whn octd by orcs ln thlr nvlronmnt. Whot l w could broth ll lnto
thos shops? Whot l thos shops could llv by thlr own ruls? Con shops hov hops
ond droms ond ors? 1hls ls whot w or hr ln thls choptr to dodvlop outonomous
ogents.
K"# S*.2(- +.*E 6&',&; K"# S*.2(- +.*E 6&',&;
1h trm (:&!.!-!:) (2$.& (:&!.!-!:) (2$.& gnrolly rrs to on ntlty thot moks lts own cholcs obout
how to oct ln lts nvlronmnt wlthout ony lnlunc rom o lodr or globol plon. |or us,
octlng" wlll mon movlng. 1hls oddltlon ls o slgnllcont concptuol lop. |nstod o o box
slttlng on o boundory woltlng to b pushd by onothr olllng box, w or now golng to
Choptr 6. Autonomous Agnts
260
dslgn o box thot hos th oblllty ond dslr" to lop out o th woy o thot othr olllng box, l
lt so chooss. Whll th concpt o orcs thot com rom wlthln ls o mojor shlt ln our dslgn
thlnklng, our cod bos wlll borly chong, os ths dslrs ond octlons or slmply
thottotces.
Hr or thr ky componnts o outonomous ognts thot w`ll wont to kp ln mlnd os w
bulld our xompls.
- 21 &('*1*7*(8 &6#1' "&8 & 21 &('*1*7*(8 &6#1' "&8 & '/-/&$8 '/-/&$8 &E/5/'U '* :#)0#/N# #1N/)*17#1'K &E/5/'U '* :#)0#/N# #1N/)*17#1'K |t moks
sns thot o llvlng, brothlng blng should hov on owornss o lts nvlronmnt.
Whot dos thls mon or us, howvr? As w look ot xompls ln thls choptr, w
wlll polnt out progrommlng tchnlqus or ollowlng objcts to stor rrncs to
othr objcts ond thror prclv" thlr nvlronmnt. |t`s olso cruclol thot w
consldr th word ||m|ted hr. Ar w dslgnlng on oll-knowlng rctongl thot lls
oround o Procsslng wlndow, owor o vrythlng ls ln thot wlndow? Or or w
crotlng o shop thot con only xomln ony othr objct wlthln ltn plxls o
ltsl? O cours, thr ls no rlght onswr to thls qustlon, lt oll dpnds. W`ll
xplor som posslbllltls os w mov orword. |or o slmulotlon to l mor
noturol," howvr, llmltotlons or o good thlng. An lnsct, or xompl, moy only b
owor o th slghts ond smlls thot lmmdlotly surround lt. |or o rol-world
crotur, w could study th xoct sclnc o ths llmltotlons. Lucklly or us, w
con just mok stu up ond try lt out.
- 21 &('*1*7*(8 &6#1' :)*0#88#8 '"# /1+*)7&'/*1 +)*7 /'8 #1N/)*17#1' &1- 21 &('*1*7*(8 &6#1' :)*0#88#8 '"# /1+*)7&'/*1 +)*7 /'8 #1N/)*17#1' &1-
0&50(5&'#8 &1 &0'/*1K 0&50(5&'#8 &1 &0'/*1K 1hls wlll b th osy port or us, os th octlon ls o orc. 1h
nvlronmnt mlght tll th ognt thot thr`s o blg scory-looklng shork swlmmlng
rlght ot lt, ond th octlon wlll b o powrul orc ln th opposlt dlrctlon.
- 21 &('*1*7*(8 &6#1' "&8 1* 5#&-#)K 21 &('*1*7*(8 &6#1' "&8 1* 5#&-#)K 1hls thlrd prlnclpl ls somthlng w cor o
llttl lss obout. Atr oll, l you or dslgnlng o systm whr lt moks sns to
hov o lodr borklng commonds ot vorlous ntltls, thn thot`s whot you`ll wont to
lmplmnt. Nvrthlss, mony o ths xompls wlll hov no lodr or on
lmportont roson. As w gt to th nd o thls choptr ond xomln group
bhovlors, w wlll look ot dslgnlng collctlons o outonomous ognts thot xhlblt
th proprtls o complx systms lntlllgnt ond structurd group dynomlcs thot
mrg not rom o lodr, but rom th locol lntroctlons o th lmnts
thmslvs.
|n th lot J980s, computr sclntlst Crolg Rynolds [http.//www.rd3d.com/cwr/j dvlopd
olgorlthmlc strlng bhovlors or onlmotd choroctrs. 1hs bhovlors ollowd lndlvlduol
lmnts to novlgot thlr dlgltol nvlronmnts ln o llllk" monnr wlth strotgls or
llng, wondrlng, orrlvlng, pursulng, vodlng, tc. sd ln th cos o o slngl outonomous
ognt, ths bhovlors or olrly slmpl to undrstond ond lmplmnt. |n oddltlon, by bulldlng
o systm o multlpl choroctrs thot str thmslvs occordlng to slmpl, locolly bosd ruls,
surprlslng lvls o complxlty mrg. 1h most omous xompl ls Rynolds`s bolds"
modl or locklng/swormlng" bhovlor.
1h Notur o Cod [v005j
26J
K"0 R(,&2%(- 4;9 U'((.&;< K"0 R(,&2%(- 4;9 U'((.&;<
Now thot w undrstond th cor concpts bhlnd outonomous ognts, w con bgln
wrltlng th cod. 1hr or mony plocs whr w could stort. Artllclol slmulotlons o ont
ond trmlt colonls or ontostlc dmonstrotlons o systms o outonomous ognts. [|or
mor on thls toplc, | ncourog you to rod 7utt|es, 7etm|tes, ond 7tott|c !oms by Mltchl
Rsnlck.j Howvr, w wont to bgln by xomlnlng ognt bhovlors thot bulld on th work
w`v don ln th lrst lv choptrs o thls book. modllng motlon wlth vctors ond drlvlng
motlon wlth orcs. And so lt`s tlm to rnom our d8A%/ closs thot bcom our ],/2:0-%
closs onc ogoln. 1hls tlm w or golng to coll lt `%<:0-%.
|n hls J999 popr 5trlng Bhovlors or Autonomous Choroctrs," Rynolds uss th word
vhlcl" to dscrlb hls outonomous ognts, so w wlll ollow sult.
6,/ R(,&2%(7 6,/ R(,&2%(7
|n J986, |tollon nurosclntlst ond cybrntlclst Volntlno Broltnbrg dscrlbd o
srls o hypothtlcol vhlcls wlth slmpl lntrnol structurs ln hls book Veh|c|es.
lxpet|ments |n 5ynthet|c lsycho|ogy. Broltnbrg orgus thot hls xtroordlnorlly
slmpl mchonlcol vhlcls monlst bhovlors such os or, oggrsslon, lov,
orslght, ond optlmlsm. Rynolds took hls lnsplrotlon rom Broltnbrg, ond w`ll
tok ours rom Rynolds.
Rynolds dscrlbs th motlon o |deo||zed vhlcls [ldollzd bcous w or not
concrnd wlth th octuol nglnrlng o such vhlcls, but slmply ossum thot thy xlst
ond wlll rspond to our rulsj os o srls o thr loyrs20'/*1 O#5#0'/*1 20'/*1 O#5#0'/*1, O'##)/16 O'##)/16, ond
_*0*7*'/*1 _*0*7*'/*1.
J. D%&/!. Q$'$%&/!.6 D%&/!. Q$'$%&/!.6 A vhlcl hos o gool [or goolsj ond con slct on octlon [or o
comblnotlon o octlonsj bosd on thot gool. 1hls ls ssntlolly whr w lt o
wlth outonomous ognts. 1h vhlcl toks o look ot lts nvlronmnt ond
colculots on octlon bosd on o dslr. | s o zombl morchlng towords m.
5lnc | don`t wont my brolns to b otn, |`m golng to l rom th zombl." 1h
gool ls to kp on`s brolns ond th octlon ls to l. Rynolds`s popr dscrlbs
mony gools ond ossoclotd octlons such os. sk o torgt, ovold on obstocl, ond
0-,## `%<:0-% 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
== +<,2 %-#% &8 ;% 7%%& 28 ,&&i
Choptr 6. Autonomous Agnts
262
ollow o poth. |n o momnt, w`ll stort bulldlng ths xompls out wlth Procsslng
cod.
2. Q&$$1/.26 Q&$$1/.26 Onc on octlon hos bn slctd, th vhlcl hos to colculot lts nxt
mov. |or us, th nxt mov wlll b o orc, mor spcllcolly, o strlng orc.
Lucklly, Rynolds hos dvlopd o slmpl strlng orc ormulo thot w`ll us
throughout th xompls ln thls choptr. )&$$1/.2 ;!1%$ ? 8$)/1$8 0$'!%/&@ H %:11$.& )&$$1/.2 ;!1%$ ? 8$)/1$8 0$'!%/&@ H %:11$.&
0$'!%/&@ 0$'!%/&@. W`ll gt lnto th dtolls o thls ormulo ond why lt works so ctlvly ln
th nxt sctlon.
3. _!%!-!&/!.6 _!%!-!&/!.6 |or th most port, w`r golng to lgnor thls thlrd loyr. |n th cos o
llng zombls, th locomotlon could b dscrlbd os lt oot, rlght oot, lt oot,
rlght oot, os ost os you con." |n our Procsslng world, howvr, o rctongl or clrcl
or trlongl`s octuol movmnt ocross o wlndow ls lrrlvont glvn thot lt`s oll on
llluslon ln th lrst ploc. Nvrthlss, thls lsn`t to soy thot you should lgnor
locomotlon ntlrly. You wlll lnd grot volu ln thlnklng obout th locomotlv dslgn
o your vhlcl ond how you choos to onlmot lt. 1h xompls ln thls choptr wlll
rmoln vlsuolly bor, ond o good xrcls would b to loborot on th onlmotlon
styl could you odd splnnlng whls or osclllotlng poddls or shullng lgs?
ltlmotly, th most lmportont loyr or you to consldr ls #JAct|on 5e|ect|on. Whot or th
lmnts o your systm ond whot or thlr gools? |n thls choptr, w or golng to look ot o
srls o strlng bhovlors [l.. octlonsj. sk, l, ollow o poth, ollow o low lld, lock
wlth your nlghbors, tc. |t`s lmportont to rollz, howvr, thot th polnt o undrstondlng
how to wrlt th cod or ths bhovlors ls not bcous you should us thm ln oll o your
projcts. Rothr, ths or o st o bulldlng blocks, o oundotlon rom whlch you con dslgn
ond dvlop vhlcls wlth crotlv gools ond nw ond xcltlng bhovlors. And vn though
w wlll thlnk lltrolly ln thls choptr [ollow thot plxl!j, you should ollow yoursl to thlnk mor
obstroctly [llk Broltnbrgj. Whot would lt mon or your vhlcl to hov lov" or or" os lts
gool, lts drlvlng orc? |lnolly [ond w`ll oddrss thls lotr ln th choptrj, you won`t gt vry
or by dvloplng slmulotlons wlth only on octlon. Ys, our lrst xompl wlll b sk o
torgt." But or you to b crotlvto mok ths strlng bhovlors yout ownlt wlll oll
com down to mlxlng ond motchlng multlpl octlons wlthln th som vhlcl. 5o vlw ths
xompls not os slngulor bhovlors to b mulotd, but os plcs o o lorgr puzzl thot you
wlll vntuolly ossmbl.
K"= @,( U'((.&;< S*.2( K"= @,( U'((.&;< S*.2(
W con ntrtoln ourslvs by dlscusslng th thortlcol prlnclpls bhlnd outonomous
ognts ond strlng os much os w llk, but w con`t gt onywhr wlthout lrst
undrstondlng th concpt o o strlng orc. Consldr th ollowlng scnorlo. A vhlcl
movlng wlth vloclty dslrs to sk o torgt.
1h Notur o Cod [v005j
263
|ts gool ond subsqunt octlon ls to sk
th torgt ln |lgur 6.J. | you thlnk bock to
Choptr 2, you mlght bgln by moklng th
torgt on ottroctor ond opply o grovltotlonol
orc thot pulls th vhlcl to th torgt.
1hls would b o prctly rosonobl
solutlon, but concptuolly lt`s not whot
w`r looklng or hr. W don`t wont to
slmply colculot o orc thot pushs th
vhlcl towords lts torgt, rothr, w or
osklng th vhlcl to mok on lntlllgnt
dclslon to str towords th torgt bosd
on lts prcptlon o lts stot ond
nvlronmnt [l.. how ost ond ln whot
dlrctlon ls lt currntly movlngj. 1h vhlcl should look ot how lt dslrs to mov [o vctor
polntlng to th torgtj, compor thot gool wlth how qulckly lt ls currntly movlng [lts
vlocltyj, ond opply o orc occordlngly.
)&$$1/.2 ;!1%$ ? 8$)/1$8 0$'!%/&@ H %:11$.& 0$'!%/&@ )&$$1/.2 ;!1%$ ? 8$)/1$8 0$'!%/&@ H %:11$.& 0$'!%/&@
Or os w mlght wrlt ln Procsslng.
|n th obov ormulo, vloclty ls no problm. Atr oll, w`v got o vorlobl or thot.
Howvr, w don`t hov th des|ted ve|oc|ty, thls ls somthlng w hov to colculot. Lt`s
tok o look ot |lgur 6.2. | w`v dlnd th vhlcl`s gool os sklng th torgt," thn lts
dslrd vloclty ls o vctor thot polnts rom lts currnt locotlon to th torgt locotlon.
Assumlng o ]`%028/ torgt, w thn hov.
Iiure .:
]`%028/ #2%%/ ' ]`%028/N#3I4&%#:/%&CA%-80:2"5*
Iiure .z
]`%028/ &%#:/%& ' ]`%028/N#3I42,/?%2C-80,2:875*
Choptr 6. Autonomous Agnts
264
But thls lsn`t portlculorly rollstlc. Whot l w hov o vry hlgh-rsolutlon wlndow ond th
torgt ls thousonds o plxls owoy? 5ur, th vhlcl mlght dslr to tlport ltsl lnstontly to
th torgt locotlon wlth o mosslv vloclty, but thls won`t mok or on ctlv onlmotlon.
Whot w rolly wont to soy ls.
7he veh|c|e des|tes to move towotds the totget ot mox|mum speed.
|n othr words, th vctor should polnt rom locotlon to torgt ond wlth o mognltud quol to
moxlmum spd [l.. th ostst th vhlcl con goj. 5o lrst, w nd to mok sur w odd o
vorlobl to our `%<:0-% closs thot stors moxlmum spd.
1hn, ln our dslrd vloclty colculotlon, w scol occordlng to moxlmum spd.
Puttlng thls oll togthr, w con wrlt o unctlon colld #%%.45 thot rclvs o ]`%028/ torgt
ond colculots o strlng orc towords thot torgt.
0-,## `%<:0-% 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
Maximum speed E-8,2 9,!#$%%&*
]`%028/ &%#:/%& ' ]`%028/N#3I42,/?%2C-80,2:875*
&%#:/%&N78/9,-:F%45*
&%#:/%&N93-249,!#$%%&5*
Iiure .
A8:& #%%.4]`%028/ 2,/?%25 1
]`%028/ &%#:/%& ' ]`%028/N#3I42,/?%2C-80,2:875*
&%#:/%&N78/9,-:F%45*
Calculating the desired velocity to target at
max speed
&%#:/%&N93-249,!#$%%&5*
Reynolds's formula for steering force ]`%028/ #2%%/ ' ]`%028/N#3I4&%#:/%&CA%-80:2"5*
1h Notur o Cod [v005j
265
Not how ln th obov unctlon w lnlsh by posslng th strlng orc lnto ,$$-"b8/0%45.
1hls ossums thot w or boslng thls xompl on th oundotlon w bullt ln Choptr 2 [s
pog 66j. Howvr, you could just os oslly us th strlng orc wlth Box2L`s
,$$-"b8/0%45 unctlon or toxlcllbs` ,&&b8/0%45 unctlon.
5o why dos thls oll work so wll? Lt`s s whot th strlng orc looks llk rlotlv to th
vhlcl ond torgt locotlons.
Agoln, notlc how thls ls not ot oll th som orc os grovltotlonol ottroctlon. Rmmbr on
o our prlnclpls o outonomous ognts. An outonomous ognt hos o ||m|ted oblllty to
prclv lts nvlronmnt. Hr ls thot oblllty, subtly mbddd lnto Rynolds`s strlng
ormulo. | th vhlcl wrn`t movlng ot oll [zro vlocltyj, dslrd mlnus vloclty would b
quol to dslrd. But thls ls not th cos. 1h vhlcl ls owor o lts own vloclty ond lts
strlng orc compnsots occordlngly. 1hls crots o mor octlv slmulotlon, os th woy
ln whlch th vhlcl movs towords th torgts dpnds on th woy lt ls movlng ln th lrst
ploc.
|n oll o thls xcltmnt, howvr, w`v mlssd on lost stp. Whot sort o vhlcl ls thls? |s
lt o supr slk roc cor wlth omozlng hondllng? Or o glont Mock truck thot nds o lot o
odvonc notlc to turn? A grocul pondo, or o lumbrlng lphont? Our xompl cod, os lt
stonds, hos no otur to occount or thls vorloblllty ln strlng oblllty. 5trlng oblllty con
b controlld by llmltlng th mognltud o th strlng orc. Lt`s coll thot llmlt th
moxlmum orc" [or 9,!E8/0% or shortj. And so lnolly, w hov.
Using our physics model and applying the
force to the object's acceleration
,$$-"b8/0%4#2%%/5*
@
Iiure .(
0-,## `%<:0-% 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
Choptr 6. Autonomous Agnts
266
ollowd by.
Llmltlng th strlng orc brlngs up on lmportont polnt. W must olwoys rmmbr thot lt`s
not octuolly our gool to gt th vhlcl to th torgt os ost os posslbl. | thot wr th cos,
w would just soy locotlon quols torgt" ond thr th vhlcl would b. Our gool, os
Rynolds puts lt, ls to mov th vhlcl ln o llllk ond lmprovlsotlonol monnr." W`r trylng
to mok lt oppor os l th vhlcl ls strlng lts woy to th torgt, ond so lt`s up to us to ploy
wlth th orcs ond vorlobls o th systm to slmulot o glvn bhovlor. |or xompl, o lorg
moxlmum strlng orc would rsult ln o vry dlrnt poth thon o smoll on. On ls not
lnhrntly bttr or wors thon th othr, lt dpnds on your dslrd ct. [And o cours,
ths volus nd not b lxd ond could chong bosd on othr condltlons. Prhops o
vhlcl hos holth. th hlghr th holth, th bttr lt con str.j
Hr ls th ull `%<:0-% closs, lncorporotlng th rst o th lmnts rom th Choptr 2
d8A%/ objct.
Maximum speed E-8,2 9,!#$%%&*
Now we also have maximum force. E-8,2 9,!E8/0%*
A8:& #%%.4]`%028/ 2,/?%25 1
]`%028/ &%#:/%& ' ]`%028/N#3I42,/?%2C-80,2:875*
&%#:/%&N78/9,-:F%45*
&%#:/%&N93-249,!#$%%&5*
]`%028/ #2%%/ ' ]`%028/N#3I4&%#:/%&CA%-80:2"5*
Limit the magnitude of the steering force. #2%%/N-:9:249,!E8/0%5*
,$$-"b8/0%4#2%%/5*
@
Iiure .
1h Notur o Cod [v005j
267
IJ&7:5# @K;L O##3/16 & '&)6#'
0-,## `%<:0-% 1
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
Additional variable for size E-8,2 /*
E-8,2 9,!E8/0%*
E-8,2 9,!#$%%&*
`%<:0-%4E-8,2 !C E-8,2 "5 1
,00%-%/,2:87 ' 7%; ]`%028/4BCB5*
A%-80:2" ' 7%; ]`%028/4BCB5*
-80,2:87 ' 7%; ]`%028/4!C"5*
/ ' HNB*
Arbitrary values for maxspeed and force;
try varying these!
9,!#$%%& ' D*
9,!E8/0% ' BN)*
@
Our standard "Euler integration motion
model
A8:& 3$&,2%45 1
A%-80:2"N,&&4,00%-%/,2:875*
A%-80:2"N-:9:249,!#$%%&5*
-80,2:87N,&&4A%-80:2"5*
,00%-%/,2:87N93-24B5*
@
Newton's second law; we could divide by
mass if we wanted.
A8:& ,$$-"b8/0%4]`%028/ E8/0%5 1
,00%-%/,2:87N,&&4E8/0%5*
@
Choptr 6. Autonomous Agnts
268
Our seek steering force algorithm A8:& #%%.4]`%028/ 2,/?%25 1
]`%028/ &%#:/%& ' ]`%028/N#3I42,/?%2C-80,2:875*
&%#:/%&N78/9,-:F%45*
&%#:/%&N93-249,!#$%%&5*
]`%028/ #2%%/ ' ]`%028/N#3I4&%#:/%&CA%-80:2"5*
#2%%/N-:9:249,!E8/0%5*
,$$-"b8/0%4#2%%/5*
@
A8:& &:#$-,"45 1
Vehicle is a triangle pointing in the direction
of velocity; since it is drawn pointing up, we
rotate it an additional 90 degrees.
E-8,2 2<%2, ' A%-80:2"N<%,&:7?>\45 ( ]c=>*
E:--4)OJ5*
#2/8.%4B5*
$3#<d,2/:!45*
2/,7#-,2%4-80,2:87N!C-80,2:87N"5*
/82,2%42<%2,5*
I%?:7[<,$%45*
A%/2%!4BC 6/Q>5*
A%/2%!46/C /Q>5*
A%/2%!4/C /Q>5*
%7&[<,$%4MlU[h5*
$8$d,2/:!45*
@
|mplmnt o llng" strlng bhovlor [dslrd vctor ls lnvrs o sk"j.
MO(.2&-( K"# MO(.2&-( K"#
|mplmnt sklng o movlng torgt, otn rrrd to os pursult." |n thls cos, your
dslrd vctor won`t polnt towords th objct`s currnt locotlon, but rothr lts utur"
locotlon os xtropolotd rom lts currnt vloclty. W`ll s thls oblllty or o vhlcl to
prdlct th utur" ln lotr xompls.
MO(.2&-( K"0 MO(.2&-( K"0
Crot o sktch whr o vhlcl`s moxlmum orc ond moxlmum spd do not rmoln
constont, but rothr vory occordlng to nvlronmntol octors.
MO(.2&-( K"= MO(.2&-( K"=
1h Notur o Cod [v005j
269
K"> !..&I&;< b(,4I&*. K"> !..&I&;< b(,4I&*.
Atr worklng or o blt wlth th sklng bhovlor, you probobly or osklng yoursl, Whot l
| wont my vhlcl to slow down os lt opproochs th torgt?" Bor w con vn bgln to
onswr thls qustlon, w should look ot th rosons bhlnd why th sk bhovlor couss
th vhlcl to ly post th torgt so thot lt hos to turn oround ond go bock. Lt`s consldr th
broln o o sklng vhlcl. Whot ls lt thlnklng?
|rom J. | wont to go os ost os posslbl towords th torgt!
|rom 2. | wont to go os ost os posslbl towords th torgt!
|rom 3. | wont to go os ost os posslbl towords th torgt!
|rom 4. | wont to go os ost os posslbl towords th torgt!
|rom 5. | wont to go os ost os posslbl towords th torgt!
tc.
1h vhlcl ls so gosh dorn xcltd obout gttlng to th torgt thot lt dosn`t bothr to
mok ony lntlllgnt dclslons obout lts spd rlotlv to th torgt`s proxlmlty. Whthr lt`s
or owoy or vry clos, lt olwoys wonts to go os ost os posslbl.
|n som coss, thls ls th dslrd bhovlor [l o mlssll ls lylng ot o torgt, lt should olwoys
trovl ot moxlmum spd.j Howvr, ln mony othr coss [o cor pulllng lnto o porklng spot, o
b londlng on o lowrj, th vhlcl`s thought procss nds to consldr lts spd rlotlv
to th dlstonc rom lts torgt. |or xompl.
|rom J. |`m vry or owoy. | wont to go os ost os posslbl towords th torgt!
|rom 2. |`m vry or owoy. | wont to go os ost os posslbl towords th torgt!
|rom 3. |`m somwhot or owoy. | wont to go os ost os posslbl towords th torgt!
|rom 4. |`m gttlng clos. | wont to go mor slowly towords th torgt!
|rom 5. |`m olmost thr. | wont to go vry slowly towords th torgt!
|rom 6. |`m thr. | wont to stop!
How con w lmplmnt thls orrlvlng" bhovlor ln cod? Lt`s rturn to our #%%.45 unctlon
ond lnd th lln o cod whr w st th mognltud o th dslrd vloclty.
Iiure .
Iiure .;
Choptr 6. Autonomous Agnts
270
|n Lxompl 6.J, th mognltud o th dslrd vctor ls olwoys moxlmum" spd.
Whot l w lnstod sold th dslrd vloclty ls quol to hol th dlstonc?
Whll thls nlcly dmonstrots our gool o o dslrd spd tld to our dlstonc rom th
torgt, lt`s not portlculorly rosonobl. Atr oll, J0 plxls owoy ls rothr clos ond o dslrd
spd o 5 ls rothr lorg. 5omthlng llk o dslrd vloclty wlth o mognltud o 5 o th
dlstonc would work much bttr.
]`%028/ &%#:/%& ' ]`%028/N#3I42,/?%2C-80,2:875*
&%#:/%&N78/9,-:F%45*
&%#:/%&N93-249,!#$%%&5*
Iiure .8
Iiure .p
]`%028/ &%#:/%& ' ]`%028/N#3I42,/?%2C-80,2:875*
&%#:/%&N&:A4>5*
1h Notur o Cod [v005j
27J
Rynolds dscrlbs o mor sophlstlcotd opprooch. Lt`s lmogln o clrcl oround th torgt
wlth o glvn rodlus. | th vhlcl ls wlthln thot clrcl, lt slows downot th dg o th
clrcl, lts dslrd spd ls moxlmum spd, ond ot th torgt ltsl, lts dslrd spd ls 0.
|n othr words, l th dlstonc rom th torgt ls lss thon r, th dslrd spd ls btwn 0
ond moxlmum spd moppd occordlng to thot dlstonc.
IJ&7:5# @K<L 2))/N# 8'##)/16 E#"&N/*)
]`%028/ &%#:/%& ' ]`%028/N#3I42,/?%2C-80,2:875*
&%#:/%&N93-24BNBJ5*
Iiure .:o
A8:& ,//:A%4]`%028/ 2,/?%25 1
]`%028/ &%#:/%& ' ]`%028/N#3I42,/?%2C-80,2:875*
The distance is the magnitude of the vector
pointing from location to target.
E-8,2 & ' &%#:/%&N9,?45*
&%#:/%&N78/9,-:F%45*
Choptr 6. Autonomous Agnts
272
1h orrlv bhovlor ls o grot dmonstrotlon o th moglc o dslrd mlnus vloclty." Lt`s
xomln thls modl ogoln rlotlv to how w colculotd orcs ln orllr choptrs. |n th
grovltotlonol ottroctlon" xompls, th orc olwoys polntd dlrctly rom th objct to th
torgt [th xoct dlrctlon o th dslrd vlocltyj, whthr th orc wos strong or wok.
1h strlng unctlon, howvr, soys. | hov th oblllty to prclv th nvlronmnt." 1h
orc lsn`t bosd on just th dslrd vloclty, but on th dslrd vloclty rlotlv to th currnt
vloclty. Only thlngs thot or ollv con know thlr currnt vloclty. A box olllng o o tobl
dosn`t know lt`s olllng. A chtoh choslng lts pry, howvr, knows lt ls choslng.
1h strlng orc, thror, ls ssntlolly o monlstotlon o th currnt vloclty`s $11!1 $11!1. "|`m
supposd to b golng thls ost ln thls dlrctlon, but |`m octuolly golng thls ost ln onothr
dlrctlon. My rror ls th dlrnc btwn whr | wont to go ond whr | om currntly
golng." 1oklng thot rror ond opplylng lt os o strlng orc rsults ln mor dynomlc, llllk
slmulotlons. Wlth grovltotlonol ottroctlon, you would nvr hov o orc polntlng owoy rom th
torgt, no mottr how clos. But wlth orrlvlng vlo strlng, l you or movlng too ost towords
th torgt, th rror would octuolly tll you to slow down!
f we are closer than 100 pixels... :E 4& P )BB5 1
...set the magnitude according to how close
we are.
E-8,2 9 ' 9,$4&CBC)BBCBC9,!#$%%&5*
&%#:/%&N93-2495*
@ %-#% 1
Otherwise, proceed at maximum speed. &%#:/%&N93-249,!#$%%&5*
@
The usual steering = desired - velocity ]`%028/ #2%%/ ' ]`%028/N#3I4&%#:/%&CA%-80:2"5*
#2%%/N-:9:249,!E8/0%5*
,$$-"b8/0%4#2%%/5*
@
Iiure .::
1h Notur o Cod [v005j
273
K"? a*:. F8; \(-&.(-D \(-&.(9 R(%*2&'/ K"? a*:. F8; \(-&.(-D \(-&.(9 R(%*2&'/
1h lrst two xompls w`v covrdsk ond orrlvboll down to colculotlng o slngl
vctor or och bhovlor. th des|ted vloclty. And ln oct, vry slngl on o Rynolds`s
strlng bhovlors ollows thls som pottrn. |n thls choptr, w`r golng to wolk through
svrol mor o Rynolds`s bhovlorslow lld, poth-ollowlng, locklng. |lrst, howvr, |
wont to mphoslz ogoln thot ths or exomp|esdmonstrotlons o common strlng
bhovlors thot or usul ln procdurol onlmotlon. 1hy or not th b-oll ond nd-oll o
whot you con do. As long os you con com up wlth o vctor thot dscrlbs o vhlcl`s
des|ted vloclty, thn you hov crotd your own strlng bhovlor.
Lt`s s how Rynolds dlns th dslrd vloclty or hls wondrlng bhovlor.
Wcnderin is c tpe oj rcndom steerin uhich hcs some lon term order: the steerin
direction on one jrcme is relcted to the steerin direction on the next jrcme. This produces
more interestin motion thcn, jor excmple, simpl enerctin c rcndom steerin direction
ecch jrcme.
-Crci Renolds (http:,,uuu.redd.com,cur,steer,Wcnder.html)
|or Rynolds, th gool o wondrlng ls not
slmply rondom motlon, but rothr o sns
o movlng ln on dlrctlon or o llttl whll,
wondrlng o to th nxt or o llttl blt, ond
so on ond so orth. 5o how dos Rynolds
colculot o dslrd vctor to ochlv such
on ct?
|lgur 6.J2 lllustrots how th vhlcl
prdlcts lts utur locotlon os o lxd
dlstonc ln ront o lt [ln th dlrctlon o lts
vlocltyj, drows o clrcl wlth rodlus / ot thot
locotlon, ond plcks o rondom polnt olong
th clrcumrnc o th clrcl. 1hot
rondom polnt movs rondomly oround th
clrcl ln och rom o onlmotlon. And thot
rondom polnt ls th vhlcl`s torgt, lts dslrd vctor polntlng ln thot dlrctlon.
5ounds o blt obsurd, rlght? Or, ot th vry lost, rothr orbltrory. |n oct, thls ls o vry clvr
ond thoughtul solutlonlt uss rondomnss to drlv o vhlcl`s strlng, but constrolns thot
rondomnss olong th poth o o clrcl to kp th vhlcl`s movmnt rom opporlng
jlttry, ond, wll, rondom.
But th smlngly rondom ond orbltrory notur o thls solutlon should drlv hom th polnt
|`m trylng to mokths or mod-up bhovlors lnsplrd by rol-ll motlon. You con just
os oslly concoct som loborot scnorlo to comput o dslrd vloclty yoursl. And you
should.
Iiure .:z
Choptr 6. Autonomous Agnts
274
Lt`s soy w wont to crot o strlng bhovlor colld stoy wlthln wolls." W`ll dln th
dslrd vloclty os.
]; ( 0$+/%'$ %!-$) >/&+/. ( 8/)&(.%$ ]; ( 0$+/%'$ %!-$) >/&+/. ( 8/)&(.%$ d !; ( >(''I /& 8$)/1$) &! -!0$ (& -(K/-:- )A$$8 /. !; ( >(''I /& 8$)/1$) &! -!0$ (& -(K/-:- )A$$8 /.
&+$ !AA!)/&$ 8/1$%&/!. !; &+$ >(''6 &+$ !AA!)/&$ 8/1$%&/!. !; &+$ >(''6
| w dln th wolls o th spoc os th dgs o o Procsslng wlndow ond th dlstonc & os
25, th cod ls rothr slmpl.
Wrlt th cod or Rynolds`s wondrlng bhovlor. s polor coordlnots to colculot
th vhlcl`s torgt olong o clrculor poth.
MO(.2&-( K"> MO(.2&-( K">
Iiure .:
1h Notur o Cod [v005j
275
IJ&7:5# @K=L dO'&U 4/'"/1 4&558e 8'##)/16 E#"&N/*)
:E 4-80,2:87N ! ^ >J5 1
]`%028/ &%#:/%& ' 7%; ]`%028/49,!#$%%&CA%-80:2"N"5*
]`%028/ #2%%/ ' ]`%028/N#3I4&%#:/%&C A%-80:2"5*
#2%%/N-:9:249,!E8/0%5*
,$$-"b8/0%4#2%%/5*
@
Make a desired vector that retains the y
direction of the vehicle but points the x
direction directly away from the window's
left edge.
Com up wlth your own orbltrory schm or colculotlng o dslrd vloclty.
MO(.2&-( K"? MO(.2&-( K"?
K"K S%*8 S&(%9- K"K S%*8 S&(%9-
Now bock to th tosk ot hond. Lt`s xomln o coupl mor o Rynolds`s strlng
bhovlors. |lrst, ;'!> ;/$'8 ;!''!>/.2 ;'!> ;/$'8 ;!''!>/.2. Whot ls o low lld? 1hlnk o your Procsslng wlndow
os o grld. |n och cll o th grld llvs on orrow polntlng ln som dlrctlonyou know, o
vctor. As o vhlcl movs oround th scrn, lt osks, Hy, whot orrow ls bnoth m?
1hot`s my dslrd vloclty!"
Choptr 6. Autonomous Agnts
276
Rynolds`s low lld ollowlng xompl hos th vhlcl prdlctlng lts utur locotlon ond
ollowlng th vctor ot thot spot, but or slmpllclty`s sok, w`ll hov th vhlcl slmply look to
th vctor ot lts currnt locotlon.
Bor w con wrlt th oddltlonol cod or our `%<:0-% closs, w`ll nd to bulld o closs thot
dscrlbs th low lld ltsl, th grld o vctors. A two-dlmnslonol orroy ls o convnlnt doto
structur ln whlch to stor o grld o lnormotlon. | you or not omlllor wlth 2L orroys, |
suggst rvlwlng thls onlln Procsslng tutorlol. 2L orroy [http.//procsslng.org/lornlng/
2dorroy/j. 1h 2L orroy ls convnlnt bcous w rrnc och lmnt wlth two lndlcs,
whlch w con thlnk o os columns ond rows.
Notlc how w or dlnlng o thlrd vorlobl colld /%#8-32:87 obov. Whot ls thls vorlobl?
Lt`s soy w hov o Procsslng wlndow thot ls 200 plxls wld by 200 plxls hlgh. W could
mok o low lld thot hos o ]`%028/ objct or vry slngl plxl, or 40,000 ]`%028/s [200 '
200j. 1hls lsn`t trrlbly unrosonobl, but ln our cos, lt`s ovrklll. W don`t nd o ]`%028/
Iiure .:(
0-,## b-8;b:%-& 1
Declaring a 2D array of PVectors ]`%028/KLKL E:%-&*
How many columns and how many rows in
the grid?
:72 08-#C /8;#*
Resolution of grid relative to window width
and height in pixels
:72 /%#8-32:87*
1h Notur o Cod [v005j
277
or vry slngl plxl, w con ochlv th som ct by hovlng, soy, on vry tn plxls
[20 ' 20 400j. W us thls rsolutlon to dln th numbr o columns ond rows bosd on
th slz o th wlndow dlvldd by rsolutlon.
Now thot w`v st up th low lld`s doto structurs, lt`s tlm to comput th vctors ln th
low lld ltsl. How do w do thot? Howvr w l llk lt! Prhops w wont to hov vry
vctor ln th low lld polntlng to th rlght.
Or prhops w wont th vctors to polnt ln rondom dlrctlons.
b-8;b:%-&45 1
/%#8-32:87 ' )B*
Total columns equals width divided by
resolution.
08-# ' ;:&2<=/%#8-32:87*
Total rows equals height divided by
resolution.
/8;# ' <%:?<2=/%#8-32:87*
E:%-& ' 7%; ]`%028/K08-#LK/8;#L*
@
Iiure .:
Using a nested loop to hit every column
and every row of the flow field
E8/ 4:72 : ' B* : P 08-#* :((5 1
E8/ 4:72 o ' B* o P /8;#* o((5 1
Arbitrary decision to make each vector
point to the right
E:%-&K:LKoL ' 7%; ]`%028/4)CB5*
@
@
Choptr 6. Autonomous Agnts
278
Whot l w us 2L Prlln nols [moppd to on onglj?
Iiure .:
E8/ 4:72 : ' B* : P 08-#* :((5 1
E8/ 4:72 o ' B* o P /8;#* o((5 1
A random PVector E:%-&K:LKoL ' ]`%028/N>\45*
@
@
Iiure .:;
E-8,2 !8EE ' B*
E8/ 4:72 : ' B* : P 08-#* :((5 1
E-8,2 "8EE ' B*
E8/ 4:72 o ' B* o P /8;#* o((5 1
E-8,2 2<%2, ' 9,$478:#%4!8EEC"8EE5CBC)CBCn+Ua]c5*
E:%-&K:LKoL ' 7%; ]`%028/408#42<%2,5C#:742<%2,55*
"8EE (' BN)*
@
!8EE (' BN)*
@
Noise
1h Notur o Cod [v005j
279
Now w`r gttlng somwhr. |low llds con b usd or slmulotlng vorlous cts, such
os on lrrgulor gust o wlnd or th mondrlng poth o o rlvr. Colculotlng th dlrctlon o
your vctors uslng Prlln nols ls on woy to ochlv such on ct. O cours, thr`s no
corrct" woy to colculot th vctors o o low lld, lt`s rolly up to you to dcld whot
you`r looklng to slmulot.
Now thot w hov o two-dlmnslonol orroy storlng oll o th low lld vctors, w nd o
woy or o vhlcl to look up lts dslrd vctor ln th low lld. Lt`s soy w hov o vhlcl
thot llvs ot o ]`%028/. lts locotlon. W lrst nd to dlvld by th rsolutlon o th grld. |or
xompl, l th rsolutlon ls J0 ond th vhlcl ls ot (!00,50I, w nd to look up column J0
ond row 5.
Bcous o vhlcl could thortlcolly wondr o th Procsslng wlndow, lt`s olso usul or
us to mploy th 087#2/,:745 unctlon to mok sur w don`t look outsld o th low lld
orroy. Hr ls o unctlon w`ll coll -88.3$45 thot gos ln th b-8;b:%-& closslt rclvs o
]`%028/ [prsumobly th locotlon o our vhlclj ond rturns th corrspondlng low lld
]`%028/ or thot locotlon.
Wrlt th cod to colculot o ]`%028/ ot vry locotlon ln th low lld thot polnts
towords th cntr o o wlndow.
]`%028/ A ' 7%; ]`%028/4aaaaaaaaaaaaCaaaaaaaaaaaa5*
ANaaaaaaaaaaaaaa45*
E:%-&K:LKoL ' A*
MO(.2&-( K"K MO(.2&-( K"K
:72 08-397 ' :724-80,2:87N!=/%#8-32:875*
:72 /8; ' :724-80,2:87N"=/%#8-32:875*
]`%028/ -88.3$4]`%028/ -88.3$5 1
Using constrain()
:72 08-397 ' :724087#2/,:74-88.3$N!=/%#8-32:87CBC08-#6)55*
:72 /8; ' :724087#2/,:74-88.3$N"=/%#8-32:87CBC/8;#6)55*
Choptr 6. Autonomous Agnts
280
Bor w mov on to th `%<:0-% closs, lt`s tok o look ot th b-8;b:%-& closs oll togthr.
5o lt`s ossum w hov o b-8;b:%-& objct colld low". slng th -88.3$45 unctlon
obov, our vhlcl con thn rtrlv o dslrd vctor rom th low lld ond us Rynolds`s
ruls [strlng dslrd - vlocltyj to colculot o strlng orc.
Note the use of get() to ensure we return a
copy of the PVector.
/%23/7 E:%-&K08-397LK/8;LN?%245*
@
0-,## b-8;b:%-& 1
A flow field is a two-dimensional array of
PVectors.
]`%028/KLKL E:%-&*
:72 08-#C /8;#*
:72 /%#8-32:87*
b-8;b:%-&4:72 /5 1
/%#8-32:87 ' /*
Determine the number of columns and
rows.
08-# ' ;:&2<=/%#8-32:87*
/8;# ' <%:?<2=/%#8-32:87*
E:%-& ' 7%; ]`%028/K08-#LK/8;#L*
:7:245*
@
A8:& :7:245 1
E-8,2 !8EE ' B*
E8/ 4:72 : ' B* : P 08-#* :((5 1
E-8,2 "8EE ' B*
E8/ 4:72 o ' B* o P /8;#* o((5 1
E-8,2 2<%2, ' 9,$478:#%4!8EEC"8EE5CBC)CBCn+Ua]c5*
n this example, we use Perlin noise to seed
the vectors.
E:%-&K:LKoL ' 7%; ]`%028/408#42<%2,5C#:742<%2,55*
"8EE (' BN)*
@
!8EE (' BN)*
@
@
Polar to Cartesian coordinate transformation
to get x and y components of the vector
A function to return a PVector based on a
location
]`%028/ -88.3$4]`%028/ -88.3$5 1
:72 08-397 ' :724087#2/,:74-88.3$N!=/%#8-32:87CBC08-#6)55*
:72 /8; ' :724087#2/,:74-88.3$N"=/%#8-32:87CBC/8;#6)55*
/%23/7 E:%-&K08-397LK/8;LN?%245*
@
@
1h Notur o Cod [v005j
28J
IJ&7:5# @K>L G5*4 +/#5- +*55*4/16
0-,## `%<:0-% 1
A8:& E8--8;4b-8;b:%-& E-8;5 1
What is the vector at that spot in the flow
field?
]`%028/ &%#:/%& ' E-8;N-88.3$4-80,2:875*
&%#:/%&N93-249,!#$%%&5*
Steering is desired minus velocity ]`%028/ #2%%/ ' ]`%028/N#3I4&%#:/%&C
A%-80:2"5*
#2%%/N-:9:249,!E8/0%5*
,$$-"b8/0%4#2%%/5*
@
Adopt th low lld xompl so thot th ]`%028/s chong ovr tlm. [Hlnt. try uslng
th thlrd dlmnslon o Prlln nols!j
MO(.2&-( K"L MO(.2&-( K"L
Con you sd o low lld rom o ]c9,?%? |or xompl, try hovlng th ]`%028/s polnt
rom dork to llght colors [or vlc vrsoj.
MO(.2&-( K"N MO(.2&-( K"N
K"L @,( \*' 5.*9:2' K"L @,( \*' 5.*9:2'
|n o momnt, w`r golng to work through th olgorlthm [olong wlth occomponylng
mothmotlcsj ond cod or onothr o Crolg Rynolds`s strlng bhovlors. Poth |ollowlng
[http.//www.rd3d.com/cwr/str/Poth|ollow.htmlj. Bor w con do thls, howvr, w hov
Choptr 6. Autonomous Agnts
282
to spnd som tlm lornlng obout onothr plc o vctor moth thot w sklppd ln Choptr
Jth dot product. W hovn`t ndd lt yt, but lt`s llkly golng to prov qult usul or you
[byond just thls poth-ollowlng xomplj, so w`ll go ovr lt ln dtoll now.
Rmmbr oll th boslc vctor moth w covrd ln Choptr J? Add, subtroct, multlply, ond
dlvld?
Notlc how ln th obov dlogrom, vctor multlpllcotlon lnvolvs multlplylng o vctor by o
scolor volu. 1hls moks sns, whn w wont o vctor to b twlc os lorg [but oclng th
som dlrctlonj, w multlply lt by 2. Whn w wont lt to b hol th slz, w multlply lt by 0.5.
Howvr, thr or two othr mu|t|p||cot|on-|||e oprotlons wlth vctors thot or usul ln
crtoln scnorlosth dot product ond th cross product. |or now w`r golng to ocus on th
dot product, whlch ls dlnd os ollows. Assum vctors +

ond =

.
+

(
:
"
, :
%
)
=

(
>
"
, >
%
)
1HL LO1 PROLC1. +

:
"
>
"
:
%
>
%
|or xompl, l w hov th ollowlng two vctors.
+

(3, 5)
=

(10, 1)
+

3 * 10 5 * 1 30 5 35
Notlc thot th rsult o th dot product ls o scolor volu [o slngl numbrj ond not o vctor.
|n Procsslng, thls would tronslot to.
Iiure .:8
1h Notur o Cod [v005j
283
And l w wr to look ln th guts o th ]`%028/ sourc, w`d lnd o prtty slmpl
lmplmntotlon o thls unctlon.
1hls ls slmpl nough, but why do w nd th dot product, ond whn ls lt golng to b
usul or us ln cod?
On o th mor common uss o th dot product ls to lnd th ongl btwn two vctors.
Anothr woy ln whlch th dot product con b xprssd ls.
+

! +

! ! =

! cos(?)
|n othr words, A dot B ls quol to th mognltud o A tlms mognltud o B tlms cosln o
thto [wlth thto dlnd os the ong|e between the two vectots A ond Bj.
1h two ormulos or dot product con b drlvd rom on onothr wlth trlgonomtry
[http.//mothworld.wolrom.com/LotProduct.htmlj, but or our purposs w con b hoppy wlth
oprotlng on th ossumptlon thot.
+

! +

! ! =

! cos(?)
+

:
"
>
"
:
%
>
%
both hold tru ond thror.
:
"
>
"
:
%
>
%
! +

! ! =

! cos(?)
Now, lt`s stort wlth th ollowlng problm.
W hov th vctors A ond B.
+

(10, 2)
=

(4, 3)
W now hov o sltuotlon ln whlch w know
vrythlng xcpt or thto. W know th
componnts o th vctor ond con
colculot th mognltud o och vctor. W
con thror solv or cosln o thto.
cos(?) ( +

) / ( ! +

! ! =

! )
]`%028/ , ' 7%; ]`%028/46HCJ5*
]`%028/ I ' 7%; ]`%028/4)BC)5*
The PVector class includes a function to
calculate the dot product.
E-8,2 7 ' ,N&824I5*
$3I-:0 E-8,2 &824]`%028/ A5 1
/%23/7 !QAN! ( "QAN" ( FQANF*
@
Iiure .:p
Choptr 6. Autonomous Agnts
284
1o solv or thto, w con tok th lnvrs cosln [otn xprssd os cos|ne
-!
or otccos|nej.
? cos
1
( ( +

) / ( ! +

! ! =

! ) )
Lt`s now do th moth wlth octuol numbrs.
! +

! 10.2
! =

! 5
1hror.
? cos
1
( ( 10 4 2 -3 ) / ( 10.2 5 ) )
? cos
1
( 34 / 51 )
? # 48
$
1h Procsslng vrslon o thls would b.
And, ogoln, l w wr to dlg lnto th guts o th Procsslng sourc cod, w would s o
unctlon thot lmplmnts thls xoct olgorlthm.
A coupl thlngs to not hr.
]`%028/ , ' 7%; ]`%028/4)BC>5*
]`%028/ I ' 7%; ]`%028/4DC6H5*
E-8,2 2<%2, ' ,08#4,N&824I5 = 4,N9,?45 Q IN9,?4555*
#2,2:0 $3I-:0 E-8,2 ,7?-%W%2;%%74]`%028/ A)C ]`%028/ A>5 1
E-8,2 &82 ' A)N&824A>5*
E-8,2 2<%2, ' 4E-8,25 d,2<N,08#4&82 = 4A)N9,?45 Q A>N9,?4555*
/%23/7 2<%2,*
@
Crot o sktch thot dlsploys th ongl
btwn two ]`%028/ objcts.
MO(.2&-( K"W MO(.2&-( K"W
1h Notur o Cod [v005j
285
J. | two vctors [ +

ond =

j or orthogonol [l.. prpndlculorj, th dot product [ +

j
ls quol to 0.
2. | two vctors or unlt vctors, thn th dot product ls slmply quol to cosln o
th ongl btwn thm, l.. +

cos(?) l +

ond =

or o lngth J.
K"N 54', S*%%*8&;< K"N 54', S*%%*8&;<
Now thot w`v got o boslc undrstondlng o th dot product undr our blt, w con rturn
to o dlscusslon o Crolg Rynolds`s poth-ollowlng olgorlthm. Lt`s qulckly clorly somthlng.
W or tolklng obout poth to||ow|ng, not poth t|nd|ng. Pothlndlng rrs to o rsorch toplc
[commonly studld ln ortllclol lntlllgncj thot lnvolvs solvlng or th shortst dlstonc
btwn two polnts, otn ln o moz. Wlth A(&+ ;!''!>/.2 A(&+ ;!''!>/.2, th poth olrody xlsts ond w`r
osklng o vhlcl to ollow thot poth.
Bor w work out th lndlvlduol plcs, lt`s tok o look ot th ovroll olgorlthm or poth
ollowlng, os dlnd by Rynolds.
W`ll lrst dln whot w mon by o poth. 1hr or mony woys w could lmplmnt o poth,
but or us, o slmpl woy wlll b to dln o poth os o srls o connctd polnts.
Iiure .zo
Choptr 6. Autonomous Agnts
286
An vn slmplr poth would b o lln btwn two polnts.
W`r olso golng to consldr o poth to hov o rodlus. | w thlnk o th poth os o rood, th
rodlus dtrmlns th rood`s wldth. Wlth o smollr rodlus, our vhlcls wlll hov to ollow th
poth mor closly, o wldr rodlus wlll ollow thm to stroy o blt mor.
Puttlng thls lnto o closs, w hov.
Iiure .z:: Pcth
Iiure .zz: Simple pcth
0-,## ],2< 1
A Path is only two points, start and end. ]`%028/ #2,/2*
]`%028/ %7&*
A path has a radius, i.e. how wide it is. E-8,2 /,&:3#*
],2<45 1
1h Notur o Cod [v005j
287
Now, lt`s ossum w hov o vhlcl [os dplctd blowj outsld o th poth`s rodlus,
movlng wlth o vloclty.
1h lrst thlng w wont to do ls prdlct, ossumlng o constont vloclty, whr thot vhlcl wlll
b ln th utur.
Onc w hov thot locotlon, lt`s now our job to lnd out th vhlcl`s currnt dlstonc rom
th poth o thot prdlctd locotlon. | lt`s vry or owoy, wll, thn, w`v stroyd rom th
poth ond nd to str bock towords lt. | lt`s clos, thn w`r dolng OK ond or ollowlng
th poth nlcly.
Picking some arbitrary values to initialize
the path
/,&:3# ' >B*
#2,/2 ' 7%; ]`%028/4BC<%:?<2=H5*
%7& ' 7%; ]`%028/4;:&2<C>Q<%:?<2=H5*
@
A8:& &:#$-,"45 1 == \:#$-," 2<% $,2<N
#2/8.%+%:?<24/,&:3#Q>5*
#2/8.%4BC)BB5*
-:7%4#2,/2N!C#2,/2N"C%7&N!C%7&N"5*
#2/8.%+%:?<24)5*
#2/8.%4B5*
-:7%4#2,/2N!C#2,/2N"C%7&N!C%7&N"5*
@
@
Iiure .z
Start by making a copy of the velocity. ]`%028/ $/%&:02 ' A%-N?%245*
Normalize it and look 25 pixels ahead by
scaling the vector up.
$/%&:02N78/9,-:F%45*
$/%&:02N93-24>J5*
Add vector to location to find the predicted
location.
]`%028/ $/%&:02l80 ' ]`%028/N,&&4-80C $/%&:025*
Choptr 6. Autonomous Agnts
288
5o, how do w lnd th dlstonc btwn o polnt ond o lln? 1hls concpt ls ky. 1h dlstonc
btwn o polnt ond o lln ls dlnd os th lngth o th normol btwn thot polnt ond lln.
1h normol ls o vctor thot xtnds rom thot polnt ond ls prpndlculor to th lln.
Lt`s lgur out whot w do know. W know w hov o vctor [coll lt +

j thot xtnds rom th


poth`s stortlng polnt to th vhlcl`s prdlctd locotlon.
W olso know thot w con dln o vctor [coll lt =

j thot polnts rom th stort o th poth to th


nd.
Now, wlth boslc trlgonomtry, w know thot th dlstonc rom th poth`s stort to th normol
polnt ls. RhR F :8.*/H$/&+.
| w knw thto, w could oslly dln thot normol polnt os ollows.
Iiure .z(
]`%028/ , ' ]`%028/N#3I4$/%&:02l80C$,2<N#2,/25*
]`%028/ I ' ]`%028/N#3I4$,2<N%7&C$,2<N#2,/25*
Iiure .z
1h Notur o Cod [v005j
289
And l th dot product hos tought us onythlng, lt`s thot glvn two vctors, w con gt thto,
th ongl btwn.
Whll th obov cod wlll work, thr`s on mor slmplllcotlon w con mok. | you`ll
notlc, th dslrd mognltud or vctor =

ls.
&-5&G*+F:8.*/H$/&+
whlch ls th cod tronslotlon o.
! +

! cos(?)
And l you rcoll.
+

! +

! ! =

! cos(?)
Now, whot l vctor =

ls o unlt vctor, l.. lngth J? 1hn.


+

! +

! 1 cos(?)
or
+

! +

! cos(?)
And whot or w dolng ln our cod? Normollzlng b!
Bcous o thls oct, w con slmplly our cod os.
The distance from START to NORMAL E-8,2 & ' ,N9,?45Q08#42<%2,5*
IN78/9,-:F%45*
Scale PVector b to that distance. IN93-24&5*
The normal point can be found by adding
the scaled version of b to the path's starting
point.
]`%028/ 78/9,-]8:72 ' ]`%028/N,&&4$,2<N#2,/2CI5*
What is theta? The angle between A and B E-8,2 2<%2, ' ]`%028/N,7?-%W%2;%%74,CI5*
IN78/9,-:F%45*
IN93-24,N9,?45Q08#42<%2,55*
]`%028/ 78/9,-]8:72 ' ]`%028/N,&&4$,2<N#2,/2CI5*
IN78/9,-:F%45*
E-8,2 2<%2, ' ]`%028/N,7?-%W%2;%%74,CI5*
IN78/9,-:F%45*
Choptr 6. Autonomous Agnts
290
1hls procss ls commonly known os scolor projctlon." `D` %!)OaP /) &+$ )%('(1 A1!#$%&/!. !; `D` %!)OaP /) &+$ )%('(1 A1!#$%&/!. !;
D !.&! T6 D !.&! T6
Onc w hov th normol polnt olong th poth, w hov to dcld whthr th vhlcl should
str towords th poth ond how. Rynolds`s olgorlthm stots thot th vhlcl should only str
towords th poth l lt stroys byond th poth [l.., l th dlstonc btwn th normol polnt ond
th prdlctd utur locotlon ls grotr thon th poth rodlusj.
We can use the dot product to scale b's
length.
IN93-24,N&824I55*
]`%028/ 78/9,-]8:72 ' ]`%028/N,&&4$,2<N#2,/2CI5*
Iiure .z
Iiure .z;
E-8,2 &:#2,70% ' ]`%028/N&:#24$/%&:02l80C 78/9,-]8:725*
f the vehicle is outside the path, seek the
target.
:E 4&:#2,70% ^ $,2<N/,&:3#5 1
We don't have to work out the desired
velocity and steering force; all that is taken
care of by seek(), which we already wrote in
Example 6.1.
#%%.42,/?%25*
@
1h Notur o Cod [v005j
29J
But whot ls th torgt?
Rynolds`s olgorlthm lnvolvs plcklng o polnt ohod o th normol on th poth [s stp #3
obovj. But or slmpllclty, w could just soy thot th torgt ls th normol ltsl. 1hls wlll work
olrly wll.
5lnc w know th vctor thot dlns th poth [w`r colllng lt B"j, w con lmplmnt
Rynolds`s polnt ohod on th poth" wlthout too much troubl.
Puttlng lt oll togthr, w hov th ollowlng strlng unctlon ln our `%<:0-% closs.
E-8,2 &:#2,70% ' ]`%028/N&:#24$/%&:02l80C 78/9,-]8:725*
:E 4&:#2,70% ^ $,2<N/,&:3#5 1
Seek the normal point on the path. #%%.478/9,-]8:725*
@
Iiure .z8
E-8,2 &:#2,70% ' ]`%028/N&:#24$/%&:02l80C 78/9,-]8:725*
:E 4&:#2,70% ^ $,2<N/,&:3#5 1
Normalize and scale b (pick 25 pixels
arbitrarily).
IN78/9,-:F%45*
IN93-24>J5*
By adding b to normalPoint, we now move
25 pixels ahead on the path.
]`%028/ 2,/?%2 ' ]`%028/N,&&478/9,-]8:72CI5*
#%%.42,/?%25*
@
Choptr 6. Autonomous Agnts
292
IJ&7:5# @K?L O/7:5# :&'" +*55*4/16
Now, you moy notlc obov thot lnstod o uslng oll thot dot product/scolor projctlon cod to
lnd th normol polnt, w lnstod coll o unctlon. ?%2k8/9,-]8:7245. |n coss llk thls, lt`s
usul to brok out th cod thot prorms o spcllc tosk [lndlng o normol polntj lnto o
unctlon thot lt con b usd gnrlcolly ln ony cos whr lt ls rqulrd. 1h unctlon toks
thr ]`%028/s. th lrst dlns o polnt ln Cortslon spoc ond th scond ond thlrd
orgumnts dln o lln sgmnt.
A8:& E8--8;4],2< $5 1
Step 1: Predict the vehicle's future location. ]`%028/ $/%&:02 ' A%-N?%245*
$/%&:02N78/9,-:F%45*
$/%&:02N93-24>J5*
]`%028/ $/%&:02l80 ' ]`%028/N,&&4-80C $/%&:025*
Step 2: Find the normal point along the
path.
]`%028/ , ' $N#2,/2*
]`%028/ I ' $N%7&*
]`%028/ 78/9,-]8:72 ' ?%2k8/9,-]8:724$/%&:02l80C ,C I5*
Step 3: Move a little further along the path
and set a target.
]`%028/ &:/ ' ]`%028/N#3I4IC ,5*
&:/N78/9,-:F%45*
&:/N93-24)B5*
]`%028/ 2,/?%2 ' ]`%028/N,&&478/9,-]8:72C &:/5*
Step 4: f we are off the path, seek that
target in order to stay on the path.
E-8,2 &:#2,70% '
]`%028/N&:#2478/9,-]8:72C $/%&:02l805*
:E 4&:#2,70% ^ $N/,&:3#5 1
#%%.42,/?%25*
@
@
1h Notur o Cod [v005j
293
Whot do w hov so or? W hov o ],2< closs thot dlns o poth os o lln btwn two
polnts. W hov o `%<:0-% closs thot dlns o vhlcl thot con ollow th poth [uslng o
strlng bhovlor to sk o torgt olong th pothj. Whot ls mlsslng?
1ok o dp broth. W`r olmost thr.
Iiure .zp
]`%028/ ?%2k8/9,-]8:724]`%028/ $C ]`%028/ ,C ]`%028/ I5 1
PVector that points from a to p ]`%028/ ,$ ' ]`%028/N#3I4$C ,5*
PVector that points from a to b ]`%028/ ,I ' ]`%028/N#3I4IC ,5*
Using the dot product for scalar projection ,IN78/9,-:F%45*
,IN93-24,$N&824,I55*
Finding the normal point along the line
segment
]`%028/ 78/9,-]8:72 ' ]`%028/N,&&4,C ,I5*
/%23/7 78/9,-]8:72*
@
K"W 54', S*%%*8&;< 8&', ]:%'&Q%( U(<E(;'- K"W 54', S*%%*8&;< 8&', ]:%'&Q%( U(<E(;'-
W`v bullt o grot xompl so or, ys, but lt`s prtty dorn llmltlng. Atr oll, whot l w wont
our poth to b somthlng thot looks mor llk.
Iiure .o
Choptr 6. Autonomous Agnts
294
Whll lt`s tru thot w could mok thls xompl work or o curvd poth, w`r much lss llkly
to nd up ndlng o cool comprss on our orhod l w stlck wlth lln sgmnts. |n th nd,
w con olwoys mploy th som tchnlqu w dlscovrd wlth Box2Lw con drow whotvr
oncy curvd poth w wont ond opproxlmot lt bhlnd th scns wlth slmpl gomtrlc
orms.
5o, whot`s th problm? | w mod poth ollowlng work wlth on lln sgmnt, how do w
mok lt work wlth o srls o connctd lln sgmnts? Lt`s tok o look ogoln ot our vhlcl
drlvlng olong th scrn. 5oy w orrlv ot 5tp 3.
Q&$A 73 U/.8 ( &(12$& A!/.& !. &+$ A(&+6 Q&$A 73 U/.8 ( &(12$& A!/.& !. &+$ A(&+6
1o lnd th torgt, w nd to lnd th normol to th lln sgmnt. But now thot w hov o
srls o lln sgmnts, w hov o srls o normol polnts [s obovj! Whlch on do w
choos? 1h solutlon w`ll mploy ls to plck th normol polnt thot ls [oj closst ond [bj on th
poth ltsl.
| w hov o polnt ond on lnlnltly long lln, w`ll olwoys hov o normol. But, os ln th poth-
ollowlng xompl, l w hov o polnt ond o lln sgmnt, w won`t ncssorlly lnd o normol
thot ls on th lln sgmnt ltsl. 5o l thls hoppns or ony o th sgmnts, w con dlsquolly
thos normols. Onc w or lt wlth normols thot or on th poth ltsl [only two ln th obov
dlogromj, w slmply plck th on thot ls closst to our vhlcl`s locotlon.
Iiure .:
Iiure .z
1h Notur o Cod [v005j
295
|n ordr to wrlt th cod or thls, w`ll hov to xpond our ],2< closs to hov on
V//,"l:#2 o polnts [rothr thon just two, o stort ond on ndj.
Now thot w hov th ],2< closs dlnd, lt`s th vhlcl`s turn to dol wlth multlpl lln
sgmnts. All w dld bor wos lnd th normol or on lln sgmnt. W con now lnd th
normols or oll th lln sgmnts ln o loop.
0-,## ],2< 1
A Path is now an ArrayList of points
(PVector objects).
V//,"l:#2P]`%028/^ $8:72#*
E-8,2 /,&:3#*
],2<45 1
/,&:3# ' >B*
$8:72# ' 7%; V//,"l:#2P]`%028/^45*
@
This function allows us to add points to the
path.
A8:& ,&&]8:724E-8,2 !C E-8,2 "5 1 N
]`%028/ $8:72 ' 7%; ]`%028/4!C"5*
$8:72#N,&&4$8:725*
@
Display the path as a series of points. A8:& &:#$-,"45 1
#2/8.%4B5*
78b:--45*
I%?:7[<,$%45*
E8/ 4]`%028/ A q $8:72#5 1
A%/2%!4AN!CAN"5*
@
%7&[<,$%45*
@
@
E8/ 4:72 : ' B* : P $N$8:72#N#:F%456)* :((5 1
]`%028/ , ' $N$8:72#N?%24:5*
]`%028/ I ' $N$8:72#N?%24:()5*
Choptr 6. Autonomous Agnts
296
1hn w should mok sur th normol polnt ls octuolly btwn polnts , ond I. 5lnc w
know our poth gos rom lt to rlght ln thls xompl, w con tst l th x componnt o
78/9,-]8:72 ls outsld th x componnts o , ond I.
As o llttl trlck, w`ll soy thot l lt`s not wlthln th lln sgmnt, lt`s just prtnd th nd polnt
o thot lln sgmnt ls th normol. 1hls wlll nsur thot our vhlcl olwoys stoys on th poth,
vn l lt stroys out o th bounds o our lln sgmnts.
|lnolly, w`ll nd to mok sur w lnd th normol polnt thot ls closst to our vhlcl. 1o
occompllsh thls, w stort wlth o vry hlgh world rcord" dlstonc ond ltrot through och
normol polnt to s l lt bots th rcord [l.. ls lss thonj. Loch tlm o normol polnt bots th
rcord, th world rcord ls updotd ond th wlnnlng polnt ls stord ln o vorlobl nomd
2,/?%2. At th nd o th loop, w`ll hov th closst normol polnt ln thot vorlobl.
IJ&7:5# @K@L 9&'" +*55*4/16
]`%028/ 78/9,-]8:72 ' ?%2k8/9,-]8:724$/%&:02l80C ,C I5*
Finding the normals for each line segment
:E 478/9,-]8:72N! P ,N! __ 78/9,-]8:72N! ^ IN!5 1
Use the end point of the segment as our
normal point if we can't find one.
78/9,-]8:72 ' IN?%245*
@
]`%028/ 2,/?%2 ' 73--*
1h Notur o Cod [v005j
297
Start with a very high record that can easily
be beaten.
E-8,2 ;8/-&Y%08/& ' )BBBBBB*
E8/ 4:72 : ' B* : P $N$8:72#N#:F%456)* :((5 1
]`%028/ , ' $N$8:72#N?%24:5*
]`%028/ I ' $N$8:72#N?%24:()5*
]`%028/ 78/9,-]8:72 ' ?%2k8/9,-]8:724$/%&:02l80C ,C I5*
:E 478/9,-]8:72N! P ,N! __ 78/9,-]8:72N! ^ IN!5 1
78/9,-]8:72 ' IN?%245*
@
E-8,2 &:#2,70% ' ]`%028/N&:#24$/%&:02l80C 78/9,-]8:725*
f we beat the record, then this should be
our target!
:E 4&:#2,70% P ;8/-&Y%08/&5 1
;8/-&Y%08/& ' &:#2,70%*
2,/?%2 ' 78/9,-]8:72N?%245*
@
@
pdot th poth-ollowlng xompl so thot th poth con go ln ony dlrctlon. [Hlnt.
you`ll nd to us th 9:745 ond 9,!45 unctlon whn dtrmlnlng l th normol polnt
ls lnsld th lln sgmnt.j
:E 478/9,-]8:72N! P aaaa4aaaaCaaaa5 __ 78/9,-]8:72N! ^ aaaa4aaaaCaaaa55 1
78/9,-]8:72 ' IN?%245*
@
MO(.2&-( K"#T MO(.2&-( K"#T
Crot o poth thot chongs ovr tlm. Con th polnts thot dln th poth ltsl hov
thlr own strlng bhovlors?
MO(.2&-( K"## MO(.2&-( K"##
K"#T P*EQ%(O U/-'(E- K"#T P*EQ%(O U/-'(E-
Rmmbr our purpos? 1o broth ll lnto th thlngs thot mov oround our Procsslng
wlndows? By lornlng to wrlt th cod or on outonomous ognt ond bulldlng o srls o
xompls o lndlvlduol bhovlors, hopully our souls l o llttl mor ull. But thls ls no
ploc to stop ond rst on our lourls. W`r just gttlng stortd. Atr oll, thr ls o dpr
purpos ot work hr. Ys, o vhlcl ls o slmulotd blng thot moks dclslons obout how
to sk ond low ond ollow. But whot ls o ll ld olon, wlthout th lov ond support o
Choptr 6. Autonomous Agnts
298
othrs? Our purpos hr ls not only to bulld lndlvlduol bhovlors or our vhlcls, but to put
our vhlcls lnto systms o mony vhlcls ond ollow thos vhlcls to lntroct wlth och
othr.
Lt`s thlnk obout o tlny, crowllng onton slngl ont. An ont ls on outonomous ognt, lt con
prclv lts nvlronmnt [uslng ontnno to gothr lnormotlon obout th dlrctlon ond
strngth o chmlcol slgnolsj ond mok dclslons obout how to mov bosd on thos slgnols.
But con o slngl ont octlng olon bulld o nst, gothr ood, dnd lts qun? An ont ls o
slmpl unlt ond con only prclv lts lmmdlot nvlronmnt. A colony o onts, howvr, ls o
sophlstlcotd complx systm, o suprorgonlsm" ln whlch th componnts work togthr to
occompllsh dllcult ond compllcotd gools.
W wont to tok whot w`v lornd durlng th procss o bulldlng outonomous ognts ln
Procsslng lnto slmulotlons thot lnvolv mony ognts oprotlng ln porolllognts thot hov
on oblllty to prclv not only thlr physlcol nvlronmnt but olso th octlons o thlr llow
ognts, ond thn oct occordlngly. W wont to crot complx systms ln Procsslng.
Whot ls o complx systm? A complx systm ls typlcolly dlnd os o systm thot ls mor
thon th sum o lts ports." Whll th lndlvlduol lmnts o th systm moy b lncrdlbly
slmpl ond oslly undrstood, th bhovlor o th systm os o whol con b hlghly complx,
lntlllgnt, ond dllcult to prdlct. Hr or thr ky prlnclpls o complx systms.
- Q/-A'$ :./&) >/&+ )+!1&H1(.2$ 1$'(&/!.)+/A)6 Q/-A'$ :./&) >/&+ )+!1&H1(.2$ 1$'(&/!.)+/A)6 1hls ls whot w`v bn bulldlng oll
olong. vhlcls thot hov o llmltd prcptlon o thlr nvlronmnt.
- Q/-A'$ :./&) !A$1(&$ /. A(1(''$'6 Q/-A'$ :./&) !A$1(&$ /. A(1(''$'6 1hls ls whot w nd to slmulot ln cod. |or
vry cycl through Procsslng`s &/,;45 loop, och unlt wlll dcld how to mov [to
crot th opporonc o thm oll worklng ln porolllj.
- Q@)&$- () ( >+!'$ $K+/"/&) $-$12$.& A+$.!-$.(6 Q@)&$- () ( >+!'$ $K+/"/&) $-$12$.& A+$.!-$.(6 Out o th lntroctlons btwn
ths slmpl unlts mrgs complx bhovlor, pottrns, ond lntlllgnc. Hr w`r
tolklng obout th rsult w or hoplng or ln our sktchs. Ys, w know thls
hoppns ln notur [ont colonls, trmlts, mlgrotlon pottrns, orthquoks,
snowloks, tc.j, but con w ochlv th som rsult ln our Procsslng sktchs?
|ollowlng or thr oddltlonol oturs o complx systms thot wlll hlp rom th dlscusslon,
os wll os provld guldllns or oturs w wlll wont to lnclud ln our sotwor slmulotlons.
|t`s lmportont to ocknowldg thot thls ls o uzzy st o choroctrlstlcs ond not oll complx
systms hov oll o thm.
- ^!.H'/.$(1/&@6 ^!.H'/.$(1/&@6 1hls ospct o complx systms ls otn cosuolly rrrd to os th
buttrly ct," colnd by mothmotlclon ond mtorologlst Ldword Norton Lornz,
o plonr ln th study o choos thory. |n J96J, Lornz wos runnlng o computr
wothr slmulotlon or th scond tlm ond, prhops to sov o llttl tlm, typd ln o
stortlng volu o 0.506 lnstod o 0.506J27. 1h nd rsult wos compltly dlrnt
rom th lrst rsult o th slmulotlon. |n othr words, th thory ls thot o slngl
buttrly lopplng lts wlngs on th othr sld o th world could cous o mosslv
1h Notur o Cod [v005j
299
wothr shlt ond ruln our wknd ot th boch. W coll lt non-llnor" bcous
thr lsn`t o llnor rlotlonshlp btwn o chong ln lnltlol condltlons ond o
chong ln outcom. A smoll chong ln lnltlol condltlons con hov o mosslv ct
on th outcom. Non-llnor systms or o suprst o chootlc systms. |n th nxt
choptr, w`ll s how vn ln o systm o mony zros ond ons, l w chong just
on blt, th rsult wlll b compltly dlrnt.
- M!-A$&/&/!. (.8 %!!A$1(&/!.6 M!-A$&/&/!. (.8 %!!A$1(&/!.6 On o th thlngs thot otn moks o complx
systm tlck ls th prsnc o both comptltlon ond cooprotlon btwn th
lmnts. |n our upcomlng locklng systm, w wlll hov thr rulsollgnmnt,
cohslon, ond sporotlon. Allgnmnt ond cohslon wlll osk th lmnts to
cooprot"l.. work togthr to stoy togthr ond mov togthr. 5porotlon,
howvr, wlll osk th lmnts to compt" or spoc. As w gt to th locklng
systm, try toklng out th cooprotlon or th comptltlon ond you`ll s how you
or lt wlthout complxlty. Comptltlon ond cooprotlon or ound ln llvlng
complx systms, but not ln non-llvlng complx systms llk th wothr.
- U$$8"(%J6 U$$8"(%J6 Complx systms otn lnclud o dbock loop whr th th output
o th systm ls d bock lnto th systm to lnlunc lts bhovlor ln o posltlv or
ngotlv dlrctlon. Lt`s soy you drlv to work och doy bcous th prlc o gos
ls low. |n oct, vryon drlvs to work. 1h prlc o gos gos up os dmond
bglns to xcd supply. You, ond vryon ls, dcld to tok th troln to work
bcous drlvlng ls too xpnslv. And th prlc o gos dcllns os th dmond
dcllns. 1h prlc o gos ls both th lnput o th systm [dtrmlnlng whthr
you choos to drlv or rld th trolnj ond th output [th dmond thot rsults rom
your cholcj. | should not thot conomlc modls [llk supply/dmond, th stock
morktj or on xompl o o humon complx systm. Othrs lnclud ods ond
trnds, lctlons, crowds, ond trolc low.
Complxlty wlll srv os o thm or th rmolnlng contnt ln thls book. |n thls choptr, w`ll
bgln by oddlng on mor otur to our `%<:0-% closs. on oblllty to look ot nlghborlng
vhlcls.
K"## e.*:Q b(,4I&*.- ^*.D V('H- ;*' .:; &;'* (42, K"## e.*:Q b(,4I&*.- ^*.D V('H- ;*' .:; &;'* (42,
*',(._ *',(._
A group ls crtolnly not o nw concpt. W`v don thls borln Choptr 4, whr w
dvlopd o romwork or monoglng collctlons o portlcls ln o ],/2:0-%["#2%9 closs.
1hr, w stord o llst o portlcls ln on V//,"l:#2. W`ll do th som thlng hr. stor o
bunch o `%<:0-% objcts ln on V//,"l:#2.
Choptr 6. Autonomous Agnts
300
Now whn lt coms tlm to dol wlth oll th vhlcls ln &/,;45, w slmply loop through oll o
thm ond coll th ncssory unctlons.
OK, so moyb w wont to odd o bhovlor, o orc to b opplld to oll th vhlcls. 1hls could
b sklng th mous.
But thot`s on lndlvlduol bhovlor. W`v olrody spnt thlrty-odd pogs worrylng obout
lndlvlduol bhovlors. W`r hr bcous w wont to opply o group bhovlor. Lt`s bgln wlth
sporotlon, o bhovlor thot commonds, Avold collldlng wlth your nlghbors!"
|s thot rlght? |t sounds good, but lt`s not. Whot`s mlsslng? |n th cos o sk, w sold, 5k
983#%e ond 983#%f." |n th cos o sporot, w`r soylng sporot rom evetyone e|se."
Who ls vryon ls? |t`s th llst o oll th othr vhlcls.
1hls ls th blg lop byond whot w dld bor wlth portlcl systms. |nstod o hovlng och
lmnt [portlcl or vhlclj oprot on lts own, w`r now soylng, Hy you, th vhlcl!
Whn lt coms tlm or you to oprot, you nd to oprot wlth on owornss o vryon
ls. 5o |`m golng to go ohod ond poss you th V//,"l:#2 o vryon ls."
1hls ls how w`v moppd out #%23$45 ond &/,;45 to dol wlth o group bhovlor.
Declare an ArrayList of Vehicle objects. V//,"l:#2P`%<:0-%^ A%<:0-%#*
A8:& #%23$45 1
nitialize and fill the ArrayList with a bunch of
Vehicles.
A%<:0-%# ' 7%; V//,"l:#2P`%<:0-%^*
E8/ 4:72 : ' B* : P )BB* :((5 1
A%<:0-%#N,&&47%; `%<:0-%4/,7&894;:&2<5C/,7&894<%:?<2555*
@
@
A8:& &/,;451
E8/ 4`%<:0-% A q A%<:0-%#5 1
AN3$&,2%45*
AN&:#$-,"45*
@
@
AN#%%.4983#%eC983#%f5*
AN#%$,/,2%45*
AN#%$,/,2%4A%<:0-%#5*
1h Notur o Cod [v005j
30J
O cours, thls ls just th bglnnlng. 1h
rol work hoppns lnsld th #%$,/,2%45
unctlon ltsl. Lt`s lgur out how w wont
to dln sporotlon. Rynolds stots.
5tr to ovold crowdlng." |n othr words, l
o glvn vhlcl ls too clos to you, str
owoy rom thot vhlcl. 5ound omlllor? Rmmbr th sk bhovlor whr o vhlcl strs
towords o torgt? Rvrs thot orc ond w hov th l bhovlor.
But whot l mor thon on vhlcl ls too
clos? |n thls cos, w`ll dln sporotlon
os th ovrog o oll th vctors polntlng
owoy rom ony clos vhlcls.
Lt`s bgln to wrlt th cod. As w just
workd out, w`r wrltlng o unctlon colld
#%$,/,2%45 thot rclvs on V//,"l:#2 o
Vhlcl objcts os on orgumnt.
|nsld thls unctlon, w`r golng to loop through oll o th vhlcls ond s l ony or too
clos.
V//,"l:#2P`%<:0-%^ A%<:0-%#*
A8:& #%23$45 1
#:F%4H>BC>DB5*
A%<:0-%# ' 7%; V//,"l:#2P`%<:0-%^45*
E8/ 4:72 : ' B* : P )BB* :((5 1
A%<:0-%#N,&&47%; `%<:0-%4/,7&894;:&2<5C/,7&894<%:?<2555*
@
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
E8/ 4`%<:0-% A q A%<:0-%#5 1
This is really the only new thing we're
doing in this section. We're asking a
Vehicle object to examine all the other
vehicles in the process of calculating a
separation force.
L-.$0&)&/$*L$H2:'$.+,
AN3$&,2%45*
AN&:#$-,"45*
@
@
Iiure .
Iiure .(
A8:& #%$,/,2% 4V//,"l:#2P`%<:0-%^ A%<:0-%#5 1
@
Choptr 6. Autonomous Agnts
302
Notlc how ln th obov cod, w or not only chcklng l th dlstonc ls lss thon o dslrd
sporotlon [l.. too clos!j, but olso l th dlstonc ls grotr thon zro. 1hls ls o llttl trlck thot
moks sur w don`t osk o vhlcl to sporot rom ltsl. Rmmbr, oll th vhlcls or ln
th V//,"l:#2, so l you orn`t corul you`ll b comporlng och vhlcl to ltsl!
Onc w know thot two vhlcls or too clos, w nd to mok o vctor thot polnts owoy
rom th ondlng vhlcl.
1hls ls not nough. W hov thot vctor now, but w nd to mok sur w colculot th
ovrog o oll vctors polntlng owoy rom clos vhlcls. How do w comput ovrog? W
odd up oll th vctors ond dlvld by th totol.
This variable specifies how close is too
close.
E-8,2 &%#:/%&#%$,/,2:87 ' >B*
E8/ 4`%<:0-% 82<%/ q A%<:0-%#5 1
E-8,2 & ' ]`%028/N&:#24-80,2:87C 82<%/N-80,2:875*
:E 44& ^ B5 mm 4& P &%#:/%&#%$,/,2:8755 1
What is the distance between me and
another Vehicle?
Any code here will be executed if the
Vehicle is within 20 pixels.
@
@
:E 44& ^ B5 mm 4& P &%#:/%&#%$,/,2:8755 1
]`%028/ &:EE ' ]`%028/N#3I4-80,2:87C 82<%/N-80,2:875*
&:EEN78/9,-:F%45*
@
A PVector pointing away from the other's
location
Start with an empty PVector. MN$:/8) .45 " #$! MN$:/8)*+,
2#/ :84#/ " ?,
We have to keep track of how many
Vehicles are too close.
E8/ 4`%<:0-% 82<%/ q A%<:0-%#5 1
E-8,2 & ' ]`%028/N&:#24-80,2:87C 82<%/N-80,2:875*
:E 44& ^ B5 mm 4& P &%#:/%&#%$,/,2:8755 1
MN$:/8) 1299 " MN$:/8)-.46*'8:&/28#J 8/H$)-'8:&/28#+,
&:EEN78/9,-:F%45*
Add all the vectors together and increment
the count.
.45-&11*1299+,
08372((*
@
@
1h Notur o Cod [v005j
303
Onc w hov th ovrog vctor [stord ln th ]`%028/ objct sum"j, thot ]`%028/ con b
scold to moxlmum spd ond bcom our dslrd vlocltyw des|te to mov ln thot
dlrctlon ot moxlmum spd! And onc w hov th dslrd vloclty, lt`s th som old
Rynolds story. strlng quols dslrd mlnus vloclty.
Lt`s s th unctlon ln lts ntlrty. 1hr or two oddltlonol lmprovmnts, notd ln th
cod commnts.
IJ&7:5# @KAL R)*(: E#"&N/*)L O#:&)&'/*1
We have to make sure we found at least
one close vehicle. We don't want to bother
doing anything if nothing is too close (not to
mention we can't divide by zero!)
29 *:84#/ Q ?+ O
.45-12L*:84#/+,
P
:E 408372 ^ B5 1
#39N&:A4083725*
Scale average to maxspeed (this becomes
desired).
#39N#%2d,?49,!#$%%&5*
Reynolds's steering formula ]`%028/ #2%%/ ' ]`%028/N#3I4#39CA%-5*
#2%%/N-:9:249,!E8/0%5*
Apply the force to the Vehicle's
acceleration.
,$$-"b8/0%4#2%%/5*
@
A8:& #%$,/,2% 4V//,"l:#2P`%<:0-%^ A%<:0-%#5 1
Choptr 6. Autonomous Agnts
304
Note how the desired separation is based
on the Vehicle's size.
9'8&/ 1$.2)$1.$0&)&/28# " )F>,
]`%028/ #39 ' 7%; ]`%028/45*
:72 08372 ' B*
E8/ 4`%<:0-% 82<%/ q A%<:0-%#5 1
E-8,2 & ' ]`%028/N&:#24-80,2:87C 82<%/N-80,2:875*
:E 44& ^ B5 mm 4& P &%#:/%&#%$,/,2:8755 1
]`%028/ &:EE ' ]`%028/N#3I4-80,2:87C 82<%/N-80,2:875*
&:EEN78/9,-:F%45*
What is the magnitude of the PVector
pointing away from the other vehicle? The
closer it is, the more we should flee. The
farther, the less. So we divide by the
distance to weight it appropriately.
1299-12L*1+,
#39N,&&4&:EE5*
08372((*
@
@
:E 408372 ^ B5 1
#39N&:A4083725*
#39N78/9,-:F%45*
#39N93-249,!#$%%&5*
]`%028/ #2%%/ ' ]`%028/N#3I4#39C A%-5*
#2%%/N-:9:249,!E8/0%5*
,$$-"b8/0%4#2%%/5*
@
@
Rwrlt #%$,/,2%45 to work ln th opposlt oshlon [cohslon"j. | o vhlcl ls byond
o crtoln dlstonc, str towords thot vhlcl. 1hls wlll kp th group togthr. [Not
thot ln o momnt, w`r golng to look ot whot hoppns whn w hov both cohslon
ond sporotlon ln th som slmulotlon.j
MO(.2&-( K"#0 MO(.2&-( K"#0
1h Notur o Cod [v005j
305
Add th sporotlon orc to poth ollowlng to crot o slmulotlon o Rynolds`s
Crowd Poth |ollowlng."
MO(.2&-( K"#= MO(.2&-( K"#=
K"#0 P*E)&;4'&*;- K"#0 P*E)&;4'&*;-
1h prvlous two xrclss hlnt ot whot ls prhops th most lmportont ospct o thls
choptr. Atr oll, whot ls o Procsslng sktch wlth on strlng orc compord to on wlth
mony? How could w vn bgln to slmulot mrgnc ln our sktchs wlth only on rul?
1h most xcltlng ond lntrlgulng bhovlors wlll com rom mlxlng ond motchlng multlpl
strlng orcs, ond w`ll nd o mchonlsm or dolng so.
You moy b thlnklng, Luh, thls ls nothlng nw. W do thls oll th tlm." You would b rlght.
|n oct, w dld thls os orly os Choptr 2.
Hr w hov o movr thot rsponds to two orcs. 1hls oll works nlcly bcous o th woy
w dslgnd th d8A%/ closs to occumulot th orc vctors lnto lts occlrotlon vctor. |n
thls choptr, howvr, our orcs stm rom lntrnol dslrs o th movrs [now colld
vhlclsj. And thos dslrs con b wlghtd. Lt`s consldr o sktch whr oll vhlcls
hov two dslrs.
- Q$$J &+$ -!:)$ '!%(&/!.6 Q$$J &+$ -!:)$ '!%(&/!.6
- Q$A(1(&$ ;1!- (.@ 0$+/%'$) &+(& (1$ &!! %'!)$6 Q$A(1(&$ ;1!- (.@ 0$+/%'$) &+(& (1$ &!! %'!)$6
]`%028/ ;:7& ' 7%; ]`%028/4BNBB)CB5*
]`%028/ ?/,A:2" ' 7%; ]`%028/4BCBN)5*
98A%/N,$$-"b8/0%4;:7&5*
98A%/N,$$-"b8/0%4?/,A:2"5*
Choptr 6. Autonomous Agnts
306
W mlght bgln by oddlng o unctlon to th `%<:0-% closs thot monogs oll o th bhovlors.
Lt`s coll lt ,$$-"W%<,A:8/#45.
Hr w s how o slngl unctlon toks cor o colllng th othr unctlons thot opply th
orcs#%$,/,2%45 ond #%%.45. W could stort mucklng oround wlth thos unctlons ond s
l w con odjust th strngth o th orcs thy or colculotlng. But lt would b oslr or us to
osk thos unctlons to rturn th orcs so thot w con odjust thlr strngth bor opplylng
thm to th vhlcl`s occlrotlon.
Lt`s look ot how th sk unctlon chongd.
1hls ls o subtl chong, but lncrdlbly lmportont or us. lt ollows us to oltr th strngth o
ths orcs ln on ploc.
A8:& ,$$-"W%<,A:8/#4V//,"l:#2P`%<:0-%^ A%<:0-%#5 1
#%$,/,2%4A%<:0-%#5*
#%%.47%; ]`%028/4983#%eC983#%f55*
@
A8:& ,$$-"W%<,A:8/#4V//,"l:#2P`%<:0-%^ A%<:0-%#5 1
]`%028/ #%$,/,2% ' #%$,/,2%4A%<:0-%#5*
]`%028/ #%%. ' #%%.47%; ]`%028/4983#%eC983#%f55*
We have to apply the force here since
seek() and separate() no longer do so.
,$$-"b8/0%4#%$,/,2%5*
,$$-"b8/0%4#%%.5*
@
]`%028/ #%%.4]`%028/ 2,/?%25 1
]`%028/ &%#:/%& ' ]`%028/N#3I42,/?%2C-805*
&%#:/%&N78/9,-:F%45*
&%#:/%&N93-249,!#$%%&5*
]`%028/ #2%%/ ' ]`%028/N#3I4&%#:/%&CA%-5*
#2%%/N-:9:249,!E8/0%5*
nstead of applying the force we return the
PVector.
,$$-"b8/0%4#2%%/5*
/%23/7 #2%%/*
@
1h Notur o Cod [v005j
307
IJ&7:5# @KBL ,*7E/1/16 8'##)/16 E#"&N/*)8L O##3 &1- 8#:&)&'#
A8:& ,$$-"W%<,A:8/#4V//,"l:#2P`%<:0-%^ A%<:0-%#5 1
]`%028/ #%$,/,2% ' #%$,/,2%4A%<:0-%#5*
]`%028/ #%%. ' #%%.47%; ]`%028/4983#%eC983#%f55*
These values can be whatever you want
them to be! They can be variables that are
customized for each vehicle, or they can
change over time.
.$0&)&/$-54'/*D-=+,
.$$(-54'/*?-=+,
,$$-"b8/0%4#%$,/,2%5*
,$$-"b8/0%4#%%.5*
@
Rdo Lxompl 6.8 so thot th bhovlor wlghts or not constonts. Whot hoppns l
thy chong ovr tlm [occordlng to o sln wov or Prlln nolsj? Or l som vhlcls
or mor concrnd wlth sklng ond othrs mor concrnd wlth sporotlng? Con
you lntroduc othr strlng bhovlors os wll?
MO(.2&-( K"#> MO(.2&-( K"#>
K"#= S%*23&;< K"#= S%*23&;<
|locklng ls on group onlmol bhovlor thot ls choroctrlstlc o mony llvlng croturs, such os
blrds, lsh, ond lnscts. |n J986, Crolg Rynolds crotd o computr slmulotlon o locklng
bhovlor ond documntd th olgorlthm ln hls popr, |locks, Hrds, ond 5chools. A
Llstrlbutd Bhovlorol Modl." Rcrotlng thls slmulotlon ln Procsslng wlll brlng togthr
oll th concpts ln thls choptr.
J. e w||| use the steet|ng totce totmu|o (steet des|ted - ve|oc|tyI to |mp|ement the
tu|es ot t|oc||ng.
2. 7hese steet|ng totces w||| be gtoup behov|ots ond tequ|te eoch veh|c|e to |oo| ot
o|| the othet veh|c|es.
3. e w||| comb|ne ond we|ght mu|t|p|e totces.
4. 7he tesu|t w||| be o comp|ex system|nte|||gent gtoup behov|ot w||| emetge ttom
the s|mp|e tu|es ot t|oc||ng w|thout the ptesence ot o centto||zed system ot
|eodet.
1h good nws ls, w`v olrody don ltms J through 3 ln thls choptr, so thls sctlon wlll
b obout just puttlng lt oll togthr ond slng th rsult.
Choptr 6. Autonomous Agnts
308
Bor w bgln, | should mntlon thot w`r golng to chong th nom o our `%<:0-% closs
[yt ogolnj. Rynolds uss th trm bold" [o mod-up word thot rrs to o blrd-llk objctj to
dscrlb th lmnts o o locklng systm ond w wlll do th som.
Lt`s tok on ovrvlw o th thr ruls o locklng.
J. Q$A(1(&/!. Q$A(1(&/!. [olso known os ovoldonc"j. 5tr to ovold collldlng wlth your
nlghbors.
2. D'/2.-$.& D'/2.-$.& [olso known os copy"j. 5tr ln th som dlrctlon os your nlghbors.
3. M!+$)/!. M!+$)/!. [olso known os cntr"j. 5tr towords th cntr o your nlghbors [stoy
wlth th groupj.
Just os w dld wlth our sporot ond sk xompl, w`ll wont our W8:& objcts to hov o
slngl unctlon thot monogs oll th obov bhovlors. W`ll coll thls unctlon E-80.45.
Now, lt`s just o mottr o lmplmntlng th thr ruls. W dld sporotlon bor, lt`s ldntlcol
to our prvlous xompl. Lt`s tok o look ot ollgnmnt, or strlng ln th som dlrctlon os
Iiure .
A8:& E-80.4V//,"l:#2PW8:&^ I8:&#5 1
The three flocking rules ]`%028/ #%$ ' #%$,/,2%4I8:&#5*
]`%028/ ,-: ' ,-:?74I8:&#5*
]`%028/ 08< ' 08<%#:874I8:&#5*
Arbitrary weights for these forces (Try
different ones!)
#%$N93-24)NJ5*
,-:N93-24)NB5*
08<N93-24)NB5*
Applying all the forces ,$$-"b8/0%4#%$5*
,$$-"b8/0%4,-:5*
,$$-"b8/0%408<5*
@
1h Notur o Cod [v005j
309
your nlghbors. As wlth oll o our strlng bhovlors, w`v got to boll down thls concpt
lnto o dslr. th bold`s dslrd vloclty ls th ovrog vloclty o lts nlghbors.
5o our olgorlthm ls to colculot th ovrog vloclty o oll th othr bolds ond st thot to
dslrd.
1h obov ls prtty good, but lt`s mlsslng on rothr cruclol dtoll. On o th ky prlnclpls
bhlnd complx systms llk locklng ls thot th lmnts [ln thls cos, boldsj hov short-
rong rlotlonshlps. 1hlnklng obout onts ogoln, lt`s prtty osy to lmogln on ont blng obl
to sns lts lmmdlot nvlronmnt, but lss so on ont hovlng on owornss o whot
onothr ont ls dolng hundrds o t owoy. 1h oct thot th onts con prorm such
complx collctlv bhovlor rom only ths nlghborlng rlotlonshlps ls whot moks thm
so xcltlng ln th lrst ploc.
|n our ollgnmnt unctlon, w`r toklng th ovrog vloclty o oll th bolds, whros w
should rolly only b looklng ot th bolds wlthln o crtoln dlstonc. 1hot dlstonc thrshold
ls up to you, o cours. You could dslgn bolds thot con s only twnty plxls owoy or
bolds thot con s o hundrd plxls owoy.
]`%028/ ,-:?7 4V//,"l:#2PW8:&^ I8:&#5 1
Add up all the velocities and divide by the
total to calculate the average velocity.
]`%028/ #39 ' 7%; ]`%028/4BCB5*
E8/ 4W8:& 82<%/ q I8:&#5 1
#39N,&&482<%/NA%-80:2"5*
@
#39N&:A4I8:&#N#:F%455*
We desire to go in that direction at
maximum speed.
#39N#%2d,?49,!#$%%&5*
Reynolds's steering force formula ]`%028/ #2%%/ ' ]`%028/N#3I4#39CA%-80:2"5*
#2%%/N-:9:249,!E8/0%5*
/%23/7 #2%%/*
@
Choptr 6. Autonomous Agnts
3J0
Much llk w dld wlth sporotlon [only colculotlng o orc or othrs wlthln o crtoln dlstoncj,
w`ll wont to do th som wlth ollgnmnt [ond cohslonj.
Iiure .
]`%028/ ,-:?7 4V//,"l:#2PW8:&^ I8:&#5 1
This is an arbitrary value and could vary
from boid to boid.
E-8,2 7%:?<I8/&:#2 ' JB*
]`%028/ #39 ' 7%; ]`%028/4BCB5*
:72 08372 ' B*
E8/ 4W8:& 82<%/ q I8:&#5 1
E-8,2 & ' ]`%028/N&:#24-80,2:87C82<%/N-80,2:875*
:E 44& ^ B5 mm 4& P 7%:?<I8/&:#255 1
#39N,&&482<%/NA%-80:2"5*
For an average, we need to keep track of
how many boids are within the distance.
08372((*
@
@
:E 408372 ^ B5 1
#39N&:A4083725*
#39N78/9,-:F%45*
#39N93-249,!#$%%&5*
]`%028/ #2%%/ ' ]`%028/N#3I4#39CA%-80:2"5*
#2%%/N-:9:249,!E8/0%5*
/%23/7 #2%%/*
f we don't find any close boids, the steering
force is zero.
@ %-#% 1
/%23/7 7%; ]`%028/4BCB5*
@
@
1h Notur o Cod [v005j
3JJ
|lnolly, w or rody or cohslon. Hr our cod ls vlrtuolly ldntlcol to thot or
ollgnmntonly lnstod o colculotlng th ovrog vloclty o th bold`s nlghbors, w wont
to colculot th ovrog locotlon o th bold`s nlghbors [ond us thot os o torgt to skj.
|t`s olso worth toklng th tlm to wrlt o closs colld b-80., whlch wlll b vlrtuolly ldntlcol
to th ],/2:0-%["#2%9 closs w wrot ln Choptr 4 wlth only on tlny chong. Whn w
coll /3745 on och W8:& objct [os w dld to och ],/2:0-% objctj, w`ll poss ln o
rrnc to th ntlr V//,"l:#2 o bolds.
Con you wrlt th obov cod so thot
bolds con only s othr bolds thot or
octuolly wlthln thlr prlphrol" vlslon
[os l thy hod ysj?
MO(.2&-( K"#? MO(.2&-( K"#?
]`%028/ 08<%#:87 4V//,"l:#2PW8:&^ I8:&#5 1
E-8,2 7%:?<I8/&:#2 ' JB*
]`%028/ #39 ' 7%; ]`%028/4BCB5*
:72 08372 ' B*
E8/ 4W8:& 82<%/ q I8:&#5 1
E-8,2 & ' ]`%028/N&:#24-80,2:87C82<%/N-80,2:875*
:E 44& ^ B5 mm 4& P 7%:?<I8/&:#255 1
Adding up all the others' locations #39N,&&482<%/N-80,2:875*
08372((*
@
@
:E 408372 ^ B5 1
#39N&:A4083725*
Here we make use of the seek() function
we wrote in Example 6.8. The target we
seek is the average location of our
neighbors.
)$/4)# .$$(*.45+,
@ %-#% 1
/%23/7 7%; ]`%028/4BCB5*
@
@
Choptr 6. Autonomous Agnts
3J2
And our moln progrom wlll look llk.
IJ&7:5# @KCL G5*03/16
0-,## b-80. 1
V//,"l:#2PW8:&^ I8:&#*
b-80.45 1
I8:&# ' 7%; V//,"l:#2PW8:&^45*
@
A8:& /3745 1
E8/ 4W8:& I q I8:&#5 1
Each Boid object must know about all the
other Boids.
6-)4#*6821.+,
@
@
A8:& ,&&W8:&4W8:& I5 1
I8:&#N,&&4I5*
@
@
A Flock object manages the entire group. b-80. E-80.*
A8:& #%23$45 1
#:F%4HBBC>BB5*
E-80. ' 7%; b-80.45*
E8/ 4:72 : ' B* : P )BB* :((5 1
W8:& I ' 7%; W8:&4;:&2<=>C<%:?<2=>5*
The Flock starts out with 100 Boids. E-80.N,&&W8:&4I5*
@
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
E-80.N/3745*
@
1h Notur o Cod [v005j
3J3
Combln locklng wlth som othr strlng bhovlors.
MO(.2&-( K"#K MO(.2&-( K"#K
|n hls book 1h Computot|ono| Beouty
ot Notute [M|1 Prss, 2000j, Gory |lok
dscrlbs o ourth rul or locklng.
Vlw. mov lotrolly owoy rom ony
bold thot blocks th vlw." Hov your
bolds ollow thls rul.
MO(.2&-( K"#L MO(.2&-( K"#L
Crot o locklng slmulotlon whr oll o th poromtrs [sepotot|on we|ght, cohes|on
we|ght, o||gnment we|ght, mox|mum totce, mox|mum speedj chong ovr tlm. 1hy
could b controlld by Prlln nols or by usr lntroctlon. [|or xompl, you could
us o llbrory such os controlp5 [http.//www.sojomo.d/llbrorls/controlP5/j to tl th
volus to slldr posltlons.j
MO(.2&-( K"#N MO(.2&-( K"#N
Vlsuollz th lock ln on ntlrly dlrnt woy.
MO(.2&-( K"#W MO(.2&-( K"#W
Choptr 6. Autonomous Agnts
3J4
K"#> !%<*.&',E&2 M++&2&(;2/ ^*.D 6,/ 9*(- E/ ij^klJ K"#> !%<*.&',E&2 M++&2&(;2/ ^*.D 6,/ 9*(- E/ ij^klJ
.:; -* -%*8%/7_ .:; -* -%*8%/7_
| would llk to hld th dork truth bhlnd w`v just don, bcous | would llk you to b
hoppy ond llv o ulllllng ond monlngul ll. But | olso would llk to b obl to slp ot nlght
wlthout worrylng obout you so much. 5o lt ls wlth o hovy hort thot | must brlng up thls toplc.
Group bhovlors or wondrul. But thy con b slow, ond th mor lmnts ln th group,
th slowr thy con b. suolly, whn w tolk obout Procsslng sktchs runnlng slowly, lt`s
bcous drowlng to th scrn con b slowth mor you drow, th slowr your sktch runs.
1hls ls octuolly o cos, howvr, whr th slownss drlvs rom th olgorlthm ltsl. Lt`s
dlscuss.
Computr sclntlsts clossly olgorlthms wlth somthlng colld Blg O nototlon," whlch
dscrlbs th lclncy o on olgorlthm. how mony computotlonol cycls dos lt rqulr to
complt? Lt`s consldr o slmpl onolog sorch problm. You hov o boskt contolnlng on
hundrd chocolot trots, only on o whlch ls pur dork chocolot. 1hot`s th on you wont
to ot. 1o lnd lt, you plck th chocolots out o th boskt on by on. 5ur, you mlght b
lucky ond lnd lt on th lrst try, but ln th worst-cos scnorlo you hov to chck oll on
hundrd bor you lnd th dork chocolot. 1o lnd on thlng ln on hundrd, you hov to
chck on hundrd thlngs [or to lnd on thlng ln N thlngs, you hov to chck N tlms.j Your
Blg O Nototlon ls N. 1hls, lncldntolly, ls th Blg O Nototlon thot dscrlbs our slmpl portlcl
systm. | w hov N portlcls, w hov to run ond dlsploy thos portlcls N tlms.
Now, lt`s thlnk obout o group bhovlor [such os locklngj. |or vry W8:& objct, w hov to
chck vry othr W8:& objct [or lts vloclty ond locotlonj. Lt`s soy w hov on hundrd
bolds. |or bold #J, w nd to chck on hundrd bolds, or bold #2, w nd to chck on
hundrd bolds, ond so on ond so orth. |or on hundrd bolds, w nd to prorm on
hundrd tlms on hundrd chcks, or tn thousond. No problm. computrs or ost ond con
do thlngs tn thousond tlms prtty oslly. Lt`s try on thousond.
J,000 x J,000 J,000,000 cycls.
OK, thls ls rothr slow, but stlll somwhot monogobl. Lt`s try J0,000 lmnts.
J0,000 x J0,000 lmnts J00,000,000 cycls.
Now, w`r rolly gttlng slow. Rolly, rolly, rolly slow.
Notlc somthlng odd? As th numbr o lmnts lncross by o octor o J0, th numbr o
rqulrd cycls lncross by o octor o J00. Or os th numbr o lmnts lncross by o
octor o N, th cycls lncros by o octor o N tlms N. 1hls ls known os Blg O Nototlon N-
5quord.
| know whot you or thlnklng. You or thlnklng. No problm, wlth locklng, w only nd to
consldr th bolds thot or clos to othr bolds. 5o vn l w hov J,000 bolds, w con just
look ot, soy, th 5 closst bolds ond thn w only hov 5,000 cycls." You pous or o
1h Notur o Cod [v005j
3J5
momnt, ond thn stort thlnklng. 5o or och bold | just nd to chck oll th bolds ond lnd
th lv closst ons ond |`m good!" 5 th cotch-22? Lvn l w only wont to look ot th
clos ons, th only woy to know whot th clos ons or would b to chck oll o thm.
Or ls thr onothr woy?
Lt`s tok o numbr thot w mlght octuolly wont to us, but would stlll run too slowly. 2,000
[4,000,000 cycls rqulrdj.
Whot l w could dlvld th scrn lnto o grld? W would tok oll 2,000 bolds ond osslgn
och bold to o cll wlthln thot grld. W would thn b obl to look ot och bold ond
compor lt to lts nlghbors wlthln thot cll ot ony glvn momnt. |mogln o J0 x J0 grld. |n o
systm o 2,000 lmnts, on ovrog, opproxlmotly 20 lmnts would b ound ln och
cll [20 x J0 x J0 2,000j. Loch cll would thn rqulr 20 x 20 400 cycls. Wlth J00 clls,
w`d hov J00 x 400 40,000 cycls, o mosslv sovlngs ovr 4,000,000.
1hls tchnlqu ls known os bln-lottlc spotlol subdlvlslon" ond ls outllnd ln mor dtoll ln
[surprls, surprlsj Rynolds`s 2000 popr, |ntroctlon wlth Groups o Autonomous
Choroctrs" [http.//www.rd3d.com/cwr/poprs/2000/plp.pdj. How do w lmplmnt such
on olgorlthm ln Procsslng? On woy ls to kp multlpl V//,"l:#2s. On V//,"l:#2 would
kp trock o oll th bolds, just llk ln our locklng xompl.
|n oddltlon to thot V//,"l:#2, w stor on oddltlonol rrnc to och W8:& objct ln o
two-dlmnslonol V//,"l:#2. |or och cll ln th grld, thr ls on V//,"l:#2 thot trocks th
objcts ln thot cll.
Iiure .;
V//,"l:#2PW8:&^ I8:&#*
Choptr 6. Autonomous Agnts
3J6
|n th moln &/,;45 loop, och W8:& objct thn rglstrs ltsl ln th opproprlot cll
occordlng to lts locotlon.
1hn whn lt coms tlm to hov th bolds chck or nlghbors, thy con look ot only thos ln
thlr portlculor cll [ln truth, w olso nd to chck nlghborlng clls to dol wlth bordr
cossj.
IJ&7:5# @K;DL S/1`5&''/0# 8:&'/&5 8(E-/N/8/*1
W`r only covrlng th boslcs hr, or th ull cod, chck th book`s wbslt.
Now, thr or crtolnly lows wlth thls systm. Whot l oll th bolds congrgot ln th cornr
ond llv ln th som cll? 1hn don`t w hov to chck oll 2,000 ogolnst oll 2,000?
1h good nws ls thot thls nd or optlmlzotlon ls o common on ond thr or o wld
vorlty o slmllor tchnlqus out thr. |or us, lt`s llkly thot o boslc opprooch wlll b good
nough [ln most coss, you won`t nd on ot oll.j |or onothr, mor sophlstlcotd opprooch,
chck out toxlcllbs' Octr xompls [http.//toxlcllbs.org/20J0/02/nw-pockog-slmutlls/j.
V//,"l:#2PW8:&^KLKL ?/:&*
:72 08-397 ' :724I8:&N!5 = /%#8-32:87*
:72 /8; ' :724I8:&N"5 =/%#8-32:87*
?/:&K08-397LK/8;LN,&&4I8:&5*
:72 08-397 ' :724I8:&N!5 = /%#8-32:87*
:72 /8; ' :724I8:&N"5 =/%#8-32:87*
I8:&NE-80.4I8:&#5*
nstead of looking at all the boids, just this
cell
I8:&NE-80.4?/:&K08-397LK/8;L5*
K"#? ! S(8 V4-' X*'(-D FQ'&E&c4'&*; @.&23- K"#? ! S(8 V4-' X*'(-D FQ'&E&c4'&*; @.&23-
1hls ls somthlng o o momntous occoslon. 1h nd o Choptr 6 morks th nd o our story
o motlon [ln th contxt o thls book, thot lsj. W stortd wlth th concpt o o vctor, movd
on to orcs, dslgnd systms o mony lmnts, xomlnd physlcs llbrorls, bullt ntltls
wlth hops ond droms ond ors, ond slmulotd mrgnc. 1h story dosn`t nd hr, but
lt dos tok o blt o o turn. 1h nxt two choptrs won`t ocus on movlng bodls, but rothr on
systms o ruls. Bor w gt thr, | hov o w qulck ltms |`d llk to mntlon thot or
lmportont whn worklng wlth th xompls ln Choptrs J through 6. 1hy olso rlot to
optlmlzlng your cod, whlch lts ln wlth th prvlous sctlon.
1h Notur o Cod [v005j
3J7
#_ ]4<;&':9( -m:4.(9 ^*. -*E('&E(- 9&-'4;2( -m:4.(9_ #_ ]4<;&':9( -m:4.(9 ^*. -*E('&E(- 9&-'4;2( -m:4.(9_
Whot ls mognltud squord ond whn should you us lt? Lt`s rvlslt how th mognltud o
o vctor ls colculotd.
Mognltud rqulrs th squor root oprotlon. And lt should. Atr oll, l you wont th
mognltud o o vctor, thn you`v got to look up th Pythogoron thorm ond comput lt
[w dld thls ln Choptr Jj. Howvr, l you could somhow sklp uslng th squor root, your
cod would run ostr. Lt`s consldr o sltuotlon whr you just wont to know th rlotlv
mognltud o o vctor. |or xompl, ls th mognltud grotr thon tn? [Assum o ]`%028/
A.j
Wll, thls ls qulvolnt to soylng.
And how ls mognltud squord colculotd?
5om os mognltud, but wlthout th squor root. |n th cos o o slngl ]`%028/ objct, thls
wlll nvr mok o slgnllcont dlrnc on o Procsslng sktch. Howvr, l you or
computlng th mognltud o thousonds o ]`%028/ objcts och tlm through &/,;45, uslng
9,?[g45 lnstod o 9,?45 could hlp your cod run o w blt ostr. [Not. 9,?[g45 ls only
ovollobl ln Procsslng 2.0oJ or lotr.j
E-8,2 9,?45 1
/%23/7 #g/24!Q! ( "Q"5*
@
:E 4AN9,?45 ^ )B5 1
== \8 [89%2<:7?S
@
:E 4AN9,?[g45 ^ )BB5 1
== \8 [89%2<:7?S
@
E-8,2 9,?[g45 1
/%23/7 !Q! ( "Q"*
@
0_ U&;( 4;9 2*-&;( %**3:Q '4)%(- 0_ U&;( 4;9 2*-&;( %**3:Q '4)%(-
1hr`s o pottrn hr. Whot klnds o unctlons or slow to comput? 5quor root. 5ln.
Cosln. 1ongnt. Agoln, l you just nd o sln or cosln volu hr or thr ln your cod,
you or nvr golng to run lnto o problm. But whot l you hod somthlng llk thls?
Choptr 6. Autonomous Agnts
3J8
5ur, thls ls o totolly rldlculous cod snlppt thot you would nvr wrlt. But lt lllustrots o
crtoln polnt. | you or colculotlng th sln o pl tn thousond tlms, why not just colculot lt
onc, sov thot volu, ond rr to lt whnvr ncssory? 1hls ls th prlnclpl bhlnd sln
ond cosln lookup tobls. |nstod o colllng th sln ond cosln unctlons ln your cod
whnvr you nd thm, you con bulld on orroy thot stors th rsults o sln ond cosln ot
ongls btwn 0 ond n+Ua]c ond just look up th volus whn you nd thm. |or xompl,
hr or two orroys thot stor th sln ond cosln volus or vry ongl, 0 to 359 dgrs.
Now, whot l you nd th volu o sln o pl?
A mor sophlstlcotd xompl o thls tchnlqu ls ovollobl on th Procsslng wlkl
[http.//wlkl.procsslng.org/w/5ln/Cos_look-up_toblj.
A8:& &/,;45 1
E8/ 4:72 : ' B* : P )BBBB* :((5 1
$/:72-74#:74]c55*
@
@
E-8,2 #:7A,-3%#KL ' 7%; E-8,2KHGBL*
E-8,2 08#A,-3%#KL ' 7%; E-8,2KHGBL*
E8/ 4:72 : ' B* : P HGB* :((5 1
#:7A,-3%#K:L ' #:74/,&:,7#4:55*
08#A,-3%#K:L ' 08#4/,&:,7#4:55*
@
:72 ,7?-% ' :724&%?/%%#4]c55*
E-8,2 ,7#;%/ ' #:7A,-3%#K,7?-%L*
=_ ]43&;< <4G&%%&*;- *+ :;;(2(--4./ 5R(2'*. *)G(2'- =_ ]43&;< <4G&%%&*;- *+ :;;(2(--4./ 5R(2'*. *)G(2'-
| hov to odmlt, | om prhops th blggst culprlt o thls lost not. |n oct, ln th lntrst o
wrltlng clor ond undrstondobl xompls, | otn choos to mok xtro ]`%028/ objcts
whn | obsolutly do not nd to. |or th most port, thls ls not o problm ot oll. But
somtlms, lt con b. Lt`s tok o look ot on xompl.
Lt`s soy our V//,"l:#2 o vhlcls hos on thousond vhlcls ln lt. W just mod on
thousond nw ]`%028/ objcts vry slngl tlm through &/,;45. Now, on ony ol` loptop or
dsktop computr you`v purchosd ln rcnt tlms, your sktch wlll llkly not rglstr o
complolnt, run slowly, or hov ony problms. Atr oll, you`v got tons o RAM, ond Jovo wlll
A8:& &/,;45 1
E8/ 4`%<:0-% A q A%<:0-%#5 1
]`%028/ 983#% ' 7%; ]`%028/4983#%eC983#%f5*
AN#%%.4983#%5*
@
@
1h Notur o Cod [v005j
3J9
b obl to hondl moklng o thousond or so tmporory objcts ond dlspos o thm wlthout
much o o problm.
| your numbrs grow lorgr [ond thy oslly couldj or prhops mor llkly, l you or
worklng wlth Procsslng on Androld, you wlll olmost crtolnly run lnto o problm. |n coss
llk thls you wont to look or woys to rduc th numbr o ]`%028/ objcts you mok. An
obvlous lx or th obov cod ls.
Now you`v mod just on ]`%028/ lnstod o on thousond. Lvn bttr, you could turn
th ]`%028/ lnto o globol vorlobl ond just osslgn th ! ond " volu.
Now you nvr mok o nw ]`%028/, you us just on ovr th lngth o your sktch!
1hroughout th book`s xompls, you con lnd lots o opportunltls to rduc th numbr o
tmporory objcts. Lt`s look ot on mor. Hr ls o snlppt rom our #%%.45 unctlon.
5 how w`v mod two ]`%028/ objcts? |lrst, w lgur out th dslrd vctor, thn w
colculot th strlng orc. Notlc how w could rwrlt thls to crot only on ]`%028/.
A8:& &/,;45 1
]`%028/ 983#% ' 7%; ]`%028/4983#%eC983#%f5*
E8/ 4`%<:0-% A q A%<:0-%#5 1
AN#%%.4983#%5*
@
@
]`%028/ 983#% ' 7%; ]`%028/45*
A8:& &/,;45 1
983#%N! ' 983#%e*
983#%N" ' 983#%f*
E8/ 4`%<:0-% A q A%<:0-%#5 1
AN#%%.4983#%5*
@
@
]`%028/ &%#:/%& ' ]`%028/N#3I42,/?%2C-80,2:875*
&%#:/%&N78/9,-:F%45*
&%#:/%&N93-249,!#$%%&5*
Create a new PVector to store the steering
force.
MN$:/8) ./$$) " MN$:/8)-.46*1$.2)$1JL$'8:2/3+,
#2%%/N-:9:249,!E8/0%5*
/%23/7 #2%%/*
]`%028/ &%#:/%& ' ]`%028/N#3I42,/?%2C -80,2:875*
&%#:/%&N78/9,-:F%45*
&%#:/%&N93-249,!#$%%&5*
Choptr 6. Autonomous Agnts
320
W don`t octuolly nd o scond ]`%028/ colld #2%%/. W could just us th dslrd
]`%028/ objct ond turn lt lnto th strlng orc by subtroctlng vloclty. | dldn`t do thls ln my
xompl bcous lt ls mor conuslng to rod. But ln som coss, lt moy b grotly mor
lclnt.
Calculate the steering force in the desired
PVector.
1$.2)$1-.46*L$'8:2/3+,
&%#:/%&N-:9:249,!E8/0%5*
/%23/7 &%#:/%&*
Lllmlnot os mony tmporory ]`%028/ objcts rom th locklng xompl os posslbl.
Also us 9,?[g45 whr posslbl.
MO(.2&-( K"0T MO(.2&-( K"0T
s strlng bhovlors wlth Box2L or toxlcllbs.
MO(.2&-( K"0# MO(.2&-( K"0#
1h Notur o Cod [v005j
32J
@,( M2*-/-'(E 5.*G(2' @,( M2*-/-'(E 5.*G(2'
U'(Q K MO(.2&-(D
[-( ',( 2*;2(Q' *+ -'((.&;< +*.2(- '* 9.&I( ',( )(,4I&*. *+ ',( 2.(4':.(- &; /*:.
(2*-/-'(E" U*E( Q*--&)&%&'&(-D
h P.(4'( A-2,**%-B *. A+%*23-B *+ 2.(4':.(-"
h [-( 4 -((3&;< )(,4I&*. +*. 2.(4':.(- '* -(4.2, +*. +**9 ^+*. 2,4-&;<
E*I&;< Q.(/` 2*;-&9(. AQ:.-:&'B_"
h [-( 4 +%*8 +&(%9 +*. ',( (2*-/-'(E (;I&.*;E(;'" S*. (O4EQ%(` ,*8 9*(-
/*:. -/-'(E )(,4I( &+ ',( 2.(4':.(- %&I( &; 4 +%*8&;< .&I(.7
h b:&%9 4 2.(4':.( 8&', 2*:;'%(-- -'((.&;< )(,4I&*.- ^4- E4;/ 4- /*: 24;
.(4-*;4)%/ 499_" @,&;3 4)*:' 84/- '* I4./ ',( 8(&<,'- *+ ',(-(
)(,4I&*.- -* ',4' /*: 24; 9&4% ',*-( )(,4I&*.- :Q 4;9 9*8;` E&O&;< 4;9
E4'2,&;< *; ',( +%/" f*8 4.( 2.(4':.(-H &;&'&4% 8(&<,'- -('7 6,4' .:%(-
9.&I( ,*8 ',( 8(&<,'- 2,4;<( *I(. '&E(7
h P*EQ%(O -/-'(E- 24; )( ;(-'(9" P4; /*: 9(-&<; 4 -&;<%( 2.(4':.( *:' *+
4 +%*23 *+ )*&9-7 !;9 24; /*: ',(; E43( 4 +%*23 *+ ',*-( 2.(4':.(-7
h P*EQ%(O -/-'(E- 24; ,4I( E(E*./ ^4;9 )( 494Q'&I(_" P4; ',( ,&-'*./ *+
/*:. (2*-/-'(E 4++(2' ',( )(,4I&*. &; &'- 2:..(;' -'4'(7 ^@,&- 2*:%9 )(
',( 9.&I&;< +*.2( )(,&;9 ,*8 ',( 2.(4':.(- 49G:-' ',(&. -'((.&;< +*.2(
8(&<,'-"_
Choptr 6. Autonomous Agnts
322
,"&:'#) AK ,#55(5&) ,"&:'#) AK ,#55(5&)
2('*7&'& 2('*7&'&
To plc lije ou must hcte c jcirl lcre checlerbocrd cnd c plentijul
suppl oj jlct counters oj tuo colors. It is possible to uorl uith pencil cnd
rcph pcper but it is much ecsier, pcrticulcrl jor beinners, to use
counters cnd c bocrd.
! H$24-, I$21,&25 5c|ent|t|c Amet|con CA.40K&2 LMN9D
|n thls choptr, w`r golng to tok o brok rom tolklng obout vctors ond motlon. |n oct, th
rst o th book wlll mostly ocus on systms ond olgorlthms [olblt ons thot w con, should,
ond wlll opply to movlng bodlsj. |n th prvlous choptr, w ncountrd our lrst Procsslng
xompl o o complx systm. locklng. W brlly stotd th cor prlnclpls bhlnd complx
systms. mor thon th sum o lts ports, o complx systm ls o systm o lmnts, oprotlng
ln porolll, wlth short-rong rlotlonshlps thot os o whol xhlblt mrgnt bhovlor. 1hls
ntlr choptr ls golng to b ddlcotd to bulldlng onothr complx systm slmulotlon ln
Procsslng. Oddly, w or golng to tok som stps bockword ond slmplly th lmnts o
our systm. No longr or th lndlvlduol lmnts golng to b mmbrs o o physlcs world,
lnstod w wlll bulld o systm out o th slmplst dlgltol lmnt posslbl, o slngl blt. 1hls blt
ls golng to b colld o cll ond lts volu [0 or Jj wlll b colld lts stot. Worklng wlth such
slmpl lmnts wlll hlp us undrstond mor o th dtolls bhlnd how complx systms
work, ond w`ll olso b obl to loborot on som progrommlng tchnlqus thot w con opply
to cod-bosd projcts.
1h Notur o Cod [v005j
323
L"# 6,4' C- 4 P(%%:%4. !:'*E4'*;7 L"# 6,4' C- 4 P(%%:%4. !:'*E4'*;7
|lrst, lt`s gt on thlng strolght. 1h trm %$'':'(1 (:&!-(&( %$'':'(1 (:&!-(&( ls plurol. Our cod xompls
wlll slmulot just ono %$'':'(1 (:&!-(&!. %$'':'(1 (:&!-(&!., slngulor. 1o slmplly our llvs, w`ll olso rr
to cllulor outomoto os CA."
|n Choptrs J through 6, our objcts [movr, portlcl, vhlcl, boldj gnrolly xlstd ln only
on stot." 1hy mlght hov movd oround wlth odvoncd bhovlors ond physlcs, but
ultlmotly thy rmolnd th som typ o objct ovr th cours o thlr dlgltol lltlm.
W`v olludd to th posslblllty thot ths ntltls con chong ovr tlm [or xompl, th
wlghts o strlng dslrs" con voryj, but w hovn`t ully put thls lnto proctlc. |n thls
contxt, cllulor outomoto mok o grot lrst stp ln bulldlng o systm o mony objcts thot
hov vorylng stots ovr tlm.
A cllulor outomoton ls o modl o o systm o cll" objcts wlth th ollowlng
choroctrlstlcs.
- 1h clls llv on o 21/8 21/8. [W`ll s xompls ln both on ond two dlmnslons ln
thls choptr, though o cllulor outomoton con xlst ln ony lnlt numbr o
dlmnslons.j
- Loch cll hos o )&(&$ )&(&$. 1h numbr o stot posslbllltls ls typlcolly lnlt. 1h
slmplst xompl hos th two posslbllltls o J ond 0 [othrwls rrrd to os on"
ond o" or ollv" ond dod"j.
- Loch cll hos o .$/2+"!1+!!8 .$/2+"!1+!!8. 1hls con b dlnd ln ony numbr o woys, but lt ls
typlcolly o llst o odjocnt clls.
1h dvlopmnt o cllulor outomoto systms ls typlcolly ottrlbutd to 5tonlsow lom ond
John von Numonn, who wr both rsorchrs ot th Los Alomos Notlonol Loborotory ln
Iiure ;.:
Choptr 7. Cllulor Automoto
324
Nw Mxlco ln th J940s. lom wos studylng th growth o crystols ond von Numonn wos
lmoglnlng o world o sl-rpllcotlng robots. 1hot`s rlght, robots thot bulld copls o
thmslvs. Onc w s som xompls o CA vlsuollzd, lt`ll b clor how on mlght
lmogln modllng crystol growth, th robots ldo ls prhops lss obvlous. Consldr th dslgn
o o robot os o pottrn on o grld o clls [thlnk o llllng ln som squors on o plc o groph
poprj. Now consldr o st o slmpl ruls thot would ollow thot pottrn to crot copls o
ltsl on thot grld. 1hls ls ssntlolly th procss o o CA thot xhlblts bhovlor slmllor to
blologlcol rproductlon ond volutlon. [|ncldntolly, von Numonn`s clls hod twnty-nln
posslbl stots.j Von Numonn`s work ln sl-rpllcotlon ond CA ls concptuolly slmllor to
whot ls probobly th most omous cllulor outomoton. th Gom o Ll," whlch w wlll
dlscuss ln dtoll ln sctlon 7.3.
Prhops th most slgnllcont sclntllc [ond lngthyj work studylng cllulor outomoto orrlvd ln
2002. 5tphn Wolrom`s J,280-pog A New k|nd ot 5c|ence [http.//www.wolromsclnc.com/
nksonlln/toc.htmlj. Avollobl ln lts ntlrty or r onlln, Wolrom`s book dlscusss how CA
or not slmply not trlcks, but or rlvont to th study o blology, chmlstry, physlcs, ond oll
bronchs o sclnc. 1hls choptr wlll borly scrotch th suroc o th thorls Wolrom
outllns [w wlll ocus on th cod lmplmntotlonj so l th xompls provldd spork your
curloslty, you`ll lnd plnty mor to rod obout ln hls book.
L"0 M%(E(;'4./ P(%%:%4. !:'*E4'4 L"0 M%(E(;'4./ P(%%:%4. !:'*E4'4
1h xompls ln thls choptr wlll bgln wlth o slmulotlon o Wolrom`s work. 1o undrstond
Wolrom`s lmntory CA, w should osk ourslvs th qustlon. Whot ls th slmplst cllulor
outomoton w con lmogln?" Whot`s xcltlng obout thls qustlon ond lts onswr ls thot vn
wlth th slmplst CA lmoglnobl, w wlll s th proprtls o complx systms ot work.
Lt`s bulld Wolrom`s lmntory CA rom scrotch. Concpts lrst, thn cod. Whot or th
thr ky lmnts o o CA?
Jj b1/8 b1/8. 1h slmplst grld would b on-dlmnslonol. o lln o clls.
2j Q&(&$) Q&(&$). 1h slmplst st o stots [byond hovlng only on stotj would b two stots. 0 or
J.
Iiure ;.z
Iiure ;.
1h Notur o Cod [v005j
325
3j ^$/2+"!1+!!8 ^$/2+"!1+!!8. 1h slmplst nlghborhood ln on dlmnslon or ony glvn cll would b
th cll ltsl ond lts two odjocnt nlghbors. on to th lt ond on to th rlght.
5o w bgln wlth o lln o clls, och wlth on lnltlol stot [lt`s soy lt ls rondomj, ond och
wlth two nlghbors. W`ll hov to lgur out whot w wont to do wlth th clls on th dgs
[slnc thos hov only on nlghbor ochj, but thls ls somthlng w con sort out lotr.
W hovn`t yt dlscussd, howvr, whot ls prhops th most lmportont dtoll o how
cllulor outomoto workt|me. W`r not rolly tolklng obout rol-world tlm hr, but obout
th CA llvlng ovr o prlod o t|me, whlch could olso b colld o 2$.$1(&/!. 2$.$1(&/!. ond, ln our
cos, wlll llkly rr to th ;1(-$ %!:.& ;1(-$ %!:.& o on onlmotlon. 1h lgurs obov show us th CA
ot tlm quols 0 or gnrotlon 0. 1h qustlons w hov to osk ourslvs or. How do we
compute the stotes tot o|| ce||s ot genetot|on !? And genetot|on 2? And so on ond so orth.
Lt`s soy w hov on lndlvlduol cll ln th CA, ond lt`s coll lt CLLL. 1h ormulo or
colculotlng CLLL`s stot ot ony glvn tlm 2 ls os ollows.
fnoo ./&/$ &/ /25$ / " 9*fnoo #$2GH68)H881 &/ /25$ / T D+
|n othr words, o cll`s nw stot ls o unctlon o oll th stots ln th cll`s nlghborhood ot
th prvlous momnt ln tlm [or durlng th prvlous gnrotlonj. W colculot o nw stot
volu by looklng ot oll th prvlous nlghbor stots.
Iiure ;.(: A neihborhood is three cells.
Iiure ;.: The ede cell onl hcs c neihborhood oj tuo.
Iiure ;.
Choptr 7. Cllulor Automoto
326
Now, ln th world o cllulor outomoto, thr or mony woys w could comput o cll`s stot
rom o group o clls. Consldr blurrlng on lmog. [Guss whot? |mog procsslng works wlth
CA-llk ruls.j A plxl`s nw stot [l.. lts colorj ls th ovrog o oll o lts nlghbors` colors.
W could olso soy thot o cll`s nw stot ls th sum o oll o lts nlghbors` stots. Wlth
Wolrom`s lmntory CA, howvr, w con octuolly do somthlng o blt slmplr ond smlngly
obsurd. W con look ot oll th posslbl conlgurotlons o o cll ond lts nlghbor ond dln th
stot outcom or vry posslbl conlgurotlon. |t sms rldlculouswouldn`t thr b woy too
mony posslbllltls or thls to b proctlcol? Lt`s glv lt o try.
W hov thr clls, och wlth o stot o 0 or J. How mony posslbl woys con w conlgur
th stots? | you lov blnory, you`ll notlc thot thr clls dln o 3-blt numbr, ond how hlgh
con you count wlth 3 blts? p to 8. Lt`s hov o look.
Onc w hov dlnd oll th posslbl nlghborhoods, w nd to dln on outcom [nw
stot volu. 0 or Jj or och nlghborhood conlgurotlon.
1h stondord Wolrom modl ls to stort gnrotlon 0 wlth oll clls hovlng o stot o 0 xcpt
or th mlddl cll, whlch should hov o stot o J.
Iiure ;.;
Iiure ;.8
Iiure ;.p
Iiure ;.:o
1h Notur o Cod [v005j
327
Rrrlng to th rulst obov, lt`s s how o glvn cll [w`ll plck th cntr onj would
chong rom gnrotlon 0 to gnrotlon J.
1ry opplylng th som loglc to oll o th clls obov ond lll ln th mpty clls.
Now, lt`s go post just on gnrotlon ond color th clls 0 mons whlt, J mons
blockond stock th gnrotlons, wlth och nw gnrotlon opporlng blow th prvlous
on.
1h low-rsolutlon shop w`r slng obov ls th 5lrplskl trlongl." Nomd otr th
Pollsh mothmotlclon Wocow 5lrplskl, lt`s o roctol pottrn thot w`ll xomln ln th nxt
choptr. 1hot`s rlght. thls lncrdlbly slmpl systm o 0s ond Js, wlth llttl nlghborhoods o
thr clls, con gnrot o shop os sophlstlcotd ond dtolld os th 5lrplskl trlongl.
Lt`s look ot lt ogoln, only wlth och cll o slngl plxl wld so thot th rsolutlon ls much
hlghr.
Iiure ;.::
Iiure ;.:z: Rule po
Choptr 7. Cllulor Automoto
328
1hls portlculor rsult dldn`t hoppn by occldnt. | plckd thls st o ruls bcous o th
pottrn lt gnrots. 1ok o look ot |lgur 7.8 on mor tlm. Notlc how thr or lght
posslbl nlghborhood conlgurotlons, w thror dln o rulst" os o llst o 8 blts.
5o thls portlculor rul con b lllustrotd os ollows.
Llght 0s ond Js mons on 8-blt numbr. How mony comblnotlons o lght 0s ond Js or thr?
256. 1hls ls just llk how w dln th componnts o on RGB color. W gt 8 blts or rd,
grn, ond blu, monlng w mok colors wlth volus rom 0 to 255 [256 posslbllltlsj.
|n trms o o Wolrom lmntory CA, w hov now dlscovrd thot thr or 256 posslbl
rulsts. 1h obov rulst ls commonly rrrd to os Rul 90" bcous l you convrt th
blnory squnc0J0JJ0J0to o dclmol numbr, you`ll gt th lntgr 90. Lt`s try looklng ot
th rsults o onothr rulst.
Iiure ;.:: Rule po
Iiure ;.:(: Rule po
1h Notur o Cod [v005j
329
As w con now s, th slmpl oct o
crotlng o CA ond dlnlng o rulst dos
not guoront vlsuolly lntrstlng rsults.
Out o oll 256 rulsts, only o hondul
produc complllng outcoms. Howvr,
lt`s qult lncrdlbl thot vn on o ths
rulsts or o on-dlmnslonol CA wlth only
two posslbl stots con produc th
pottrns w s vry doy ln notur [s
|lgur 7.J6j, ond lt dmonstrots how
voluobl ths systms con b ln
slmulotlon ond pottrn gnrotlon.
Bor w go too or down th rood o how
Wolrom closslls th rsults o vorylng
rulsts, lt`s look ot how w octuolly bulld
o Procsslng sktch thot gnrots th
Wolrom CA ond vlsuollzs lt onscrn.
Iiure ;.:: Rule zzz
Iiure ;.:: A Textile Cone Sncil (Conus textile),
Cod Hole, Grect crrier Reej, Austrclic, ;
Auust zoo. Photorcpher: Richcrd Lin
richcrdQresecrch.ccnon.com.cu
L"= f*8 '* 5.*<.4E 4; M%(E(;'4./ P! L"= f*8 '* 5.*<.4E 4; M%(E(;'4./ P!
You moy b thlnklng. OK, |`v got thls cll thlng. And th cll thlng hos som proprtls,
llk o stot, whot gnrotlon lt`s on, who lts nlghbors or, whr lt llvs plxl-wls on th
scrn. And moyb lt hos som unctlons. lt con dlsploy ltsl, lt con gnrot lts nw stot,
tc." 1hls lln o thlnklng ls on xcllnt on ond would llkly lod you to wrlt som cod
llk thls.
0-,## M%-- 1
@
Choptr 7. Cllulor Automoto
330
1hls lln o thlnklng, howvr, ls not th rood w wlll lrst trovl. Lotr ln thls choptr, w wlll
dlscuss why on objct-orlntd opprooch could prov voluobl ln dvloplng o CA slmulotlon,
but to bgln, w con work wlth o mor lmntory doto structur. Atr oll, whot ls on
lmntory CA but o llst o 0s ond Js? Crtolnly, w could dscrlb th ollowlng CA
gnrotlon uslng on orroy.
1o drow thot orroy, w slmply chck l w`v got o 0 or o J ond crot o lll occordlngly.
Now thot w hov th orroy to dscrlb th cll stots o o glvn gnrotlon [whlch w`ll
ultlmotly consldr th currnt" gnrotlonj, w nd o mchonlsm by whlch to comput th
nxt gnrotlon. Lt`s thlnk obout th psudocod o whot w or dolng ot th momnt.
G*) #N#)U 0#55 /1 '"# &))&UL G*) #N#)U 0#55 /1 '"# &))&UL
- *(J$ ( '!!J (& &+$ .$/2+"!1+!!8 )&(&$)3 '$;&I -/88'$I 1/2+&6 *(J$ ( '!!J (& &+$ .$/2+"!1+!!8 )&(&$)3 '$;&I -/88'$I 1/2+&6
- _!!J :A &+$ .$> 0(':$ ;!1 &+$ %$'' )&(&$ (%%!18/.2 &! )!-$ 1:'$)$&6 _!!J :A &+$ .$> 0(':$ ;!1 &+$ %$'' )&(&$ (%%!18/.2 &! )!-$ 1:'$)$&6
- Q$& &+$ %$''\) )&(&$ &! &+(& .$> 0(':$6 Q$& &+$ %$''\) )&(&$ &! &+(& .$> 0(':$6
1hls moy lod you to wrlt som cod llk thls.
Iiure ;.:;
:72KL 0%--# ' 1)CBC)CBCBCBCBC)CBC)C)C)CBCBCBC)C)C)CBCB@*
Loop through every cell. E8/ 4:72 : ' B* : P 0%--#N-%7?2<* :((5 1
:E 40%--#K:L '' B5 E:--4>JJ5*
Create a fill based on its state (0 or 1). %-#% E:--4B5*
#2/8.%4B5*
/%024:QJBCBCJBCJB5*
@
For every cell in the array... E8/ 4:72 : ' B* : P 0%--#N-%7?2<* :((5 1
...take a look at the neighborhood. :72 -%E2 ' 0%--K:6)L*
:72 9:&&-% ' 0%--K:L*
:72 /:?<2 ' 0%--K:()L*
Look up the new value according to the
rules.
:72 7%;#2,2% ' /3-%#4-%E2C9:&&-%C/:?<25*
1h Notur o Cod [v005j
33J
W`r olrly clos to gttlng thls rlght, but w`v mod on mlnor blundr ond on mojor
blundr ln th obov cod. Lt`s tolk obout whot w`v don wll so or.
Notlc how osy lt ls to look ot o cll`s nlghbors. Bcous on orroy ls on ordrd llst o
doto, w con us th oct thot th lndlcs or numbrd to know whlch clls or nxt to
whlch clls. W know thot cll numbr J5, or xompl, hos cll J4 to lts lt ond J6 to lts
rlght. Mor gnrolly, w con soy thot or ony cll :, lts nlghbors or :6) ond :().
W`r olso ormlng out th colculotlon o o nw stot volu to som unctlon colld /3-%#45.
Obvlously, w`r golng to hov to wrlt thls unctlon ourslvs, but th polnt w`r moklng
hr ls modulorlty. W hov o boslc romwork or th CA ln thls unctlon, ond l w lotr
wont to chong how th ruls oprot, w don`t hov to touch thot romwork, w con
slmply rwrlt th /3-%#45 unctlon to comput th nw stots dlrntly.
5o whot hov w don wrong? Lt`s tolk through how th cod wlll xcut. |lrst, w look
ot cll lndx : quols 0. Now lt`s look ot 0`s nlghbors. Lt ls lndx -J. Mlddl ls lndx 0.
And rlght ls lndx J. Howvr, our orroy by dlnltlon dos not hov on lmnt wlth th
lndx -J. |t storts wlth 0. 1hls ls o problm w`v olludd to bor. th dg coss.
How do w dol wlth th clls on th dg who don`t hov o nlghbor to both thlr lt ond
thlr rlght? Hr or thr posslbl solutlons to thls problm.
J. =82$) 1$-(/. %!.)&(.&6 =82$) 1$-(/. %!.)&(.&6 1hls ls prhops th slmplst solutlon. W nvr bothr to
voluot th dgs ond olwoys lov thlr stot volu constont [0 or Jj.
2. =82$) >1(A (1!:.86 =82$) >1(A (1!:.86 1hlnk o th CA os o strlp o popr ond turn thot strlp o
popr lnto o rlng. 1h cll on th lt dg ls o nlghbor o th cll on th rlght
ond vlc vrso. 1hls con crot th opporonc o on lnlnlt grld ond ls probobly
th most usd solutlon.
3. =82$) +(0$ 8/;;$1$.& .$/2+"!1+!!8) (.8 1:'$)6 =82$) +(0$ 8/;;$1$.& .$/2+"!1+!!8) (.8 1:'$)6 | w wontd to, w could trot
th dg clls dlrntly ond crot ruls or clls thot hov o nlghborhood o
two lnstod o thr. You moy wont to do thls ln som clrcumstoncs, but ln our
cos, lt`s golng to b o lot o xtro llns o cod or llttl bnlt.
1o mok th cod oslst to rod ond undrstond rlght now, w`ll go wlth optlon #J ond just
sklp th dg coss, lovlng thlr volus constont. 1hls con b occompllshd by stortlng th
loop on cll lotr ond ndlng on cll orllr.
Set the cell's state to the new value. 0%--K:L ' 7%;#2,2%*
@
Choptr 7. Cllulor Automoto
332
1hr`s on mor problm w hov to lx bor w`r don. |t`s subtl ond you won`t gt o
compllotlon rror, th CA just won`t prorm corrctly. Howvr, ldntlylng thls problm ls
obsolutly undomntol to th tchnlqus bhlnd progrommlng CA slmulotlons. |t oll lls ln thls
lln o cod.
1hls sms llk o prctly lnnocnt lln. Atr oll, w`v computd th nw stot volu ond
w`r slmply glvlng th cll lts nw stot. But ln th nxt ltrotlon, you`ll dlscovr o mosslv
bug. Lt`s soy w`v just computd th nw stot or cll #5. Whot do w do nxt? W
colculot th nw stot volu or cll #6.
Ce|| #, genetot|on 0 some stote, 0 ot !
Ce|| #, genetot|on ! o tunct|on ot stotes tot %$'' c< %$'' c<, ce|| #, ond ce|| #7 ot genetot|on 0
Notlc how w nd th volu o cll #5 ot gnrotlon 0 ln ordr to colculot cll #6`s nw
stot ot gnrotlon J? A cll`s nw stot ls o unctlon o th prvlous nlghbor stots. Lo w
know cll #5`s volu ot gnrotlon 0? Rmmbr, Procsslng just xcuts thls lln o cod
or | 5.
Onc thls hoppns, w no longr hov occss to cll #5`s stot ot gnrotlon 0, ond cll lndx
5 ls storlng th volu or gnrotlon J. W connot ovrwrlt th volus ln th orroy whll w
or procsslng th orroy, bcous w nd thos volus to colculot th nw volus. A
solutlon to thls problm ls to hov two orroys, on to stor th currnt gnrotlon stots ond
on or th nxt gnrotlon stots.
A loop that ignores the first and last cell 98) *2#/ 2 " D, 2 S :$''.-'$#G/HTD, 2KK+ O
:72 -%E2 ' 0%--K:6)L*
:72 9:&&-% ' 0%--K:L*
:72 /:?<2 ' 0%--K:()L*
:72 7%;#2,2% ' /3-%#4-%E2C9:&&-%C/:?<25*
0%--K:L ' 7%;#2,2%*
@
0%--K:L ' 7%;#2,2%*
0%--K:L ' 7%;#2,2%*
Another array to store the states for the next
generation.
2#/[\ #$!:$''. " #$! 2#/[:$''.-'$#G/H\,
E8/ 4:72 : ' )* : P 0%--#N-%7?2<6)* :((5 1
Look at the states from the current array. :72 -%E2 ' 0%--K:6)L*
:72 9:&&-% ' 0%--K:L*
:72 /:?<2 ' 0%--K:()L*
:72 7%;#2,2% ' /3-%#4-%E2C9:&&-%C/:?<25*
Saving the new state in the new array #$!:$''.[2\ " #$!./&/$,
@
1h Notur o Cod [v005j
333
Onc th ntlr orroy o volus ls procssd, w con thn dlscord th old orroy ond st lt
quol to th nw orroy o stots.
W`r olmost don. 1h obov cod ls complt xcpt or th oct thot w hovn`t yt
wrlttn th /3-%#45 unctlon thot computs th nw stot volu bosd on th nlghborhood
[lt, mlddl, ond rlght cllsj. W know thot unctlon nds to rturn on lntgr [0 or Jj os
wll os rclv thr orgumnts [or th thr nlghborsj.
Now, thr or mony woys w could wrlt thls unctlon, but |`d llk to stort wlth o long-
wlndd on thot wlll hopully provld o clor lllustrotlon o whot w or dolng.
Lt`s lrst stobllsh how w or storlng th rulst. 1h rulst, l you rmmbr rom th
prvlous sctlon, ls o srls o 8 blts [0 or Jj thot dlns thot outcom or vry posslbl
nlghborhood conlgurotlon.
W con stor thls rulst ln Procsslng os on orroy.
And thn soy.
| lt, mlddl, ond rlght oll hov th stot J, thn thot motchs th conlgurotlon JJJ ond th
nw stot should b quol to th lrst volu ln th rulst orroy. W con now dupllcot thls
strotgy or oll lght posslbllltls.
The new generation becomes the current
generation.
:$''. " #$!:$''.,
Function receives 3 ints and returns 1. :72 /3-%# 4:72 ,C :72 IC :72 05 1
Iiure ;.:( (repected)
:72KL /3-%#%2 ' 1BC)CBC)C)CBC)CB@*
:E 4, '' ) mm I '' ) mm 0 '' )5 /%23/7 /3-%#%2KBL*
Choptr 7. Cllulor Automoto
334
| llk hovlng th xompl wrlttn os obov bcous lt dscrlbs lln by lln xoctly whot ls
hoppnlng or och nlghborhood conlgurotlon. Howvr, lt`s not o grot solutlon. Atr oll,
whot l w dslgn o CA thot hos 4 posslbl stots [0-3j ond suddnly w hov 64 posslbl
nlghborhood conlgurotlons? Wlth J0 posslbl stots, w hov J,000 conlgurotlons. Crtolnly
w don`t wont to typ ln J,000 llns o cod!
Anothr solutlon, though prhops o blt mor dllcult to ollow, ls to convrt th nlghborhood
conlgurotlon [o 3-blt numbrj lnto o rgulor lntgr ond us thot volu os th lndx lnto th
rulst orroy. 1hls con b don ln Jovo llk so.
1hr`s on tlny problm wlth thls solutlon, howvr. Lt`s soy w or lmplmntlng rul 222.
And w hov th nlghborhood JJJ". 1h rsultlng stot ls quol to rulst lndx 0, os w s
ln th lrst woy w wrot th unctlon.
| w convrt JJJ" to o dclmol numbr, w gt 7. But w don`t wont rulst7, w wont
rulst0. |or thls to work, w nd to wrlt th rulst wlth th blts ln rvrs ordr, l..
:72 /3-%# 4:72 ,C :72 IC :72 05 1
:E 4, '' ) mm I '' ) mm 0 '' )5 /%23/7 /3-%#%2KBL*
%-#% :E 4, '' ) mm I '' ) mm 0 '' B5 /%23/7 /3-%#%2K)L*
%-#% :E 4, '' ) mm I '' B mm 0 '' )5 /%23/7 /3-%#%2K>L*
%-#% :E 4, '' ) mm I '' B mm 0 '' B5 /%23/7 /3-%#%2KHL*
%-#% :E 4, '' B mm I '' ) mm 0 '' )5 /%23/7 /3-%#%2KDL*
%-#% :E 4, '' B mm I '' ) mm 0 '' B5 /%23/7 /3-%#%2KJL*
%-#% :E 4, '' B mm I '' B mm 0 '' )5 /%23/7 /3-%#%2KGL*
%-#% :E 4, '' B mm I '' B mm 0 '' B5 /%23/7 /3-%#%2KOL*
For this function to be valid, we have to
make sure something is returned in cases
where the states do not match one of the
eight possibilities. We know this is
impossible given the rest of our code, but
Processing does not.
/%23/7 B*
@
:72 /3-%# 4:72 ,C :72 IC :72 05 1
A quick way to join three bits into a String [2/:7? # ' TT ( , ( I ( 0*
The second argument '2' indicates that we
intend to parse a binary number (base 2).
:72 :7&%! ' c72%?%/N$,/#%c724#C>5*
/%23/7 /3-%#%2K:7&%!L*
@
Rule 222 :72KL /3-%#%2 ' 1)C)CBC)C)C)C)CB@*
:E 4, '' ) mm I '' ) mm 0 '' )5 /%23/7 /3-%#%2KBL*
1h Notur o Cod [v005j
335
5o or ln thls sctlon, w`v wrlttn vrythlng w nd to comput th gnrotlons or o
Wolrom lmntory CA. Lt`s tok o momnt to orgonlz th obov cod lnto o closs, whlch
wlll ultlmotly hlp ln th dslgn o our ovroll sktch.
Rule 222 in "reverse order :72KL /3-%#%2 ' 1BC)C)C)C)CBC)C)@*
0-,## MV 1
We need an array for the cells and one for
the rules.
:72KL 0%--#*
:72KL /3-%#%2*
MV45 1
0%--# ' 7%; :72K;:&2<L*
Arbitrarily starting with rule 90 /3-%#%2 ' 1BC)CBC)C)CBC)CB@*
E8/ 4:72 : ' B* : P 0%--#N-%7?2<* :((5 1
0%--#K:L ' B*
@
All cells start with state 0, except the center
cell has state 1.
0%--#K0%--#N-%7?2<=>L ' )*
@
A8:& ?%7%/,2%45 1
Compute the next generation. :72KL 7%!2?%7 ' 7%; :72K0%--#N-%7?2<L*
E8/ 4:72 : ' )* : P 0%--#N-%7?2<6)* :((5 1
:72 -%E2 ' 0%--#K:6)L*
:72 9% ' 0%--#K:L*
:72 /:?<2 ' 0%--#K:()L*
7%!2?%7K:L ' /3-%#4-%E2C 9%C /:?<25*
@
0%--# ' 7%!2?%7*
@
Look up a new state from the ruleset. :72 /3-%# 4:72 ,C :72 IC :72 05 1
[2/:7? # ' TT ( , ( I ( 0*
:72 :7&%! ' c72%?%/N$,/#%c724#C>5*
/%23/7 /3-%#%2K:7&%!L*
@
@
L"> \.48&;< 4; M%(E(;'4./ P! L"> \.48&;< 4; M%(E(;'4./ P!
Whot`s mlsslng? Prsumobly, lt`s our lntntlon to dlsploy clls ond thlr stots ln vlsuol orm.
As w sow orllr, th stondord tchnlqu or dolng thls ls to stock th gnrotlons on on
top o och othr ond drow o rctongl thot ls block [or stot Jj or whlt [or stot 0j.
Choptr 7. Cllulor Automoto
336
Bor w lmplmnt thls portlculor vlsuollzotlon, |`d llk to polnt out two thlngs.
On, thls vlsuol lntrprtotlon o th doto ls compltly lltrol. |t`s usul or dmonstrotlng th
olgorlthms ond rsults o Wolrom`s lmntory CA, but lt shouldn`t ncssorlly drlv your own
prsonol work. |t`s rothr unllkly thot you or bulldlng o projct thot nds prclsly thls
olgorlthm wlth thls vlsuol styl. 5o whll lornlng to drow th CA ln thls woy wlll hlp you
undrstond ond lmplmnt CA systms, thls sklll should xlst only os o oundotlon.
5cond, th oct thot w or vlsuollzlng o on-dlmnslonol CA wlth o two-dlmnslonol lmog
con b conuslng. |t`s vry lmportont to rmmbr thot thls ls not o 2L CA. W or slmply
chooslng to show o hlstory o oll th gnrotlons stockd vrtlcolly. 1hls tchnlqu crots o
two-dlmnslonol lmog out o mony lnstoncs o on-dlmnslonol doto. But th systm ltsl ls
on-dlmnslonol. Lotr, w or golng to look ot on octuol 2L CA [th Gom o Llj ond
dlscuss how w mlght choos to dlsploy such o systm.
1h good nws ls thot drowlng th CA ls not portlculorly dllcult. Lt`s bgln by looklng ot
how w would rndr o slngl gnrotlon. Assum w hov o Procsslng wlndow 600 plxls
wld ond w wont och cll to b o J0xJ0 squor. W thror hov o CA wlth 60 clls. O
cours, w con colculot thls volu dynomlcolly.
Assumlng w`v gon through th procss o gnrotlng th cll stots [whlch w dld ln th
prvlous sctlonj, w con now loop through th ntlr orroy o clls, drowlng o block cll whn
th stot ls J ond o whlt on whn th stot ls 0.
Iiure ;.:z (repected)
:72 ; ' )B*
How many cells fit across given a certain
width
:72KL 0%--# ' 7%; :72K;:&2<=;L*
E8/ 4:72 : ' B* : P 0%--#N-%7?2<* :((5 1
Black or white fill? :E 40%--#K:L '' )5 E:--4B5*
%-#% E:--4>JJ5*
1h Notur o Cod [v005j
337
|n truth, w could optlmlz th obov by hovlng o whlt bockground ond only drowlng whn
thr ls o block cll [sovlng us th work o drowlng mony whlt squorsj, but ln most coss
thls solutlon ls good nough [ond ncssory or othr mor sophlstlcotd dslgns wlth
vorylng colors, tc.j Also, l w wontd och cll to b rprsntd os o slngl plxl, w
would not wont to us Procsslng`s /%0245 unctlon, but rothr occss th plxl orroy
dlrctly.
|n th obov cod, you`ll notlc th y-locotlon or och rctongl ls 0. | w wont th
gnrotlons to b drown nxt to och othr, wlth och row o clls morklng o nw
gnrotlon, w`ll olso nd to comput o y-locotlon bosd on how mony ltrotlons o th CA
w`v xcutd. W could occompllsh thls by oddlng o gnrotlon" vorlobl [on lntgrj to
our CA closs ond lncrmntlng lt och tlm through ?%7%/,2%45. Wlth ths oddltlons, w
con now look ot th CA closs wlth oll th oturs or both computlng ond drowlng th CA.
IJ&7:5# AK;L M*5+)&7 #5#7#1'&)U 0#55(5&) &('*7&'&
Notice how the x-location is the cell index
times the cell width. n the above scenario,
this would give us cells located at x equals
0, 10, 20, 30, all the way up to 600.
/%024:Q;C BC ;C ;5*
@
0-,## MV 1
:72KL 0%--#*
:72KL /3-%#%2*
:72 ; ' )B*
The CA should keep track of how many
generations.
:72 ?%7%/,2:87 ' B*
MV45 1
0%--# ' 7%; :72K;:&2<=;L*
/3-%#%2 ' 1BC)CBC)C)CBC)CB@*
0%--#K0%--#N-%7?2<=>L ' )*
@
Choptr 7. Cllulor Automoto
338
Function to compute the next generation A8:& ?%7%/,2%45 1
:72KL 7%!2?%7 ' 7%; :72K0%--#N-%7?2<L*
E8/ 4:72 : ' )* : P 0%--#N-%7?2<6)* :((5 1
:72 -%E2 ' 0%--#K:6)L*
:72 9% ' 0%--#K:L*
:72 /:?<2 ' 0%--#K:()L*
7%!2?%7K:L ' /3-%#4-%E2C 9%C /:?<25*
@
0%--# ' 7%!2?%7*
ncrement the generation counter. ?%7%/,2:87((*
@
:72 /3-%#4:72 ,C :72 IC :72 05 1
[2/:7? # ' TT ( , ( I ( 0*
:72 :7&%! ' c72%?%/N$,/#%c724#C>5*
/%23/7 /3-%#%2K:7&%!L*
@
E8/ 4:72 : ' B* : P 0%--#N-%7?2<* :((5 1
:E 40%--#K:L '' )5 E:--4B5*
%-#% E:--4>JJ5*
Set the y-location according to the
generation.
/%024:Q;C ?%7%/,2:87Q;C ;C ;5*
@
@
Lxpond Lxompl 7.J to hov th ollowlng otur. whn th CA rochs th bottom o
th Procsslng wlndow, th CA storts ovr wlth o nw, rondom rulst.
MO(.2&-( L"# MO(.2&-( L"#
Lxomln whot pottrns occur l you lnltlollz th lrst gnrotlon wlth och cll hovlng o
rondom stot.
MO(.2&-( L"0 MO(.2&-( L"0
Vlsuollz th CA ln o non-trodltlonol woy. Brok oll th ruls you con, don`t l tld to
uslng squors on o prct grld wlth block ond whlt.
MO(.2&-( L"= MO(.2&-( L"=
1h Notur o Cod [v005j
339
Crot o vlsuollzotlon o th CA thot scrolls upwords os th gnrotlons lncros so
thot you con vlw th gnrotlons to lnlnlty." Hlnt. lnstod o kplng trock o only
on gnrotlon ot o tlm, you`ll nd to stor o hlstory o gnrotlons, olwoys oddlng
o nw on ond dltlng th oldst on ln och rom.
MO(.2&-( L"> MO(.2&-( L">
L"? 6*%+.4E P%4--&+&24'&*; L"? 6*%+.4E P%4--&+&24'&*;
Bor w mov on to looklng ot CA ln two dlmnslons, lt`s worth toklng o brl look ot
Wolrom`s clossllcotlon or cllulor outomoto. As w notd orllr, th vost mojorlty o
lmntory CA rulsts produc unlnsplrlng rsults, whll som rsult ln wondrously
complx pottrns llk thos ound ln notur. Wolrom hos dlvldd up th rong o outcoms
lnto our closss.
M'()) 53 R./;!1-/&@6 M'()) 53 R./;!1-/&@6 Closs J CAs nd up, otr som numbr o gnrotlons, wlth vry cll
constont. 1hls ls not trrlbly xcltlng to wotch. Rul 222 [obovj ls o closs J CA, l you run lt
or nough gnrotlons, vry cll wlll vntuolly bcom ond rmoln block.
Iiure ;.:8: Rule zzz
Iiure ;.:p: Rule :po
Choptr 7. Cllulor Automoto
340
M'()) X3 S$A$&/&/!.6 M'()) X3 S$A$&/&/!.6 Llk closs J CAs, closs 2 CAs rmoln stobl, but th cll stots or not
constont. Rothr, thy osclllot ln som rgulor pottrn bock ond orth rom 0 to J to 0 to J ond
so on. |n rul J90 [obovj, och cll ollows th squnc JJJ0JJJ0JJJ0JJJ0JJJ0.
M'()) 73 S(.8!-6 M'()) 73 S(.8!-6 Closs 3 CAs oppor rondom ond hov no oslly dlscrnlbl pottrn. |n oct,
rul 30 [obovj ls usd os o rondom numbr gnrotor ln Wolrom`s Mothmotlco sotwor.
Agoln, thls ls o momnt whr w con l omozd thot such o slmpl systm wlth slmpl ruls
con dscnd lnto o chootlc ond rondom pottrn.
M'()) Z3 M!-A'$K/&@6 M'()) Z3 M!-A'$K/&@6 Closs 4 CAs con b thought o os o mlx btwn closs 2 ond closs 3.
On con lnd rptltlv, osclllotlng pottrns lnsld th CA, but whr ond whn ths pottrns
oppor ls unprdlctobl ond smlngly rondom. Closs 4 CA xhlblt th proprtls o complx
systms thot w dscrlbd orllr ln thls choptr ond ln Choptr 6. | o closs 3 CA wowd you,
thn o closs 4 llk Rul JJ0 obov should rolly blow your mlnd.
Iiure ;.zo: Rule o
Iiure ;.z:: Rule ::o
Lxrcls. Crot o Procsslng sktch thot sovs on lmog or vry posslbl rulst.
Con you clossly thm?
MO(.2&-( L"? MO(.2&-( L"?
1h Notur o Cod [v005j
34J
L"K @,( e4E( *+ V&+( L"K @,( e4E( *+ V&+(
1h nxt stp w or golng to tok ls to mov rom o on-dlmnslonol CA to o two-
dlmnslonol on. 1hls wlll lntroduc som oddltlonol complxlty, och cll wlll hov o blggr
nlghborhood, but thot wlll opn up th door to o rong o posslbl oppllcotlons. Atr oll,
most o whot w do ln computr grophlcs llvs ln two dlmnslons, ond thls choptr wlll
dmonstrot how to opply CA thlnklng to whot w drow ln our Procsslng sktchs.
|n J970, Mortln Gordnr wrot on ortlcl ln 5c|ent|t|c Amet|con thot documntd
mothmotlclon John Conwoy`s nw Gom o Ll," dscrlblng lt os rcrotlonol"
mothmotlcs ond suggstlng thot th rodr gt out o chssboord ond som chckrs ond
ploy." Whll th Gom o Ll hos bcom somthlng o o computotlonol cllch [mok not
o th myrlod projcts thot dlsploy th Gom o Ll on LLLs, scrns, projctlon surocs,
tc.j, lt ls stlll lmportont or us to bulld lt rom scrotch. |or on, lt provlds o good
opportunlty to proctlc our skllls wlth two-dlmnslonol orroys, objct orlntotlon, tc. But
prhops mor lmportontly, lts cor prlnclpls or tld dlrctly to our cor goolsslmulotlng
th noturol world wlth cod. 1hough w moy wont to ovold slmply dupllcotlng lt wlthout o
grot dol o thought or cor, th olgorlthm ond lts tchnlcol lmplmntotlon wlll provld us
wlth th lnsplrotlon ond oundotlon to bulld slmulotlons thot xhlblt th choroctrlstlcs ond
bhovlors o blologlcol systms o rproductlon.
nllk von Numonn, who crotd on xtroordlnorlly complx systm o stots ond ruls,
Conwoy wontd to ochlv o slmllor llllk" rsult wlth th slmplst st o ruls posslbl.
Mortln Gordnr outllnd Conwoy`s gools os ollows.
:. There should be no initicl pcttern jor uhich there is c simple prooj thct the populction
ccn rou uithout limit. z. There should be initicl pctterns thct cppcrentl do rou
uithout limit. . There should be simple initicl pctterns thct rou cnd chcne jor c
considercble period oj time bejore comin to cn end in three possible ucs: jcdin cuc
completel (jrom otercroudin or becomin too spcrse), settlin into c stcble
conjiurction thct remcins unchcned therecjter, or enterin cn oscillctin phcse in
uhich the repect cn endless ccle oj tuo or more periods.
-Mcrtin Gcrdner, 6.-&,4-O-. >%&2-.$, CE443PQQRRRS-K-K?-0S027Q?-O&3$44&2,'Q
0.40K&2LMN9SE4%?D zz (Dctober :p;o): :zo-:z.
1h obov mlght sound o blt cryptlc, but lt ssntlolly dscrlbs o Wolrom closs 4 CA. 1h
CA should b pottrnd but unprdlctobl ovr tlm, vntuolly sttllng lnto o unlorm or
osclllotlng stot. |n othr words, though Conwoy dldn`t us thls trmlnology, lt should hov
oll thos proprtls o o comp|ex system thot w kp mntlonlng.
Lt`s look ot how th Gom o Ll works. |t won`t tok up too much tlm or spoc, slnc
w`v covrd th boslcs o CA olrody.
Choptr 7. Cllulor Automoto
342
|lrst, lnstod o o lln o clls, w now hov
o two-dlmnslonol motrlx o clls. As wlth
th lmntory CA, th posslbl stots or 0
or J. Only ln thls cos, slnc w`r tolklng
obout ll," 0 mons dod ond J mons
ollv.
1h cll`s nlghborhood hos olso xpondd.
| o nlghbor ls on odjocnt cll, o
nlghborhood ls now nln clls lnstod o
thr.
Wlth thr clls, w hod o 3-blt numbr or
lght posslbl conlgurotlons. Wlth nln
clls, w hov 9 blts, or 5J2 posslbl
nlghborhoods. |n most coss, lt would b
lmproctlcol to dln on outcom or vry
slngl posslblllty. 1h Gom o Ll gts
oround thls problm by dlnlng o st o ruls occordlng to gnrol choroctrlstlcs o th
nlghborhood. |n othr words, ls th nlghborhood ovrpopulotd wlth ll? 5urroundd by
doth? Or just rlght? Hr or th ruls o ll.
J. E$(&+6 E$(&+6 | o cll ls ollv [stot Jj lt wlll dl [stot bcoms 0j undr th ollowlng
clrcumstoncs.
d0$1A!A:'(&/!.3 d0$1A!A:'(&/!.3 | th cll hos our or mor ollv nlghbors, lt dls.
_!.$'/.$))3 _!.$'/.$))3 | th cll hos on or wr ollv nlghbors, lt dls.
2. T/1&+6 T/1&+6 | o cll ls dod [stot 0j lt wlll com to ll [stot bcoms Jj l lt hos xoctly
thr ollv nlghbors [no mor, no lssj.
3. Q&()/)6 Q&()/)6 |n oll othr coss, th cll stot dos not chong. 1o b thorough, lt`s
dscrlb thos scnorlos.
Q&(@/.2 D'/0$3 Q&(@/.2 D'/0$3 | o cll ls ollv ond hos xoctly two or thr llv nlghbors,
lt stoys ollv.
Q&(@/.2 E$(83 Q&(@/.2 E$(83 | o cll ls dod ond hos onythlng othr thon thr llv
nlghbors, lt stoys dod.
Lt`s look ot o w xompls.
Iiure ;.zz
1h Notur o Cod [v005j
343
Wlth th lmntory CA, w wr obl to look ot oll th gnrotlons nxt to och othr,
stockd os rows ln o 2L grld. Wlth th Gom o Ll, howvr, th CA ltsl ls ln two
dlmnslons. W could try crotlng on loborot 3L vlsuollzotlon o th rsults ond stock oll
th gnrotlons ln o cub structur [ond ln oct, you mlght wont to try thls os on xrclsj.
Nvrthlss, th typlcol woy th Gom o Ll ls dlsployd ls to trot och gnrotlon os o
slngl rom ln on onlmotlon. 5o lnstod o vlwlng oll th gnrotlons ot onc, w s thm
on ot o tlm, ond th rsult rsmbls ropldly growlng boctrlo ln o ptrl dlsh.
On o th xcltlng ospcts o th Gom o Ll ls thot thr or lnltlol pottrns thot ylld
lntrlgulng rsults. |or xompl, som rmoln stotlc ond nvr chong.
1hr or pottrns thot osclllot bock ond orth btwn two stots.
Iiure ;.z
Iiure ;.z(
Iiure ;.z
Choptr 7. Cllulor Automoto
344
And thr or olso pottrns thot rom gnrotlon to gnrotlon mov obout th grld. [|t`s
lmportont to not thot th clls thmslvs orn`t octuolly movlng, olthough w s th
opporonc o motlon ln th rsult os th clls turn on ond o.j
| you or lntrstd ln ths pottrns, thr or svrol good out o th box" Gom o Ll
dmonstrotlons onlln thot ollow you to conlgur th CA`s lnltlol stot ond wotch lt run ot
vorylng spds. 1wo xompls you mlght wont to xomln or.
- Lxplorlng Lmrgnc [http.//llk.mdlo.mlt.du/projcts/mrgnc/j by Mltchl
Rsnlck ond Brlon 5llvrmon, Lllong Klndrgortn Group, M|1 Mdlo Loborotory
- Conwoy`s Gom o Ll [http.//stvnklls.glthub.com/ConwoysGomOLlj by
5tvn Klls [uss Procsslng.js!j
|or th xompl w`ll bulld rom scrotch ln th nxt sctlon, lt wlll b oslr to slmply
rondomly st th stots or och cll.
Iiure ;.z
L"L 5.*<.4EE&;< ',( e4E( *+ V&+( L"L 5.*<.4EE&;< ',( e4E( *+ V&+(
Now w just nd to xtnd our cod rom th Wolrom CA to two dlmnslons. W usd o
on-dlmnslonol orroy to stor th llst o cll stots bor, ond or th Gom o Ll, w con
us o two-dlmnslonol orroy [http.//www.procsslng.org/lornlng/2dorroy/j.
W`ll bgln by lnltlollzlng och cll o th boord wlth o rondom stot. 0 or J.
:72KLKL I8,/& ' 7%; :72K08-397#LK/8;#L*
E8/ 4:72 ! ' B* ! P 08-397#* !((5 1
E8/ 4:72 " ' B* " P /8;#* "((5 1
nitialize each cell with a 0 or 1. 03//%72K!LK"L ' :724/,7&894>55*
@
@
1h Notur o Cod [v005j
345
And to comput th nxt gnrotlon, just os bor, w nd o rsh 2L orroy to wrlt to os
w onolyz och cll`s nlghborhood ond colculot o nw stot.
OK. Bor w con sort out how to octuolly
colculot th nw stot, w nd to know
how w con rrnc och cll`s nlghbor.
|n th cos o th JL CA, thls wos slmpl. l
o cll lndx wos :, lts nlghbors wr l-J
ond lJ. Hr och cll dosn`t hov o
slngl lndx, but rothr o column ond row
lndx. x,y. As shown ln |lgur 7.27, w con
s thot lts nlghbors or. (x-!,y-!I (x,y-!I,
(x-!,y-2I, (x-!,yI, (x-!,yI, (x-!,y-!I, (x,y-!I, ond
(x-!,y-!I.
All o th Gom o Ll ruls oprot by
knowlng how mony nlghbors or ollv. 5o
l w crot o nlghbor countr vorlobl
ond lncrmnt lt och tlm w lnd o
nlghbor wlth o stot o J, w`ll hov th
totol o llv nlghbors.
:72KLKL 7%!2 ' 7%; :72K08-397#LK/8;#L*
E8/ 4:72 ! ' B* ! P 08-397#* !((5 1
E8/ 4:72 " ' B* " P /8;#* "((5 1
We need a new state for each cell. 7%!2K!LK"L ' aaaaaaaaaaaaaaai*
@
@
Iiure ;.z;
:72 7%:?<I8/# ' B*
Top row of neighbors :E 4I8,/&K!6)LK"6)L '' )5 7%:?<I8/#((*
:E 4I8,/&K! LK"6)L '' )5 7%:?<I8/#((*
:E 4I8,/&K!()LK"6)L '' )5 7%:?<I8/#((*
Middle row of neighbors (note we don't
count self)
:E 4I8,/&K!6)LK"L '' )5 7%:?<I8/#((*
:E 4I8,/&K!()LK"L '' )5 7%:?<I8/#((*
Bottom row of neighbors :E 4I8,/&K!6)LK"()L '' )5 7%:?<I8/#((*
:E 4I8,/&K! LK"()L '' )5 7%:?<I8/#((*
:E 4I8,/&K!()LK"()L '' )5 7%:?<I8/#((*
Choptr 7. Cllulor Automoto
346
And ogoln, just os wlth th Wolrom CA, w lnd ourslvs ln o sltuotlon whr th obov ls o
usul ond clor woy to wrlt th cod or tochlng purposs, ollowlng us to s vry stp
[och tlm w lnd o nlghbor wlth o stot o on, w lncros o countrj. Nvrthlss, lt`s o
blt sllly to soy, | th cll stot quols on, odd on to o countr" whn w could just soy,
Add th cll stot to o countr." Atr oll, l th stot ls only o 0 or J, th sum o oll th
nlghbors` stots wlll ylld th totol numbr o llv clls. 5lnc th nlghbors or orrongd ln o
mlnl 3x3 grld, w con odd thm oll up wlth onothr loop.
O cours, w`v mod o mlstok ln th cod obov. |n th Gom o Ll, th cll ltsl dos
not count os on o th nlghbors. W could us o condltlonol to sklp oddlng th stot whn
both : ond o quol 0, but onothr optlon would b to just subtroct th cll stot onc w`v
lnlshd th loop.
|lnolly, onc w know th totol numbr o llv nlghbors, w con dcld whot th cll`s nw
stot should b occordlng to th ruls. blrth, doth, or stosls.
Puttlng thls oll togthr, w hov.
E8/ 4:72 : ' 6)* : P' )* :((5 1
E8/ 4:72 o ' 6)* o P' )* o((5 1
Add up all the neighbors' states. 7%:?<I8/# (' I8,/&K!(:LK"(oL*
@
@
Whoops! Subtract the cell's state, which we
don't want in the total.
7%:?<I8/# 6' I8,/&K!LK"L*
f it is alive and has less than 2 live
neighbors, it dies from loneliness.
:E 44I8,/&K!LK"L '' )5 mm 47%:?<I8/# P >55 1
7%!2K!LK"L ' B*
@
f it is alive and has more than 3 live
neighbors, it dies from overpopulation.
%-#% :E 44I8,/&K!LK"L '' )5 mm 47%:?<I8/# ^ H55 1
7%!2K!LK"L ' B*
@
f it is dead and has exactly 3 live
neighbors, it is born!
%-#% :E 44I8,/&K!LK"L '' B5 mm 47%:?<I8/# '' H55 1
7%!2K!LK"L ' )*
@
n all other cases, its state remains the
same.
%-#% 1
7%!2K!LK"L ' I8,/&K!LK"L*
@
The next board :72KLKL 7%!2 ' 7%; :72K08-397#LK/8;#L*
1h Notur o Cod [v005j
347
|lnolly, onc th nxt gnrotlon ls colculotd, w con mploy th som mthod w usd to
drow th Wolrom CAo squor or och spot, whlt or o, block or on.
IJ&7:5# AK<L R&7# *+ _/+#
Looping but skipping the edge cells E8/ 4:72 ! ' )* ! P 08-397#6)* !((5 1
E8/ 4:72 " ' )* " P /8;#6)* "((5 1
Add up all the neighbor states to calculate
the number of live neighbors.
:72 7%:?<I8/# ' B*
E8/ 4:72 : ' 6)* : P' )* :((5 1
E8/ 4:72 o ' 6)* o P' )* o((5 1
7%:?<I8/# (' I8,/&K!(:LK"(oL*
@
@
Correct by subtracting the cell state itself. 7%:?<I8/# 6' I8,/&K!LK"L*
The ruIes of Iife!
:E 44I8,/&K!LK"L '' )5 mm 47%:?<I8/# P >55 7%!2K!LK"L ' B*
%-#% :E 44I8,/&K!LK"L '' )5 mm 47%:?<I8/# ^ H55 7%!2K!LK"L ' B*
%-#% :E 44I8,/&K!LK"L '' B5 mm 47%:?<I8/# '' H55 7%!2K!LK"L ' )*
%-#% 7%!2K!LK"L ' I8,/&K!LK"L*
@
@
The 2D array "next is now the current
board.
I8,/& ' 7%!2*
E8/ 4 :72 : ' B* : P 08-397#*:((5 1
E8/ 4 :72 o ' B* o P /8;#*o((5 1
Black when state = 1 :E 44I8,/&K:LKoL '' )55 E:--4B5*
Choptr 7. Cllulor Automoto
348
White when state = 0 %-#% E:--4>JJ5*
#2/8.%4B5*
/%024:Q;C oQ;C ;C ;5*
@
@
Crot o Gom o Ll slmulotlon thot ollows you to monuolly conlgur th grld by
drowlng or wlth spcllc known pottrns.
MO(.2&-( L"K MO(.2&-( L"K
|mplmnt wrop-oround" or th Gom o Ll so thot clls on th dgs hov
nlghbors on th opposlt sld o th grld.
MO(.2&-( L"L MO(.2&-( L"L
Whll th obov solutlon [Lxompl 7.2j ls convnlnt, lt ls not portlculorly mmory-
lclnt. |t crots o nw 2L orroy or vry rom o onlmotlon! 1hls mottrs vry llttl
or o Procsslng dsktop oppllcotlon, but l you wr lmplmntlng th Gom o Ll on
o mlcrocontrollr or mobll dvlc, you`d wont to b mor corul. On solutlon ls to
hov only two orroys ond constontly swop thm, wrltlng th nxt st o stots lnto
whlchvr on lsn`t th currnt orroy. |mplmnt thls portlculor solutlon.
MO(.2&-( L"N MO(.2&-( L"N
L"N F)G(2'ZF.&(;'(9 P(%%- L"N F)G(2'ZF.&(;'(9 P(%%-
Ovr th cours o th prvlous slx choptrs, w`v slowly bullt xompls o systms o
obects wlth proprtls thot mov obout th scrn. And ln thls choptr, olthough w`v bn
tolklng obout o cll" os l lt wr on objct, w octuolly hovn`t bn uslng ony objct
orlntotlon ln our cod [othr thon o closs to dscrlb th CA systm os o wholj. 1hls hos
workd bcous o cll ls such on normously slmpl objct [o slngl bltj. Howvr, ln o
momnt, w or golng to dlscuss som ldos or urthr dvloplng CA systms, mony o
whlch lnvolv kplng trock o multlpl proprtls or och cll. |or xompl, whot l o cll
ndd to rmmbr lts lost tn stots? Or whot l w wontd to opply som o our motlon
ond physlcs thlnklng to o CA ond hov th clls mov obout th wlndow, dynomlcolly
chonglng thlr nlghbors rom rom to rom?
1h Notur o Cod [v005j
349
1o occompllsh ony o ths ldos [ond morj, lt would b hlpul to s how w mlght trot
o cll os on objct wlth multlpl proprtls, rothr thon os o slngl 0 or J. 1o show thls, lt`s
just rcrot th Gom o Ll slmulotlon. Only lnstod o.
Lt`s hov.
whr M%-- ls o closs w wlll wrlt. Whot or th proprtls o o M%-- objct? |n our Gom
o Ll xompl, och cll hos o locotlon ond slz, os wll os o stot.
|n th non-OOP vrslon, w usd o sporot 2L orroy to kp trock o th stots or th
currnt ond nxt gnrotlon. By moklng o cll on objct, howvr, och cll could kp
trock o both stots. |n thls cos, w`ll thlnk o th cll os rmmbrlng lts prvlous stot [or
whn nw stots nd to b computdj.
1hls ollows us to vlsuollz mor lnormotlon obout whot th stot ls dolng. |or xompl, w
could choos to color o cll dlrntly l lts stot hos chongd. |or xompl.
IJ&7:5# AK=L R&7# *+ _/+# YY9
:72KLKL I8,/&*
M%--KLKL I8,/&*
0-,## M%-- 1
Location and size E-8,2 !C "*
E-8,2 ;*
What is the cell's state? :72 #2,2%*
What was its previous state? :72 $/%A:83#*
A8:& &:#$-,"45 1
Choptr 7. Cllulor Automoto
350
Not much ls obout th cod [ot lost or our purposs hrj hos to chong. 1h nlghbors
con stlll b countd th som woy, th dlrnc ls thot w now nd to rr to th objct`s
stot vorlobls os w loop through th 2L orroy.
f the cell is born, color it blue! :E 4$/%A:83# '' B mm #2,2% '' )5 E:--4BCBC>JJ5*
%-#% :E 4#2,2% '' )5 E:--4B5*
%-#% :E 4$/%A:83# '' ) mm #2,2% '' B5 E:--4>JJCBCB5*
%-#% E:--4>JJ5*
/%024!C "C ;C ;5*
@
f the cell dies, color it red!
E8/ 4:72 ! ' )* ! P 08-397#6)* !((5 1
E8/ 4:72 " ' )* " P /8;#6)* "((5 1
:72 7%:?<I8/# ' B*
E8/ 4:72 : ' 6)* : P' )* :((5 1
E8/ 4:72 o ' 6)* o P' )* o((5 1
Use the previous state when tracking
neighbors.
#$2GH68). K" 68&)1[IK2\[3Kt\-0)$L284.,
@
@
7%:?<I8/# 6' I8,/&K!LK"LN$/%A:83#*
We are calling a function newState() to
assign a new state to each cell.
:E 44I8,/&K!LK"LN#2,2% '' )5 mm 47%:?<I8/# P >55 I8,/&K!LK"LN7%;[2,2%4B5*
%-#% :E 44I8,/&K!LK"LN#2,2% '' )5 mm 47%:?<I8/# ^ H55 I8,/&K!LK"LN7%;[2,2%4B5*
%-#% :E 44I8,/&K!LK"LN#2,2% '' B5 mm 47%:?<I8/# '' H55 I8,/&K!LK"LN7%;[2,2%4)5*
else do nothing! @
@
L"W R4.&4'&*;- *+ @.49&'&*;4% P! L"W R4.&4'&*;- *+ @.49&'&*;4% P!
Now thot w hov covrd th boslc concpts, olgorlthms, ond progrommlng strotgls
bhlnd th most omous JL ond 2L cllulor outomoto, lt`s tlm to thlnk obout how you mlght
tok thls oundotlon o cod ond bulld on lt, dvloplng crotlv oppllcotlons o CAs ln your
own work. |n thls sctlon, w`ll tolk through som ldos or xpondlng th oturs o th CA
xompls. Lxompl onswrs to och o ths xrclss con b ound on th book wbslt.
5P ^!.H1$%&(.2:'(1 b1/8) 5P ^!.H1$%&(.2:'(1 b1/8). 1hr`s no portlculor roson why you should llmlt yoursl to hovlng
your clls on o rctongulor grld. Whot hoppns l you dslgn o CA wlth onothr typ o shop?
1h Notur o Cod [v005j
35J
XP N1!"("/'/)&/% XP N1!"("/'/)&/%. 1h ruls o o CA don`t ncssorlly hov to dln on xoct outcom.
7P M!.&/.:!:) 7P M!.&/.:!:). W`v lookd ot xompls whr th cll`s stot con only b o J or o 0. But
whot l th cll`s stot wos o lootlng polnt numbr btwn 0 ond J?
ZP ]-(2$ N1!%$))/.2 ZP ]-(2$ N1!%$))/.2. W brlly touchd on thls orllr, but mony lmog-procsslng
olgorlthms oprot on CA-llk ruls. Blurrlng on lmog ls crotlng o nw plxl out o th
ovrog o o nlghborhood o plxls. 5lmulotlons o lnk dlsprslng on popr or wotr
rlppllng ovr on lmog con b ochlvd wlth CA ruls.
Crot o CA uslng o grld o hxogons [os blowj, och wlth slx nlghbors.
MO(.2&-( L"W MO(.2&-( L"W
Rwrlt th Gom o Ll ruls os ollows.
Ovrpopulotlon. | th cll hos our or mor ollv nlghbors, lt hos o 80 chonc o
dylng.
Lonllnss. | th cll hos on or wr ollv nlghbors, lt hos o 60 chonc o dylng.
Ltc.
MO(.2&-( L"#T MO(.2&-( L"#T
Adopt Wolrom lmntory CA to hov th stot b o loot. You could dln ruls
such os, | th stot ls grotr thon 0.5" or .lss thon 0.2."
MO(.2&-( L"## MO(.2&-( L"##
Choptr 7. Cllulor Automoto
352
<P e/)&!1/%(' <P e/)&!1/%('. |n th Gom o Ll objct-orlntd xompl, w usd two vorlobls to kp
trock o lts stot. currnt ond prvlous. Whot l you us on orroy to kp trock o o cll`s stot
hlstory? 1hls rlots to th ldo o o complx odoptlv systm," on thot hos th oblllty to
odopt ond chong lts ruls ovr tlm by lornlng rom lts hlstory. W`ll s on xompl o thls
ln Choptr J0. Nurol Ntworks.
fP [!0/.2 %$'') fP [!0/.2 %$''). |n ths boslc xompls, clls hov o lxd posltlon on o grld, but you could
bulld o CA wlth clls thot hov no lxd posltlon ond lnstod mov obout th scrn.
gP ^$)&/.2 gP ^$)&/.2. Anothr otur o complx systms ls thot thy con b nstd. Our world tnds to
work thls woy. o clty ls o complx systm o popl, o prson ls o complx systm o orgons,
on orgon ls o complx systm o clls, ond so on ond so orth.
Crot o CA ln whlch o plxl ls o cll ond o color ls lts stot.
MO(.2&-( L"#0 MO(.2&-( L"#0
Vlsuollz th Gom o Ll by colorlng och cll occordlng to how long lt`s bn ollv or
dod. Con you olso us th cll`s hlstory to lnorm th ruls?
MO(.2&-( L"#= MO(.2&-( L"#=
s CA ruls ln o locklng systm. Whot l och bold hod o stot [thot prhops lnorms
lts strlng bhovlorsj ond lts nlghborhood chongd rom rom to rom os lt movd
closr to or urthr rom othr bolds?
MO(.2&-( L"#> MO(.2&-( L"#>
Lslgn o CA ln whlch och cll ltsl ls o smollr CA or o systm o bolds.
MO(.2&-( L"#? MO(.2&-( L"#?
1h Notur o Cod [v005j
353
@,( M2*-/-'(E 5.*G(2' @,( M2*-/-'(E 5.*G(2'
U'(Q L MO(.2&-(D
C;2*.Q*.4'( 2(%%:%4. 4:'*E4'4 &;'* /*:. (2*-/-'(E" U*E( Q*--&)&%&'&(-D
h e&I( (42, 2.(4':.( 4 -'4'(" f*8 24; ',4' -'4'( 9.&I( ',(&. )(,4I&*.7
@43&;< &;-Q&.4'&*; +.*E P!` ,*8 24; ',4' -'4'( 2,4;<( *I(. '&E(
422*.9&;< '* &'- ;(&<,)*.-H -'4'(-7
h P*;-&9(. ',( (2*-/-'(EH- 8*.%9 '* )( 4 P!" @,( 2.(4':.(- E*I( +.*E
'&%( '* '&%(" M42, '&%( ,4- 4 -'4'(d&- &' %4;97 84'(.7 +**97
h [-( 4 P! '* <(;(.4'( 4 Q4''(.; +*. ',( 9(-&<; *+ 4 2.(4':.( &; /*:.
(2*-/-'(E"
Choptr 7. Cllulor Automoto
354
,"&:'#) BK G)&0'&58 ,"&:'#) BK G)&0'&58
Pctholoiccl monstersl cried the terrijied mcthemcticicn
Eter one oj them c splinter in m ee
I hcte the Pecno Spcce cnd the Koch Curte
I jecr the Ccntor Terncr Set
The Sierpinsli Gcslet mcles me ucnnc cr
And c million miles cuc c butterjl jlcpped its uins
Dn c cold Notember dc c mcn ncmed enoit Mcndelbrot ucs born
! #0,$4E$, @0)?40,5 ?+2-.' O20% TH$,1&?K204 6&4U
Onc upon o tlm, | took o cours ln hlgh school colld Gomtry." Prhops you dld too. You
lornd obout shops ln on dlmnslon, two dlmnslons, ond moyb vn thr. Whot ls th
clrcumrnc o o clrcl? 1h oro o o rctongl? 1h dlstonc btwn o polnt ond o lln?
Com to thlnk o lt, w`v bn studylng gomtry oll olong ln thls book, uslng vctors to
dscrlb th motlon o bodls ln Cortslon spoc. 1hls sort o gomtry ls gnrolly rrrd
to os Luclldon gomtry, otr th Grk mothmotlclon Luclld.
Iiure 8.:
1h Notur o Cod [v005j
355
|or us notur codrs, w hov to osk th qustlon. Con w dscrlb our world wlth
Luclldon gomtry? 1h LCL scrn |`m storlng ot rlght now sur looks llk o rctongl.
And th plum | ot thls mornlng ls clrculor. But whot l | wr to look urthr, ond consldr
th trs thot lln th strt, th lovs thot hong o thos trs, th llghtnlng rom lost
nlght`s thundrstorm, th coulllowr | ot or dlnnr, th blood vssls ln my body, ond th
mountolns ond coostllns thot covr lond byond Nw York Clty? Most o th stu you lnd
ln notur connot b dscrlbd by th ldollzd gomtrlcol orms o Luclldon gomtry. 5o
l w wont to stort bulldlng computotlonol dslgns wlth pottrns byond th slmpl shops
%--:$#%45, /%0245, ond -:7%45, lt`s tlm or us to lorn obout th concpts bhlnd ond
tchnlqus or slmulotlng th gomtry o notur. roctols.
N"# 6,4' C- 4 S.42'4%7 N"# 6,4' C- 4 S.42'4%7
1h trm ;1(%&(' ;1(%&(' [rom th Lotln ttoctus, monlng brokn"j wos colnd by th
mothmotlclon Bnolt Mondlbrot ln J975. |n hls smlnol work 1h |roctol Gomtry o
Notur," h dlns o roctol os o rough or rogmntd gomtrlc shop thot con b spllt
lnto ports, och o whlch ls [ot lost opproxlmotlyj o rducd-slz copy o th whol."
Lt`s lllustrot thls dlnltlon wlth two slmpl xompls. |lrst, lt`s thlnk obout o tr
bronchlng structur [or whlch w`ll wrlt th cod lotrj.
Iiure 8.z: Dne oj the most uell-lnoun cnd reconizcble jrcctcl pctterns is ncmed jor enoit
Mcndelbrot himselj. Generctin the Mcndelbrot set intoltes testin the properties oj complex
numbers cjter the cre pcssed throuh cn iterctite junction. Do the tend to injinit? Do the stc
bounded? While c jcscinctin mcthemcticcl discussion, this esccpe-time clorithm is c less
prccticcl method jor enerctin jrcctcls thcn the recursite techniques ue'll excmine in this chcpter.
Houeter, cn excmple jor enerctin the Mcndelbrot set is included in the code excmples.
Choptr 8. |roctols
356
Notlc how th tr ln |lgur 8.3 hos o slngl root wlth two bronchs connctd ot lts nd.
Loch on o thos bronchs hos two bronchs ot lts nd ond thos bronchs hov two
bronchs ond so on ond so orth. Whot l w wr to pluck on bronch rom th tr ond
xomln lt on lts own?
Looklng closly ot o glvn sctlon o th tr, w lnd thot th shop o thls bronch rsmbls
th tr ltsl. 1hls ls known os )$';H)/-/'(1/&@ )$';H)/-/'(1/&@, os Mondlbrot stotd, och port ls o rducd-
slz copy o th whol."
1h obov tr ls prctly symmtrlcol ond th ports or, ln oct, xoct rpllcos o th whol.
Howvr, roctols do not hov to b prctly sl-slmllor. Lt`s tok o look ot o groph o th
stock morkt [odoptd rom octuol Appl stock dotoj.
And on mor.
Iiure 8.
Iiure 8.(
Iiure 8.: Grcph A
1h Notur o Cod [v005j
357
|n ths grophs, th x-oxls ls tlm ond th y-oxls ls th stock`s volu. |t`s not on occldnt thot
| omlttd th lobls, howvr. Grophs o stock morkt doto or xompls o roctols bcous
thy look th som ot ony scol. Ar ths grophs o th stock ovr on yor? On doy?
On hour? 1hr`s no woy or you to know wlthout o lobl. [|ncldntolly, groph A shows slx
months` worth o doto ond groph B zooms lnto o tlny port o groph A, showlng slx hours.j
1hls ls on xompl o o )&!%+()&/% )&!%+()&/% roctol, monlng thot lt ls bullt out o probobllltls ond
rondomnss. nllk th dtrmlnlstlc tr-bronchlng structur, lt ls stotlstlcolly sl-slmllor.
As w go through th xompls ln thls choptr, w wlll look ot both dtrmlnlstlc ond
stochostlc tchnlqus or gnrotlng roctol pottrns.
Whll sl-slmllorlty ls o ky trolt o roctols, lt`s lmportont to rollz thot sl-slmllorlty olon
dos not mok o roctol. Atr oll, o lln ls sl-slmllor. A lln looks th som ot ony scol,
ond con b thought o os comprlslng lots o llttl llns. But lt`s not o roctol. |roctols or
choroctrlzd by hovlng o ln structur ot smoll scols [kp zoomlng lnto th stock morkt
groph ond you`ll contlnu to lnd luctuotlonsj ond connot b dscrlbd wlth Luclldon
gomtry. | you con soy |t`s o lln!" thn lt`s not o roctol.
Anothr undomntol componnt o roctol gomtry ls rcurslon. |roctols oll hov o
rcurslv dlnltlon. W`ll stort wlth rcurslon bor dvloplng tchnlqus ond cod
xompls or bulldlng roctol pottrns ln Procsslng.
Iiure 8.: Grcph
Iiure 8.;
N"0 Y(2:.-&*; N"0 Y(2:.-&*;
Lt`s bgln our dlscusslon o rcurslon by xomlnlng th lrst opporonc o roctols ln
modrn mothmotlcs. |n J883, Grmon mothmotlclon Gorg Contor dvlopd slmpl
ruls to gnrot on lnlnlt st.
Choptr 8. |roctols
358
1hr ls o dbock loop ot work hr. 1ok o slngl lln ond brok lt lnto two. 1hn rturn to
thos two llns ond opply th som rul, broklng och lln lnto two, ond now w`r lt wlth
our. 1hn rturn to thos our llns ond opply th rul. Now you`v got lght. 1hls procss ls
known os 1$%:1)/!. 1$%:1)/!.. th rpotd oppllcotlon o o rul to succsslv rsults. Contor wos
lntrstd ln whot hoppns whn you opply ths ruls on lnlnlt numbr o tlms. W,
howvr, or worklng ln o lnlt plxl spoc ond con mostly lgnor th qustlons ond
porodoxs thot orls rom lnlnlt rcurslon. W wlll lnstod construct our cod ln such o woy
thot w do not opply th ruls orvr [whlch would cous our progrom to rzj.
Bor w lmplmnt th Contor st, lt`s tok o look ot whot lt mons to hov rcurslon ln
cod. Hr`s somthlng w`r usd to dolng oll th tlmcolllng o unctlon lnsld onothr
unctlon.
Whot would hoppn l w colld th unctlon w or dlnlng wlthln th unctlon ltsl? Con
#89%b3702:8745 coll #89%b3702:8745?
|n oct, thls ls not only ollowd, but lt`s qult common [ond ssntlol to how w wlll lmplmnt
th Contor stj. |unctlons thot coll thmslvs or tecuts|ve ond good or solvlng crtoln
problms. |or xompl, crtoln mothmotlcol colculotlons or lmplmntd rcurslvly, th
most common xompl ls toctot|o|.
1h octorlol o ony numbr n, usuolly wrlttn os n!, ls dlnd os.
#m " # F # u D F - - - - F E F > F D
?m " D
Hr w`ll wrlt o unctlon ln Procsslng thot uss o E8/ loop to colculot octorlol.
Iiure 8.8: The Ccntor set
A8:& #89%b3702:8745 1
Calling the function background() in the
definition of someFunction()
I,0.?/837&4B5*
@
A8:& #89%b3702:8745 1
#89%b3702:8745*
@
:72 E,028/:,-4:72 75 1
:72 E ' )*
1h Notur o Cod [v005j
359
pon clos xomlnotlon, you`ll notlc somthlng lntrstlng obout how octorlol works. Lt`s
look ot 4! ond 3!
<m " < F E F > F D
Em " E F > F D
&+$1$;!1$6 6 6 &+$1$;!1$6 6 6
<m " < F Em
|n mor gnrol trms, or ony posltlv lntgr n.
#m " # F *#TD+m
Dm " D
Wrlttn out.
1h toctot|o| o 7 ls dlnd os 7 tlms th toctot|o| o 76).
1h dlnltlon o ;(%&!1/(' ;(%&!1/(' lncluds ;(%&!1/(' ;(%&!1/('?! |t`s klnd o llk dlnlng tlrd" os th llng
you gt whn you or tlrd." 1hls concpt o sl-rrnc ln unctlons ls on xompl o
rcurslon. And w con us lt to wrlt o octorlol unctlon thot colls ltsl.
|t moy look crozy, but lt works. Hr or th stps thot hoppn whn E,028/:,-4D5 ls
colld.
Using a regular loop to compute factorial E8/ 4:72 : ' B* : P 7* :((5 1
E ' E Q 4:()5*
@
/%23/7 E*
@
:72 E,028/:,-4:72 75 1
:E 47 '' )5 1
/%23/7 )*
@ %-#% 1
/%23/7 7 Q E,028/:,-476)5*
@
@
Choptr 8. |roctols
360
W con opply th som prlnclpl to grophlcs wlth lntrstlng rsults, os w wlll s ln mony
xompls throughout thls choptr. 1ok o look ot thls rcurslv unctlon.
IJ&7:5# BK;L H#0()8/N# ,/)05#8 F
&/,;M:/0-%45 drows on lllps bosd on o st o poromtrs thot lt rclvs os orgumnts. |t
thn colls ltsl wlth thos som poromtrs, odjustlng thm sllghtly. 1h rsult ls o srls o
clrcls, och o whlch ls drown lnsld th prvlous clrcl.
Iiure 8.p
A8:& &/,;M:/0-%4:72 !C :72 "C E-8,2 /,&:3#5 1
%--:$#%4!C "C /,&:3#C /,&:3#5*
:E4/,&:3# ^ >5 1
/,&:3# Q' BNOJE*
The drawCircle() function is calling itself
recursively.
&/,;M:/0-%4!C "C /,&:3#5*
@
@
1h Notur o Cod [v005j
36J
Notlc thot th obov unctlon only rcurslvly colls ltsl l th rodlus ls grotr thon 2. 1hls
ls o cruclol polnt. As wlth ltrotlon, o|| tecuts|ve tunct|ons must hove on ex|t cond|t|on| You
llkly or olrody owor thot oll E8/ ond ;<:-% loops must lnclud o boolon xprsslon
thot vntuolly voluots to ols, thus xltlng th loop. Wlthout on, th progrom would
crosh, cought lnsld o on lnlnlt loop. 1h som con b sold obout rcurslon. | o rcurslv
unctlon colls ltsl orvr ond vr, you`ll b most llkly b trotd to o nlc rozn scrn.
1hls clrcls xompl ls rothr trlvlol, lt could oslly b ochlvd through slmpl ltrotlon.
Howvr, or scnorlos ln whlch o unctlon colls ltsl mor thon onc, rcurslon bcoms
wondrully lgont.
Lt`s mok &/,;M:/0-%45 o blt mor complx. |or vry clrcl dlsployd, drow o clrcl hol
lts slz to th lt ond rlght o thot clrcl.
IJ&7:5# BK<L H#0()8/*1 '4/0#
A8:& #%23$45 1
#:F%4DBBCDBB5*
#9882<45*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
&/,;M:/0-%4;:&2<=>C<%:?<2=>C>BB5*
@
A8:& &/,;M:/0-%4E-8,2 !C E-8,2 "C E-8,2 /,&:3#5 1
#2/8.%4B5*
78b:--45*
%--:$#%4!C "C /,&:3#C /,&:3#5*
:E4/,&:3# ^ >5 1
drawCircle() calls itself twice, creating a
branching effect. For every circle, a
smaller circle is drawn to the left and the
right.
&/,;M:/0-%4! ( /,&:3#=>C "C /,&:3#=>5*
&/,;M:/0-%4! 6 /,&:3#=>C "C /,&:3#=>5*
@
@
Choptr 8. |roctols
362
Wlth just o llttl mor cod, w could olso odd o clrcl obov ond blow och clrcl.
IJ&7:5# BK=L H#0()8/*1 +*() '/7#8
1ry rproduclng thls sktch wlth ltrotlon lnstod o rcurslon| dor you!
A8:& &/,;M:/0-%4E-8,2 !C E-8,2 "C E-8,2 /,&:3#5 1
%--:$#%4!C "C /,&:3#C /,&:3#5*
:E4/,&:3# ^ X5 1
&/,;M:/0-%4! ( /,&:3#=>C "C /,&:3#=>5*
&/,;M:/0-%4! 6 /,&:3#=>C "C /,&:3#=>5*
&/,;M:/0-%4!C " ( /,&:3#=>C /,&:3#=>5*
&/,;M:/0-%4!C " 6 /,&:3#=>C /,&:3#=>5*
@
@
N"= @,( P4;'*. U(' 8&', 4 Y(2:.-&I( S:;2'&*; N"= @,( P4;'*. U(' 8&', 4 Y(2:.-&I( S:;2'&*;
Now w`r rody to vlsuollz th Contor st ln Procsslng uslng o rcurslv unctlon. Whr
do w bgln? Wll, w know thot th Contor st bglns wlth o lln. 5o lt`s stort thr ond
wrlt o unctlon thot drows o lln.
1h obov 0,728/45 unctlon drows o lln thot storts ot plxl coordlnot (x,yI wlth o lngth o
-%7. [1h lln ls drown horlzontolly hr, but thls ls on orbltrory dclslon.j 5o l w colld thot
unctlon, soylng.
w`d gt th ollowlng.
A8:& 0,728/4E-8,2 !C E-8,2 "C E-8,2 -%75 1
-:7%4!C"C!(-%7C"5*
@
0,728/4)BC >BC ;:&2<6>B5*
1h Notur o Cod [v005j
363
Now, th Contor rul tlls us to ros th
mlddl thlrd o thot lln, whlch lovs us
wlth two llns, on rom th bglnnlng o
th lln to th on-thlrd mork, ond on rom
th two-thlrds mork to th nd o th lln.
W con now odd two mor llns o cod to
drow th scond polr o llns, movlng th
y-locotlon down o bunch o plxls so thot
w con s th rsult blow th orlglnol
lln.
Whll thls ls o ln stort, such o monuol opprooch o colllng -:7%45 or och lln ls not whot
w wont. |t wlll gt unwlldy vry qulckly, os w`d nd our, thn lght, thn slxtn colls to
-:7%45. Ys, o E8/ loop ls our usuol woy oround such o problm, but glv thot o try ond
you`ll s thot worklng out th moth or och ltrotlon qulckly provs lnordlnotly
compllcotd. Hr ls whr rcurslon coms ond rscus us.
1ok o look ot whr w drow thot lrst lln rom th stort to th on-thlrd mork.
|nstod o colllng th -:7%45 unctlon dlrctly, w con slmply coll th 0,728/45 unctlon
ltsl. Atr oll, whot dos th 0,728/45 unctlon do? |t drows o lln ot on (x,yI locotlon wlth o
glvn lngth! And so.
Iiure 8.:o
Iiure 8.::
A8:& 0,728/4E-8,2 !C E-8,2 "C E-8,2 -%75 1
-:7%4!C"C!(-%7C"5*
" (' >B*
From start to 1/3rd '2#$*IJ3JIK'$#;EJ3+,
From 2/3rd to end '2#$*IK'$#F>;EJ3JIK'$#J3+,
@
Iiure 8.:z
-:7%4!C"C!(-%7=HC"5*
-:7%4!C"C!(-%7=HC"5* I%089%# 6666666^ 0,728/4!C"C-%7=H5*
Choptr 8. |roctols
364
And or th scond lln.
Lovlng us wlth.
And slnc th 0,728/45 unctlon ls colld rcurslvly, th som rul wlll b opplld to th nxt
llns ond to th nxt ond to th nxt os 0,728/45 colls ltsl ogoln ond ogoln! Now, don`t go
ond run thls cod yt. W`r mlsslng thot cruclol lmnt. on xlt condltlon. W`ll wont to
mok sur w stop ot som polntor xompl, l th lngth o th lln vr ls lss thon J
plxl.
IJ&7:5# BK>L ,&1'*) 8#'
-:7%4!(-%7Q>=HC"C!(-%7C"5* I%089%# 6666666^ 0,728/4!(-%7Q>=HC"C-%7=H5*
A8:& 0,728/4E-8,2 !C E-8,2 "C E-8,2 -%75 1
-:7%4!C"C!(-%7C"5*
" (' >B*
0,728/4!C"C-%7=H5*
0,728/4!(-%7Q>=HC"C-%7=H5*
@
A8:& 0,728/4E-8,2 !C E-8,2 "C E-8,2 -%75 1
Stop at 1 pixel! :E 4-%7 ^' )5 1
-:7%4!C"C!(-%7C"5*
" (' >B*
0,728/4!C"C-%7=H5*
0,728/4!(-%7Q>=HC"C-%7=H5*
@
@
1h Notur o Cod [v005j
365
Lxrcls. slng &/,;M:/0-%45 ond th Contor st os modls, gnrot your own
pottrn wlth rcurslon. Hr ls o scrnshot o on thot uss llns.
MO(.2&-( N"# MO(.2&-( N"#
N"> @,( 1*2, P:.I( 4;9 ',( !..4/V&-' @(2,;&m:( N"> @,( 1*2, P:.I( 4;9 ',( !..4/V&-' @(2,;&m:(
Wrltlng o unctlon thot rcurslvly colls ltsl ls on tchnlqu or gnrotlng o roctol
pottrn on scrn. Howvr, whot l you wontd th llns ln th obov Contor st to xlst os
lndlvlduol objcts thot could b movd lndpndntly? 1h rcurslv unctlon ls slmpl ond
lgont, but lt dos not ollow you to do much bslds slmply gnrotlng th pottrn ltsl.
Howvr, thr ls onothr woy w con opply rcurslon ln comblnotlon wlth on V//,"l:#2
thot wlll ollow us to not only gnrot o roctol pottrn, but kp trock o oll lts lndlvlduol
ports os objcts.
1o dmonstrot thls tchnlqu, lt`s look ot onothr omous roctol pottrn, dlscovrd ln
J904 by 5wdlsh mothmotlclon Hlg von Koch. Hr or th ruls. [Not thot lt storts th
som woy os th Contor st, wlth o slngl lln.j
Choptr 8. |roctols
366
1h rsult looks llk.
@,( A]*;-'(.B P:.I( @,( A]*;-'(.B P:.I(
1h Koch curv ond othr roctol pottrns or otn colld mothmotlcol monstrs."
1hls ls du to on odd porodox thot mrgs whn you opply th rcurslv dlnltlon on
lnlnlt numbr o tlms. | th lngth o th orlglnol stortlng lln ls on, th lrst
ltrotlon o th Koch curv wlll ylld o lln o lngth our-thlrds [och sgmnt ls on-
thlrd th lngth o th stortlng llnj. Lo lt ogoln ond you gt o lngth o slxtn-nlnths.
As you ltrot towords lnlnlty, th lngth o th Koch curv opproochs lnlnlty. Yt lt
lts ln th tlny lnlt spoc provldd rlght hr on thls popr [or scrnj!
5lnc w or worklng ln th Procsslng lond o lnlt plxls, thls thortlcol porodox
won`t b o octor or us. W`ll hov to llmlt th numbr o tlms w rcurslvly opply
th Koch ruls so thot our progrom won`t run out o mmory or crosh.
W could procd ln th som monnr os w dld wlth th Contor st, ond wrlt o rcurslv
unctlon thot ltrotlvly opplls th Koch ruls ovr ond ovr. Nvrthlss, w or golng to
tockl thls problm ln o dlrnt monnr by trotlng och sgmnt o th Koch curv os on
lndlvlduol objct. 1hls wlll opn up som dslgn posslbllltls. |or xompl, l och sgmnt ls
Iiure 8.:
Iiure 8.:(
1h Notur o Cod [v005j
367
on objct, w could ollow och sgmnt to mov lndpndntly rom lts orlglnol locotlon
ond portlclpot ln o physlcs slmulotlon. |n oddltlon, w could us o rondom color, lln
thlcknss, tc. to dlsploy och sgmnt dlrntly.
|n ordr to occompllsh our gool o trotlng och sgmnt os on lndlvlduol objct, w must
lrst dcld whot thls objct should b ln th lrst ploc. Whot doto should lt stor? Whot
unctlons should lt hov?
1h Koch curv ls o srls o connctd llns, ond so w wlll thlnk o och sgmnt os o
KochLln." Loch Koch lln hos o stort polnt [o"j ond on nd polnt [b"j. 1hs polnts or
]`%028/ objcts, ond th lln ls drown wlth Procsslng`s -:7%45 unctlon.
Now thot w hov our t80<l:7% closs, w con gt stortd on th moln progrom. W`ll nd
o doto structur to kp trock o whot wlll vntuolly bcom mony t80<l:7% objcts, ond
on V//,"l:#2 [s Choptr 4 or o rvlw o V//,"l:#2sj wlll do just ln.
|n #%23$45, w`ll wont to crot th V//,"l:#2 ond odd th lrst lln sgmnt to lt, o lln
thot strtchs rom 0 to th wldth o th sktch.
0-,## t80<l:7% 1
A line between two points: start and end ]`%028/ #2,/2*
]`%028/ %7&*
t80<l:7%4]`%028/ ,C ]`%028/ I5 1
#2,/2 ' ,N?%245*
%7& ' IN?%245*
@
A8:& &:#$-,"45 1
#2/8.%4B5*
Draw the line from PVector start to end. -:7%4#2,/2N!C #2,/2N"C %7&N!C %7&N"5*
@
@
V//,"l:#2Pt80<l:7%^ -:7%#*
A8:& #%23$45 1
#:F%4GBBC HBB5*
Create the ArrayList. -:7%# ' 7%; V//,"l:#2Pt80<l:7%^45*
Left side of window ]`%028/ #2,/2 ' 7%; ]`%028/4BC >BB5*
Right side of window ]`%028/ %7& ' 7%; ]`%028/4;:&2<C >BB5*
Choptr 8. |roctols
368
1hn ln &/,;45, oll t80<l:7% objcts [just on rlght nowj con b dlsployd ln o loop.
1hls ls our oundotlon. Lt`s rvlw whot w hov so or.
- Y!%+_/.$ %'())3 Y!%+_/.$ %'())3 A closs to kp trock o o lln rom polnt A to B.
- D11(@_/)&3 D11(@_/)&3 A llst o oll t80<l:7% objcts.
Wlth th obov lmnts, how ond whr do w opply Koch ruls ond prlnclpls o rcurslon?
Rmmbr th Gom o Ll cllulor outomoto? |n thot slmulotlon, w olwoys kpt trock o two
gnrotlons. currnt ond nxt. Whn w wr lnlshd computlng th nxt gnrotlon, nxt
bcom currnt ond w movd on to computlng th nw nxt gnrotlon. W or golng to
opply o slmllor tchnlqu hr. W hov on V//,"l:#2 thot kps trock o th currnt st o
t80<l:7% objcts [ot th stort o th progrom, thr ls only onj. W wlll nd o scond
V//,"l:#2 [lt`s coll lt nxt"j whr w wlll ploc oll th nw t80<l:7% objcts thot or
gnrotd rom opplylng th Koch ruls. |or vry t80<l:7% objct ln th currnt V//,"l:#2,
our nw t80<l:7% objcts or oddd to th nxt V//,"l:#2. Whn w`r don, th nxt
V//,"l:#2 bcoms th currnt on.
The first KochLine object -:7%#N,&&47%; t80<l:7%4#2,/2C %7&55*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
E8/ 4t80<l:7% - q -:7%#5 1
-N&:#$-,"45*
@
@
Iiure 8.:
1h Notur o Cod [v005j
369
Hr`s how th cod wlll look.
By colllng ?%7%/,2%45 ovr ond ovr ogoln [or xompl, och tlm th mous ls prssdj,
w rcurslvly opply th Koch curv ruls to th xlstlng st o t80<l:7% objcts. O
cours, th obov omlts th rol work" hr, whlch ls lgurlng out thos ruls. How do w
brok on lln sgmnt lnto our os dscrlbd by th ruls? Whll thls con b occompllshd
wlth som slmpl orlthmtlc ond trlgonomtry, slnc our t80<l:7% objct uss ]`%028/, thls
ls o nlc opportunlty or us to proctlc our vctor moth. Lt`s stobllsh how mony polnts w
nd to comput or och t80<l:7% objct.
As you con s rom th obov lgur, w nd lv polnts [o, b, c, d, ond j to gnrot th
nw t80<l:7% objcts ond mok th nw lln sgmnts [ob, cb, cd, ond dj.
Whr do w gt ths polnts? 5lnc w hov o t80<l:7% objct, why not osk th
t80<l:7% objct to comput oll ths polnts or us?
A8:& ?%7%/,2%45 1
Create the next ArrayList... V//,"l:#2 7%!2 ' 7%; V//,"l:#2Pt80<l:7%^45*
...for every current line. E8/ 4t80<l:7% - q -:7%#5 1
Add four new lines. (We need to figure out
how to compute the locations of these
lines!)
7%!2N,&&47%; t80<l:7%4iiiCiii55*
7%!2N,&&47%; t80<l:7%4iiiCiii55*
7%!2N,&&47%; t80<l:7%4iiiCiii55*
7%!2N,&&47%; t80<l:7%4iiiCiii55*
@
The new ArrayList is now the one we care
about!
-:7%# ' 7%!2*
@
Iiure 8.:
7%!2N,&&47%; t80<l:7%4,CI55*
7%!2N,&&47%; t80<l:7%4IC055*
7%!2N,&&47%; t80<l:7%40C&55*
7%!2N,&&47%; t80<l:7%4&C%55*
A8:& ?%7%/,2%45 1
V//,"l:#2 7%!2 ' 7%; V//,"l:#2Pt80<l:7%^45*
E8/ 4t80<l:7% - q -:7%#5 1
Choptr 8. |roctols
370
Now w just nd to wrlt lv nw unctlons ln th t80<l:7% closs, och on rturnlng o
]`%028/ occordlng to |lgur 8.J6 [s pog 370j obov. Lt`s knock o .80<V45 ond .80<h45
lrst, whlch or slmply th stort ond nd polnts o th orlglnol lln.
Now lt`s mov on to polnts B ond L. B ls on-thlrd o th woy olong th lln sgmnt ond L ls
two-thlrds. Hr w con mok o ]`%028/ thot polnts rom stort to nd ond shrlnk lt to on-thlrd
th lngth or B ond two-thlrds th lngth or L to lnd ths polnts.
The KochLine object has five functions,
each of which return a PVector according to
the Koch rules.
]`%028/ , ' -N.80<V45*
]`%028/ I ' -N.80<W45*
]`%028/ 0 ' -N.80<M45*
]`%028/ & ' -N.80<\45*
]`%028/ % ' -N.80<h45*
7%!2N,&&47%; t80<l:7%4,C I55*
7%!2N,&&47%; t80<l:7%4IC 055*
7%!2N,&&47%; t80<l:7%40C &55*
7%!2N,&&47%; t80<l:7%4&C %55*
@
-:7%# ' 7%!2*
@
]`%028/ .80<V45 1
Note the use of get(), which returns a copy
of the PVector. As was noted in Chapter 6,
section 14, we want to avoid making copies
whenever possible, but here we will need a
new PVector in case we want the segments
to move independently of each other.
/%23/7 #2,/2N?%245*
@
]`%028/ .80<h45 1
/%23/7 %7&N?%245*
@
Iiure 8.:;
]`%028/ .80<W45 1
PVector from start to end ]`%028/ A ' ]`%028/N#3I4%7&C #2,/25*
One-third the length AN&:A4H5*
1h Notur o Cod [v005j
37J
1h lost polnt, C, ls th most dllcult on to lnd. Howvr, l you rcoll thot th ongls o on
qullotrol trlongl or oll slxty dgrs, thls moks lt o llttl blt oslr. | w know how to
lnd polnt B wlth o ]`%028/ on-thlrd th lngth o th lln, whot l w wr to rotot thot
som ]`%028/ slxty dgrs ond mov olong thot vctor rom polnt B? W`d b ot polnt C!
Puttlng lt oll togthr, l w coll ?%7%/,2%45 lv tlms ln #%23$45, w`ll s th ollowlng
rsult.
Add that PVector to the beginning of the
line to find the new point.
AN,&&4#2,/25*
/%23/7 A*
@
]`%028/ .80<\45 1
]`%028/ A ' ]`%028/N#3I4%7&C #2,/25*
Same thing here, only we need to move
two-thirds along the line instead of one-
third.
AN93-24>=HNB5*
AN,&&4#2,/25*
/%23/7 A*
@
Iiure 8.:8
]`%028/ .80<M45 1
Start at the beginning. ]`%028/ , ' #2,/2N?%245*
]`%028/ A ' ]`%028/N#3I4%7&C #2,/25*
Move 1/3rd of the way to point B. AN&:A4H5*
,N,&&4A5*
Rotate "above the line 60 degrees. AN/82,2%46/,&:,7#4GB55*
Move along that vector to point C. ,N,&&4A5*
/%23/7 ,*
@
Choptr 8. |roctols
372
IJ&7:5# BK?L f*0" 0()N#
V//,"l:#2Pt80<l:7%^ -:7%#*
A8:& #%23$45 1
#:F%4GBBC HBB5*
I,0.?/837&4>JJ5*
-:7%# ' 7%; V//,"l:#2Pt80<l:7%^45*
]`%028/ #2,/2 ' 7%; ]`%028/4BC >BB5*
]`%028/ %7& ' 7%; ]`%028/4;:&2<C >BB5*
-:7%#N,&&47%; t80<l:7%4#2,/2C %7&55*
Arbitrarily apply the Koch rules five times. E8/ 4:72 : ' B* : P J* :((5 1
?%7%/,2%45*
@
@
Lrow th Koch snowlok [or som othr
vorlotlon o th Koch curvj.
MO(.2&-( N"0 MO(.2&-( N"0
1h Notur o Cod [v005j
373
1ry onlmotlng th Koch curv. |or xompl, con you drow lt rom lt to rlght? Con you
vory th vlsuol dslgn o th lln sgmnts? Con you mov th lln sgmnts uslng
tchnlqus rom orllr choptrs? Whot l och lln sgmnt wr mod lnto o sprlng
[toxlcllbsj or jolnt [Box2Lj?
MO(.2&-( N"= MO(.2&-( N"=
Rwrlt th Contor st xompl uslng objcts ond on V//,"l:#2.
MO(.2&-( N"> MO(.2&-( N">
Lrow th 5lrplskl trlongl [os sn ln Wolrom lmntory CAj uslng rcurslon.
MO(.2&-( N"? MO(.2&-( N"?
N"? @.((- N"? @.((-
1h roctols w hov xomlnd ln thls choptr so or or dtrmlnlstlc, monlng thy hov
no rondomnss ond wlll olwoys produc th ldntlcol outcom och tlm thy or run. 1hy
or xcllnt dmonstrotlons o closslc roctols ond th progrommlng tchnlqus bhlnd
drowlng thm, but or too prcls to l notuto|. |n thls nxt port o th choptr, | wont to
xomln som tchnlqus bhlnd gnrotlng o stochostlc [or non-dtrmlnlstlcj roctol. 1h
xompl w`ll us ls o bronchlng tr. Lt`s lrst wolk through th stps to crot o
dtrmlnlstlc vrslon. Hr or our productlon ruls.
Choptr 8. |roctols
374
Agoln, w hov o nlc roctol wlth o rcurslv dlnltlon. A bronch ls o lln wlth two bronchs
connctd to lt.
1h port thot ls o blt mor dllcult thon our prvlous roctols lls ln th us o th word totote
ln th roctol`s ruls. Loch nw bronch must rotot rlotlv to th prvlous bronch, whlch ls
rototd rlotlv to oll lts prvlous bronchs. Lucklly or us, Procsslng hos o mchonlsm to
kp trock o rototlons or usth &1(.);!1-(&/!. -(&1/K &1(.);!1-(&/!. -(&1/K. | you orn`t omlllor wlth th
unctlons $3#<d,2/:!45 ond $8$d,2/:!45, | suggst you rod th onlln Procsslng tutorlol
2L 1ronsormotlons [http.//procsslng.org/lornlng/tronsorm2d/j, whlch wlll covr th
concpts you`ll nd or thls portlculor xompl.
Lt`s bgln by drowlng o slngl bronch, th trunk o th tr. 5lnc w or golng to lnvolv th
/82,2%45 unctlon, w`ll nd to mok sur w or contlnuously tronslotlng olong th
bronchs whll w drow th tr. And slnc th root storts ot th bottom o th wlndow [s
obovj, th lrst stp rqulrs tronslotlng to thot spot.
Iiure 8.:p
2/,7#-,2%4;:&2<=>C<%:?<25*
1h Notur o Cod [v005j
375
.ollowd by drowlng o lln upwords
[|lgur 8.20j.
Onc w`v lnlshd th root, w just nd to tronslot to th nd ond rotot ln ordr to
drow th nxt bronch. [Lvntuolly, w`r golng to nd to pockog up whot w`r dolng
rlght now lnto o rcurslv unctlon, but lt`s sort out th stps lrst.j
Rmmbr, whn w rotot ln Procsslng, w or olwoys rototlng oround th polnt o orlgln,
so hr th polnt o orlgln must olwoys b tronslotd to th nd o our currnt bronch.
Now thot w hov o bronch golng to th rlght, w nd on golng to th lt. W con us
$3#<d,2/:!45 to sov th tronsormotlon stot bor w rotot, lttlng us coll
$8$d,2/:!45 to rstor thot stot ond drow th bronch to th lt. Lt`s look ot oll th cod
togthr.
Iiure 8.zo
-:7%4BCBCBC6)BB5*
Iiure 8.z:
2/,7#-,2%4BC6)BB5*
/82,2%4]c=G5*
-:7%4BCBCBC6)BB5*
Choptr 8. |roctols
376
| you thlnk o och coll to th unctlon -:7%45 os o bronch," you con s rom th cod
obov thot w hov lmplmntd our dlnltlon o bronchlng os o lln thot hos two llns
connctd to lts nd. W could kp oddlng mor ond mor colls to -:7%45 or mor ond
mor bronchs, but just os wlth th Contor st ond Koch curv, our cod would bcom
lncrdlbly compllcotd ond unwlldy. |nstod, w con us th obov loglc os our oundotlon
or wrltlng o rcurslv unctlon, rploclng th dlrct colls to -:7%45 wlth our own unctlon
colld I/,70<45. Lt`s tok o look.
IJ&7:5# BK@L H#0()8/N# ')##
Iiure 8.zz Iiure 8.z
2/,7#-,2%4;:&2<=>C<%:?<25*
The root -:7%4BCBCBC6)BB5*
2/,7#-,2%4BC6)BB5*
$3#<d,2/:!45*
/82,2%4]c=G5*
Branch to the right -:7%4BCBCBC6)BB5*
$8$d,2/:!45*
/82,2%46]c=G5*
Branch to the left -:7%4BCBCBC6)BB5*
A8:& I/,70<45 1
Draw the branch itself. -:7%4BC BC BC 6)BB5*
Translate to the end. 2/,7#-,2%4BC 6)BB5*
$3#<d,2/:!45*
1h Notur o Cod [v005j
377
Notlc how ln th obov cod w us $3#<d,2/:!45 ond $8$d,2/:!45 oround och
subsqunt coll to I/,70<45. 1hls ls on o thos lgont cod solutlons thot ls olmost
llk moglc. Loch coll to I/,70<45 toks o momnt to rmmbr th locotlon o thot
portlculor bronch. | you turn yoursl lnto Procsslng or o momnt ond try to ollow th
rcurslv unctlon wlth pncll ond popr, you`ll notlc thot lt drows oll o th bronchs to th
rlght lrst. Whn lt gts to th nd, $8$d,2/:!45 wlll pop us bock olong oll o th bronchs
w`v drown ond stort sndlng bronchs out to th lt.
You moy hov notlcd thot th rcurslv unctlon w just wrot would not octuolly drow th
obov tr. Atr oll, lt hos no xlt condltlon ond would gt stuck ln lnlnlt rcurslv colls to
ltsl. You`ll olso probobly notlc thot th bronchs o th tr gt shortr ot och lvl.
Lt`s look ot how w con shrlnk th lngth o th llns os th tr ls drown, ond stop
bronchlng onc th llns hov bcom too short.
Rotate to the right and branch again. /82,2%4]c=G5*
I/,70<45*
$8$d,2/:!45*
$3#<d,2/:!45*
Rotate to the left and branch again. /82,2%46]c=G5*
I/,70<45*
$8$d,2/:!45*
@
Lmulot th Procsslng cod ln Lxompl 8.6 [s pog 377j ond numbr th
bronchs ln th obov dlogrom ln th ordr thot Procsslng would octuolly drow och
on.
MO(.2&-( N"K MO(.2&-( N"K
Choptr 8. |roctols
378
W`v olso lncludd o vorlobl or thto thot ollows us, whn wrltlng th rst o th cod ln
#%23$45 ond &/,;45, to vory th bronchlng ongl occordlng to, soy, th 983#%e locotlon.
IJ&7:5# BKAL H#0()8/N# ')##
Each branch now receives its length as an
argument.
A8:& I/,70<4E-8,2 -%75 1
-:7%4BC BC BC 6-%75*
2/,7#-,2%4BC 6-%75*
Each branch's length shrinks by two-thirds. -%7 Q' BNGG*
:E 4-%7 ^ >5 1
$3#<d,2/:!45*
/82,2%42<%2,5*
Subsequent calls to branch() include the
length argument.
I/,70<4-%75*
$8$d,2/:!45*
$3#<d,2/:!45*
/82,2%462<%2,5*
I/,70<4-%75*
$8$d,2/:!45*
@
@
E-8,2 2<%2,*
A8:& #%23$45 1
#:F%4HBBC >BB5*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
1h Notur o Cod [v005j
379
1h rcurslv tr roctol ls o nlc xompl o o scnorlo ln whlch oddlng o llttl blt o
rondomnss con mok th tr look mor noturol. 1ok o look outsld ond you`ll notlc thot
bronch lngths ond ongls vory rom bronch to bronch, not to mntlon th oct thot bronchs
don`t oll hov xoctly th som numbr o smollr bronchs. |lrst, lt`s s whot hoppns
Pick an angle according to the mouse
location.
2<%2, ' 9,$4983#%eCBC;:&2<CBC]c=>5*
The first branch starts at the bottom of the
window.
2/,7#-,2%4;:&2<=>C <%:?<25*
#2/8.%4B5*
I/,70<4GB5*
@
Vory th #2/8.%+%:?<245 or och bronch. Mok th root thlck ond och subsqunt
bronch thlnnr.
MO(.2&-( N"L MO(.2&-( N"L
1h tr structur con olso b gnrotd uslng th V//,"l:#2 tchnlqu
dmonstrotd wlth th Koch curv. Rcrot th tr uslng o W/,70< objct ond on
V//,"l:#2 to kp trock o th bronchs. Hlnt. you`ll wont to kp trock o th bronch
dlrctlons ond lngths uslng vctor moth lnstod o Procsslng tronsormotlons.
MO(.2&-( N"N MO(.2&-( N"N
Onc you hov th tr bullt wlth on V//,"l:#2 o W/,70< objcts, onlmot th tr`s
growth. Con you drow lovs ot th nd o th bronchs?
MO(.2&-( N"W MO(.2&-( N"W
Choptr 8. |roctols
380
whn w slmply vory th ongl ond lngth. 1hls ls o prtty osy on, glvn thot w con just
osk Procsslng or o rondom numbr och tlm w drow th tr.
|n th obov unctlon, w olwoys coll I/,70<45 twlc. But why not plck o rondom numbr o
bronchs ond coll I/,70<45 thot numbr o tlms?
A8:& I/,70<4E-8,2 -%75 1
Start by picking a random angle for each
branch.
E-8,2 2<%2, ' /,7&894BC]c=H5*
-:7%4BC BC BC 6-%75*
2/,7#-,2%4BC 6-%75*
-%7 Q' BNGG*
:E 4-%7 ^ >5 1
$3#<d,2/:!45*
/82,2%42<%2,5*
I/,70<4-%75*
$8$d,2/:!45*
$3#<d,2/:!45*
/82,2%462<%2,5*
I/,70<4-%75*
$8$d,2/:!45*
@
@
1h Notur o Cod [v005j
38J
IJ&7:5# BKBL O'*0"&8'/0 ')##
A8:& I/,70<4E-8,2 -%75 1
-:7%4BC BC BC 6-%75*
2/,7#-,2%4BC 6-%75*
:E 4-%7 ^ >5 1
Call branch() a random number of times. :72 7 ' :724/,7&894)CD55*
E8/ 4:72 : ' B* : P 7* :((5 1
Each branch gets its own random angle. E-8,2 2<%2, ' /,7&8946]c=>C ]c=>5*
$3#<d,2/:!45*
/82,2%42<%2,5*
I/,70<4<5*
$8$d,2/:!45*
@
@
5t th ongls o th bronchs o th tr occordlng to Prlln nols volus. Adjust th
nols volus ovr tlm to onlmot th tr. 5 l you con gt lt to oppor os l lt ls
blowlng ln th wlnd.
MO(.2&-( N"#T MO(.2&-( N"#T
s toxlcllbs to slmulot tr physlcs. Loch bronch o th tr should b two portlcls
connctd wlth o sprlng. How con you gt th tr to stond up ond not oll down?
MO(.2&-( N"## MO(.2&-( N"##
N"K VZ-/-'(E- N"K VZ-/-'(E-
|n J968, Hungorlon botonlst Arlstld Llndnmoyr dvlopd o grommor-bosd systm to
modl th growth pottrns o plonts. L-systms [short or Llndnmoyr systmsj con b usd
to gnrot oll o th rcurslv roctol pottrns w`v sn so or ln thls choptr. W don`t
nd L-systms to do th klnd o work w`r dolng hr, howvr, thy or lncrdlbly usul
bcous thy provld o mchonlsm or kplng trock o roctol structurs thot rqulr
complx ond multl-octd productlon ruls.
Choptr 8. |roctols
382
|n ordr to crot on xompl thot lmplmnts L-systms ln Procsslng, w or golng to hov
to b comortobl wlth worklng wlth [oj rcurslon, [bj tronsormotlon motrlcs, ond [cj strlngs.
5o or w`v workd wlth rcurslon ond tronsormotlons, but strlngs or nw hr. W wlll
ossum th boslcs, but l thot ls not comortobl or you, | would suggst toklng o look ot th
Procsslng tutorlol 5trlngs ond Lrowlng 1xt [http.//www.procsslng.org/lornlng/txt/j.
An L-systm lnvolvs thr moln componnts.
- D'A+("$&6 D'A+("$&6 An L-systm`s olphobt ls comprlsd o th volld choroctrs thot con b
lncludd. |or xompl, w could soy th olphobt ls ABC," monlng thot ony volld
sntnc" [o strlng o choroctrsj ln on L-systm con only lnclud ths thr
choroctrs.
- DK/!-6 DK/!-6 1h oxlom ls o sntnc [mod up wlth choroctrs rom th olphobtj thot
dscrlbs th lnltlol stot o th systm. |or xompl, wlth th olphobt ABC," som
xompl oxloms or AAA" or B" or ACBAB."
- S:'$)6 S:'$)6 1h ruls o on L-systm or opplld to th oxlom ond thn opplld
rcurslvly, gnrotlng nw sntncs ovr ond ovr ogoln. An L-systm rul
lncluds two sntncs, o prdcssor" ond o succssor." |or xompl, wlth th
Rul A AB", whnvr on A" ls ound ln o strlng, lt ls rplocd wlth AB."
Lt`s bgln wlth o vry slmpl L-systm. [1hls ls, ln oct, Llndnmoyr`s orlglnol L-systm or
modllng th growth o olgo.j
h'0H&6$/Y h l
hI285Y h
q4'$.Y *h a hl+ *l a h+
As wlth our rcurslv roctol shops, w con
consldr och succsslv oppllcotlon o th
L-systm ruls to b o gnrotlon.
Gnrotlon 0 ls, by dlnltlon, th oxlom.
Lt`s look ot how w mlght crot ths
gnrotlons wlth cod. W`ll stort by uslng o
[2/:7? objct to stor th oxlom.
And onc ogoln, just os w dld wlth th Gom o Ll ond th Koch curv V//,"l:#2
xompls, w wlll nd on ntlrly sporot strlng to kp trock o th nxt" gnrotlon.
Iiure 8.z(: And so on cnd so jorth...
[2/:7? 03//%72 ' TVT*
1h Notur o Cod [v005j
383
Now lt`s tlm to opply th ruls to th currnt gnrotlon ond ploc th rsults ln th nxt.
And whn w`r don, currnt con bcom nxt.
1o b sur thls ls worklng, lt`s pockog lt lnto o unctlon ond ond coll lt vry tlm th
mous ls prssd.
IJ&7:5# BKCL O/7:5# _`8U8'#7 8#1'#10# 6#1#)&'/*1
[2/:7? 7%!2 ' TT*
E8/ 4:72 : ' B* : P 03//%72N-%7?2<45* :((5 1
0<,/ 0 ' 03//%72N0<,/V24:5*
Production rule A --> AB :E 40 '' wVw5 1
7%!2 (' TVWT*
Production rule B --> A @ %-#% :E 40 '' wWw5 1
7%!2 (' TVT*
@
@
03//%72 ' 7%!2*
Start with an axiom. [2/:7? 03//%72 ' TVT*
Let's keep track of how many generations. :72 08372 ' B*
A8:& #%23$45 1
$/:72-74TZ%7%/,2:87 T ( 08372 ( Tq T ( 03//%725*
@
A8:& &/,;45 1
@
A8:& 983#%]/%##%&45 1
[2/:7? 7%!2 ' TT*
Choptr 8. |roctols
384
5lnc th ruls or opplld rcurslvly to och gnrotlon, th lngth o th strlng grows
xponntlolly. By gnrotlon #JJ, th sntnc ls 233 choroctrs long, by gnrotlon #22, lt ls
ovr 46,000 choroctrs long. 1h Jovo [2/:7? closs, whll convnlnt to us, ls o grossly
lnlclnt doto structur or concotnotlng lorg strlngs. A [2/:7? objct ls lmmutobl,"
whlch mons onc th objct ls crotd lt con nvr b chongd. Whnvr you odd on to th
nd o o [2/:7? objct, Jovo hos to mok o brond nw [2/:7? objct [vn l you or uslng
th som vorlobl nomj.
|n most coss, thls ls ln, but why dupllcot o 46,000-choroctr strlng l you don`t hov to?
|or bttr lclncy ln our L-systm xompls, w`ll us th [2/:7?W3EE%/ closs, whlch ls
optlmlzd or thls typ o tosk ond con oslly b convrtd lnto o strlng otr concotnotlon ls
complt.
You moy lnd yoursl wondrlng rlght obout now. whot xoctly ls th polnt o oll thls? Atr oll,
lsn`t thls o choptr obout dtow|ng roctol pottrns? Ys, th rcurslv notur o th L-systm
sntnc structur sms rlvont to th dlscusslon, but how xoctly dos thls modl plont
growth ln o vlsuol woy?
Traverse the current String and make the
new one.
E8/ 4:72 : ' B* : P 03//%72N-%7?2<45* :((5 1
0<,/ 0 ' 03//%72N0<,/V24:5*
:E 40 '' wVw5 1
7%!2 (' TVWT*
@ %-#% :E 40 '' wWw5 1
7%!2 (' TVT*
@
@
03//%72 ' 7%!2*
08372((*
$/:72-74TZ%7%/,2:87 T ( 08372 ( Tq T ( 03//%725*
@
[2/:7? # ' TI-,<T*
# (' T,&& #89% 98/% #23EET*
A StringBuffer for the "next sentence [2/:7?W3EE%/ 7%!2 ' 7%; [2/:7?W3EE%/45*
E8/ 4:72 : ' B* : P 03//%72N-%7?2<45* :((5 1
0<,/ 0 ' 03//%72N0<,/V24:5*
:E 40 '' wVw5 1
append() instead of += 7%!2N,$$%7&4TVWT5*
@ %-#% :E 40 '' wWw5 1
7%!2N,$$%7&4TVT5*
@
@
StringBuffer can easily be converted back to
a String.
03//%72 ' 7%!2N28[2/:7?45*
1h Notur o Cod [v005j
385
Whot w`v lt unsold untll now ls thot mbddd lnto ths L-systm sntncs or
lnstructlons or drowlng. Lt`s s how thls works wlth onothr xompl.
h'0H&6$/Y h l
hI285Y h
q4'$.Y *h a hlh+ *l a lll+
1o rod o sntnc, w`ll tronslot lt ln th ollowlng woy.
hY Z)&! & '2#$ 98)!&)1-
lY g8L$ 98)!&)1 !2/H84/ 1)&!2#G-
Lt`s look ot th sntnc o och gnrotlon ond lts vlsuol output.
r$#$)&/28# ?Y h
r$#$)&/28# DY hlh
r$#$)&/28# >Y hlhlllhlh
r$#$)&/28# EY hlhlllhlhlllllllllhlhlllhlh
Look omlllor? 1hls ls th Contor st gnrotd wlth on L-systm.
1h ollowlng olphobt ls otn usd wlth L-systms. |G-", monlng.
^Y Z)&! & '2#$ &#1 58L$ 98)!&)1
rY g8L$ 98)!&)1 *!2/H84/ 1)&!2#G & '2#$+
KY b4)# )2GH/
TY b4)# '$9/
[Y k&L$ :4))$#/ '8:&/28#
\Y q$./8)$ 0)$L284. '8:&/28#
1hls typ o drowlng romwork ls otn rrrd to os 1urtl grophlcs" [rom th old doys
o LOGO progrommlngj. |mogln o turtl slttlng on your computr scrn to whlch you could
lssu o smoll st o commonds. turn lt, turn rlght, drow o lln, tc. Procsslng lsn`t st up
to oprot thls woy by doult, but by uslng 2/,7#-,2%45, /82,2%45, ond -:7%45, w con
mulot o 1urtl grophlcs ngln olrly oslly.
Iiure 8.z
Choptr 8. |roctols
386
Hr`s how w would tronslot th obov L-systm olphobt lnto Procsslng cod.
^Y '2#$*?J?J?J'$#+, /)&#.'&/$*?J'$#+,
rY /)&#.'&/$*?J'$#+,
KY )8/&/$*&#G'$+,
TY )8/&/$*T&#G'$+,
[Y 04.Hg&/)2I*+,
\Y 080g&/)2I*+,
Assumlng w hov o sntnc gnrotd rom th L-systm, w con wolk through th
sntnc choroctr by choroctr ond coll th opproprlot unctlon os outllnd obov.
1h nxt xompl wlll drow o mor loborot structur wlth th ollowlng L-systm.
h'0H&6$/Y ^rKT[\
hI285Y ^
q4'$.Y ^ Ta ^^K[K^T^T^\T[T^K^K^\
1h xompl ovollobl or downlood on th book`s wbslt toks oll o th L-systm cod
provldd ln thls sctlon ond orgonlzs lt lnto thr closss.
- q4'$. A closs thot stors th prdcssor ond succssor strlngs or on L-systm rul.
- ok3./$5. A closs to ltrot o nw L-systm gnrotlon [os dmonstrotd wlth th
[2/:7?W3EE%/ tchnlquj.
- b4)/'$. A closs to monog rodlng th L-systm sntnc ond ollowlng lts
lnstructlons to drow on th scrn.
E8/ 4:72 : ' B* : P #%72%70%N-%7?2<45* :((5 1
Looking at each character one at a time 0<,/ 0 ' #%72%70%N0<,/V24:5*
Performing the correct task for each
character. This could also be written with a
"case statement, which might be nicer to
look at, but leaving it as an if/else if
structure helps readers not familiar with
case statements.
:E 40 '' wbw5 1
-:7%4BCBC-%7CB5*
2/,7#-,2%4-%7CB5*
@ %-#% :E 40 '' wbw5 1
2/,7#-,2%4-%7CB5*
@ %-#% :E 40 '' w(w5 1
/82,2%42<%2,5*
@ %-#% :E 40 '' w6w5 1
/82,2%462<%2,5*
@ %-#% :E 40 '' wKw5 1
$3#<d,2/:!45*
@ %-#% :E 40 '' wLw5 1
$8$d,2/:!45*
@
@
1h Notur o Cod [v005j
387
W won`t wrlt out ths closss hr slnc thy slmply dupllcot th cod w`v olrody
workd out ln thls choptr. Howvr, lt`s s how thy or put togthr ln th moln tob.
IJ&7:5# BK;DL _OU8'#7
l["#2%9 -#"#*
n3/2-% 23/2-%*
A8:& #%23$45 1
#:F%4GBBCGBB5*
A ruleset is an array of Rule objects. Y3-%KL /3-%#%2 ' 7%; Y3-%K)L*
/3-%#%2KBL ' 7%; Y3-%4wbwCTbb(K(b6b6bL6K6b(b(bLT5*
The L-system is created with an axiom and
a ruleset.
-#"# ' 7%; l["#2%94TbTC/3-%#%25*
23/2-% ' 7%; n3/2-%4-#"#N?%2[%72%70%45C;:&2<=DC/,&:,7#4>J55*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
The Turtle graphics renderer is given a
sentence, a starting length, and an angle
for rotations.
Start at the bottom of the window and draw. 2/,7#-,2%4;:&2<=>C<%:?<25*
23/2-%N/%7&%/45*
@
A8:& 983#%]/%##%&45 1
Generate a new sentence when the mouse
is pressed.
-#"#N?%7%/,2%45*
23/2-%N#%2n8\84-#"#N?%2[%72%70%455*
The length shrinks each generation. 23/2-%N0<,7?%l%74BNJ5*
@
Choptr 8. |roctols
388
@,( M2*-/-'(E 5.*G(2' @,( M2*-/-'(E 5.*G(2'
U'(Q N MO(.2&-(D
C;2*.Q*.4'( +.42'4%- &;'* /*:. (2*-/-'(E" U*E( Q*--&)&%&'&(-D
h !99 Q%4;'Z%&3( 2.(4':.(- '* ',( (2*-/-'(E (;I&.*;E(;'"
h V('H- -4/ *;( *+ /*:. Q%4;'- &- -&E&%4. '* 4 '.((" P4; /*: 499 %(4I(- *.
+%*8(.- '* ',( (;9 *+ ',( ).4;2,(-7 6,4' &+ ',( %(4I(- 24; +4%% *++ ',( '.((
^9(Q(;9&;< *; 4 8&;9 +*.2(_7 6,4' &+ /*: 499 +.:&' ',4' 24; )( Q&23(9 4;9
(4'(; )/ ',( 2.(4':.(-7
h \(-&<; 4 2.(4':.( 8&', 4 +.42'4% Q4''(.;"
h [-( 4; VZ-/-'(E '* <(;(.4'( &;-'.:2'&*;- +*. ,*8 4 2.(4':.( -,*:%9 E*I(
*. )(,4I("
s on L-systm os o st o lnstructlons or crotlng objcts stord ln on V//,"l:#2.
s trlgonomtry ond vctor moth to prorm th rototlons lnstod o motrlx
tronsormotlons [much llk w dld ln th Koch curv xomplj.
MO(.2&-( N"#0 MO(.2&-( N"#0
1h smlnol work ln L-systms ond plont structurs, 7he A|got|thm|c Beouty ot l|onts
by Przmysow Pruslnklwlcz ond Arlstld Llndnmoyr, wos publlshd ln J990. |t ls
ovollobl or r ln lts ntlrty onlln [http.//olgorlthmlcbotony.org/poprs/#obopj.
Choptr J dscrlbs mony sophlstlcotd L-systms wlth oddltlonol drowlng ruls ond
ovollobl olphobt choroctrs. |n oddltlon, lt dscrlbs svrol mthods or gnrotlng
stochostlc L-systms. Lxpond th L-systm xompl to lnclud on or mor oddltlonol
oturs dscrlbd by Pruslnklwlcz ond Llndnmoyr.
MO(.2&-( N"#= MO(.2&-( N"#=
|n thls choptr, w mphoslzd uslng roctol olgorlthms or gnrotlng vlsuol pottrns.
Howvr, roctols con b ound ln othr crotlv mdlums. |or xompl, roctol pottrns
or vldnt ln Johonn 5bostlon Boch`s Cllo 5ult no. 3. 1h structur o Lovld |ostr
Wolloc`s novl lnt|n|te !est wos lnsplrd by roctols. Consldr uslng th xompls ln
thls choptr to gnrot oudlo or txt.
MO(.2&-( N"#> MO(.2&-( N"#>
1h Notur o Cod [v005j
389
,"&:'#) CK !"# ,"&:'#) CK !"#
IN*5('/*1 *+ ,*-# IN*5('/*1 *+ ,*-#
The jcct thct lije etolted out oj necrl nothin, some :o billion ecrs
cjter the uniterse etolted out oj litercll nothin, is c jcct so stcerin
thct I uould be mcd to cttempt uords to do it justice.
! V-.E$21 *$RG-,'
Lt`s tok o momnt to thlnk bock to o slmplr tlm, whn you wrot your lrst Procsslng
sktchs ond ll wos r ond osy. Whot ls on o progrommlng`s undomntol concpts
thot you llkly usd ln thos lrst sktchs ond contlnu to us ovr ond ovr ogoln?
Vot|ob|es. Vorlobls ollow you to sov doto ond rus thot doto whll o progrom runs. 1hls,
o cours, ls nothlng nw to us. |n oct, w hov movd or byond o sktch wlth just on or
two vorlobls ond on to mor complx doto structursvorlobls mod rom custom typs
[objctsj thot lnclud both doto ond unctlonollty. W`v mod our own llttl worlds o
movrs ond portlcls ond vhlcls ond clls ond trs.
|n och ond vry xompl ln thls book, th vorlobls o ths objcts hov to b lnltlollzd.
Prhops you mod o whol bunch o portlcls wlth rondom colors ond slzs or o llst o
vhlcls oll stortlng ot th som !," locotlon on scrn. But lnstod o octlng os lntlllgnt
dslgnrs" ond osslgnlng th proprtls o our objcts through rondomnss or thoughtul
consldrotlon, w con lt o procss ound ln noturevo|ut|ondcld or us.
Con w thlnk o th vorlobls o on objct os lts LNA? Con objcts mok othr objcts ond
poss down thlr LNA to o nw gnrotlon? Con our slmulotlon volv?
Choptr 9. 1h Lvolutlon o Cod
390
1h onswr to oll ths qustlons ls ys. Atr oll, w wouldn`t b obl to oc ourslvs ln th
mlrror os notur-o-codrs wlthout tockllng o slmulotlon o on o th most powrul
olgorlthmlc procsss ound ln notur ltsl. 1hls choptr ls ddlcotd to xomlnlng th
prlnclpls bhlnd blologlcol volutlon ond lndlng woys to opply thos prlnclpls ln cod.
W"# e(;('&2 !%<*.&',E-D C;-Q&.(9 )/ !2':4% MI(;'- W"# e(;('&2 !%<*.&',E-D C;-Q&.(9 )/ !2':4% MI(;'-
|t`s lmportont or us to clorly th gools o thls choptr. W wlll not go lnto dpth obout th
sclnc o gntlcs ond volutlon os lt hoppns ln th rol world. W won`t b moklng Punntt
squors [sorry to dlsoppolntj ond thr wlll b no dlscusslon o nuclotlds, protln synthsls,
RNA, ond othr toplcs rlotd to th octuol blologlcol procsss o volutlon. |nstod, w or
golng to look ot th cor prlnclpls bhlnd Lorwlnlon volutlonory thory ond dvlop o st o
olgorlthms |nsp|ted by ths prlnclpls. W don`t cor so much obout on occurot slmulotlon
o volutlon, rothr, w cor obout mthods or opplylng volutlonory strotgls ln sotwor.
1hls ls not to soy thot o projct wlth mor sclntllc dpth wouldn`t hov volu, ond |
ncourog rodrs wlth o portlculor lntrst ln thls toplc to xplor posslbllltls or xpondlng
th xompls provldd wlth oddltlonol volutlonory oturs. Nvrthlss, or th sok o
kplng thlngs monogobl, w`r golng to stlck to th boslcs, whlch wlll b plnty complx
ond xcltlng.
1h trm gntlc olgorlthm" rrs to o spcllc olgorlthm lmplmntd ln o spcllc woy to
solv spcllc sorts o problms. Whll th ormol gntlc olgorlthm ltsl wlll srv os th
oundotlon or th xompls w crot ln thls choptr, w ndn`t worry obout lmplmntlng
th olgorlthm wlth prct occurocy, glvn thot w or looklng or crotlv uss o
volutlonory thorls ln our cod. 1hls choptr wlll b brokn down lnto th ollowlng thr
ports [wlth th mojorlty o th tlm spnt on th lrstj.
J. *1(8/&/!.(' b$.$&/% D'2!1/&+-6 *1(8/&/!.(' b$.$&/% D'2!1/&+-6 W`ll bgln wlth th trodltlonol computr sclnc
gntlc olgorlthm. 1hls olgorlthm wos dvlopd to solv problms ln whlch th
solutlon spoc ls so vost thot o brut orc" olgorlthm would slmply tok too long.
Hr`s on xompl. |`m thlnklng o o numbr. A numbr btwn on ond on bllllon.
How long wlll lt tok or you to guss lt? 5olvlng o problm wlth brut orc" rrs
to th procss o chcklng vry posslbl solutlon. |s lt on? |s lt two? |s lt thr? |s
lt our? And so ond ond so orth. 1hough luck dos ploy o octor hr, wlth brut
orc w would otn lnd ourslvs potlntly woltlng or yors whll you count to
on bllllon. Howvr, whot l | could tll you l on onswr you gov wos good or bod?
Worm or cold? Vry worm? Hot? 5upr, supr cold? | you could voluot how lt" o
guss ls, you could plck othr numbrs closr to thot guss ond orrlv ot th onswr
mor qulckly. Your onswr could volv.
2. ].&$1(%&/0$ Q$'$%&/!.6 ].&$1(%&/0$ Q$'$%&/!.6 Onc w stobllsh th trodltlonol computr sclnc olgorlthm,
w`ll look ot othr oppllcotlons o gntlc olgorlthms ln th vlsuol orts. |ntroctlv
slctlon rrs to th procss o volvlng somthlng [otn on computr-gnrotd
lmogj through usr lntroctlon. Lt`s soy you wolk lnto o musum gollry ond s
1h Notur o Cod [v005j
39J
tn polntlngs. Wlth lntroctlv slctlon, you would plck your ovorlts ond ollow
on olgorlthmlc procss to gnrot [or volv"j nw polntlngs bosd on your
prrncs.
3. =%!)@)&$- Q/-:'(&/!.6 =%!)@)&$- Q/-:'(&/!.6 1h trodltlonol computr sclnc gntlc olgorlthm ond
lntroctlv slctlon tchnlqu or whot you wlll llkly lnd l you sorch onlln or
rod o txtbook obout ortllclol lntlllgnc. But os w`ll soon s, thy don`t rolly
slmulot th procss o volutlon os lt hoppns ln th rol world. |n thls choptr, |
wont to olso xplor tchnlqus or slmulotlng th procss o volutlon ln on
cosystm o psudo-llvlng blngs. How con our objcts thot mov obout th
scrn mt och othr, mot, ond poss thlr gns on to o nw gnrotlon? 1hls
would opply dlrctly to th Lcosystm Projct outllnd ot th nd o och choptr.
W"0 6,/ [-( e(;('&2 !%<*.&',E-7 W"0 6,/ [-( e(;('&2 !%<*.&',E-7
Whll computr slmulotlons o volutlonory procsss dot bock to th J950s, much o whot
w thlnk o os gntlc olgorlthms [olso known os GAs"j todoy wos dvlopd by John
Hollond, o prossor ot th nlvrslty o Mlchlgon, whos book Adoptot|on |n Notuto| ond
Att|t|c|o| 5ystems plonrd GA rsorch. 1odoy, mor gntlc olgorlthms or port o o
wldr lld o rsorch, otn rrrd to os "Lvolutlonory Computlng."
1o hlp lllustrot th trodltlonol gntlc olgorlthm, w or golng to stort wlth monkys. No,
not our volutlonory oncstors. W`r golng to stort wlth som lctlonol monkys thot bong
owoy on kyboords wlth th gool o typlng out th complt works o 5hokspor.
Iiure p.:
Choptr 9. 1h Lvolutlon o Cod
392
1h lnlnlt monky thorm" ls stotd os ollows. A monky hlttlng kys rondomly on o
typwrltr wlll vntuolly typ th complt works o 5hokspor [glvn on lnlnlt omount o
tlmj. 1h problm wlth thls thory ls thot th proboblllty o sold monky octuolly typlng
5hokspor ls so low thot vn l thot monky stortd ot th Blg Bong, lt`s unbllvobly
unllkly w`d vn hov Hom|et ot thls polnt.
Lt`s consldr o monky nomd Gorg. Gorg typs on o rducd typwrltr contolnlng
only twnty-svn choroctrs. twnty-slx lttrs ond on spoc bor. 5o th proboblllty o
Gorg hlttlng ony glvn ky ls on ln twnty-svn.
Lt`s consldr th phros to b or not to b thot ls th qustlon" [w`r slmpllylng lt rom th
orlglnol 1o b, or not to b. thot ls th qustlon"j. 1h phros ls 39 choroctrs long. | Gorg
storts typlng, th chonc h`ll gt th lrst choroctr rlght ls J ln 27. 5lnc th proboblllty h`ll
gt th scond choroctr rlght ls olso J ln 27, h hos o J ln 27'27 chonc o londlng th lrst
two choroctrs ln corrct ordrwhlch ollows dlrctly rom our dlscusslon o "vnt
proboblllty" ln th |ntroductlon [s pog 0j. 1hror, th proboblllty thot Gorg wlll typ
th ull phros ls.
[J/27j multlplld by ltsl 39 tlms, l.. [J/27j
39
whlch quols o J ln
66,555,937,033,867,822,607,895,549,24J,096,482,953,0J7,6J5,834,735,226,J63 chonc o
gttlng lt rlght!
Ndlss to soy, vn hlttlng just thls on phros, not to mntlon on ntlr ploy, ls hlghly
unllkly. Lvn l Gorg ls o computr slmulotlon ond con typ on mllllon rondom phross
pr scond, or Gorg to hov o 99 proboblllty o vntuolly gttlng lt rlght, h would hov
to typ or 9,7J9,096,J82,0J0,563,073,J25,59J,J33,903,305,625,605,0J7 yors. [Not thot th
og o th unlvrs ls stlmotd to b o mr J3,750,000,000 yors.j
1h polnt o oll ths unothomobly lorg numbrs ls not to glv you o hodoch, but to
dmonstrot thot o brut orc olgorlthm [typlng vry posslbl rondom phrosj ls not o
rosonobl strotgy or orrlvlng rondomly ot to b or not to b thot ls th qustlon". Lntr
gntlc olgorlthms, whlch wlll show thot w con stlll stort wlth rondom phross ond lnd th
solutlon through slmulotd volutlon.
Now, lt`s worth notlng thot thls problm [ott|ve ot the phtose "to be ot not to be thot |s the
quest|on"j ls o rldlculous on. 5lnc w know th onswr, oll w nd to do ls typ lt. Hr`s o
Procsslng sktch thot solvs th problm.
Nvrthlss, th polnt hr ls thot solvlng o problm wlth o known onswr ollows us to oslly
tst our cod. Onc w`v succssully solvd th problm, w con l mor conldnt ln
uslng gntlc olgorlthms to do som octuol usul work. solvlng problms wlth unknown
onswrs. 5o thls lrst xompl srvs no rol purpos othr thon to dmonstrot how gntlc
#2/:7? # ' Tn8 I% 8/ 782 28 I% 2<,2 :# 2<% g3%#2:87T*
$/:72-74#5*
1h Notur o Cod [v005j
393
olgorlthms work. | w tst th GA rsults ogolnst th known onswr ond gt to b or not to
b", thn w`v succdd ln wrltlng our gntlc olgorlthm.
Crot o sktch thot gnrots rondom strlngs. W`ll nd to know how to do thls ln
ordr to lmplmnt th gntlc olgorlthm xompl thot wlll shortly ollow. How long
dos lt tok or Procsslng to rondomly gnrot th strlng cot"? How could you
odopt thls to gnrot o rondom dslgn uslng Procsslng`s shop-drowlng unctlons?
MO(.2&-( W"# MO(.2&-( W"#
W"= \4.8&;&4; X4':.4% U(%(2'&*; W"= \4.8&;&4; X4':.4% U(%(2'&*;
Bor w bgln wolklng through th gntlc olgorlthm, lt`s tok o momnt to dscrlb
thr cor prlnclpls o Lorwlnlon volutlon thot wlll b rqulrd os w lmplmnt our
slmulotlon. |n ordr or noturol slctlon to occur os lt dos ln notur, oll thr o ths
lmnts must b prsnt.
J. e$1$8/&@6 e$1$8/&@6 1hr must b o procss ln ploc by whlch chlldrn rclv th
proprtls o thlr pornts. | croturs llv long nough to rproduc, thn thlr
trolts or possd down to thlr chlldrn ln th nxt gnrotlon o croturs.
2. W(1/(&/!.6 W(1/(&/!.6 1hr must b o vorlty o trolts prsnt ln th populotlon or o mons
wlth whlch to lntroduc vorlotlon. |or xompl, lt`s soy thr ls o populotlon o
btls ln whlch oll th btls or xoctly th som. som color, som slz, som
wlngspon, som vrythlng. Wlthout ony vorlty ln th populotlon, th chlldrn wlll
olwoys b ldntlcol to th pornts ond to och othr. Nw comblnotlons o trolts
con nvr occur ond nothlng con volv.
3. Q$'$%&/!.6 Q$'$%&/!.6 1hr must b o mchonlsm by whlch som mmbrs o o populotlon
hov th opportunlty to b pornts ond poss down thlr gntlc lnormotlon ond
som do not. 1hls ls typlcolly rrrd to os survlvol o th lttst." |or xompl,
lt`s soy o populotlon o gozlls ls chosd by llons vry doy. 1h ostr gozlls
or mor llkly to scop th llons ond or thror mor llkly to llv longr ond
hov o chonc to rproduc ond poss thlr gns down to thlr chlldrn. 1h trm
t|ttest, howvr, con b o blt mlslodlng. Gnrolly, w thlnk o lt os monlng
blggr, ostr, or strongr. Whll thls moy b th cos ln som lnstoncs, noturol
slctlon oprots on th prlnclpl thot som trolts or bttr odoptd or th
crotur`s nvlronmnt ond thror produc o grotr llkllhood o survlvlng
ond rproduclng. |t hos nothlng to do wlth o glvn crotur blng bttr" [otr oll,
thls ls o subjctlv trmj or mor physlcolly lt." |n th cos o our typlng
monkys, or xompl, o mor lt" monky ls on thot hos typd o phros closr
to to b or not to b".
Choptr 9. 1h Lvolutlon o Cod
394
Nxt |`d llk to wolk through th norrotlv o th gntlc olgorlthm. W`ll do thls ln th contxt
o th typlng monky. 1h olgorlthm ltsl wlll b dlvldd lnto two ports. o st o condltlons or
lnltlollzotlon [l.. Procsslng`s #%23$45j ond th stps thot or rpotd ovr ond ovr ogoln
[l.. Procsslng`s &/,;45j untll w orrlv ot th corrct onswr.
W"> @,( e(;('&2 !%<*.&',E` 54.' CD P.(4'&;< 4 W"> @,( e(;('&2 !%<*.&',E` 54.' CD P.(4'&;< 4
5*Q:%4'&*; 5*Q:%4'&*;
|n th contxt o th typlng monky xompl, w wlll crot o populotlon o phross. [Not
thot w or uslng th trm phros" rothr loosly, monlng o strlng o choroctrs.j 1hls bgs
th qustlon. How do w crot thls populotlon? Hr ls whr th Lorwlnlon prlnclpl o
0(1/(&/!. 0(1/(&/!. opplls. Lt`s soy, or slmpllclty, thot w or trylng to volv th phros cot" ond
thot w hov o populotlon o thr phross.
H4G
)21
!8#
5ur, thr ls vorlty ln th thr phross obov, but try to mlx ond motch th choroctrs
vry whlch woy ond you wlll nvr gt cot. 1hr ls not enough vorlty hr to volv th
optlmol solutlon. Howvr, l w hod o populotlon o thousonds o phross, oll gnrotd
rondomly, choncs or thot ot lost on mmbr o th populotlon wlll hov o c os th lrst
choroctr, on wlll hov on o os th scond, ond on o t os th thlrd. A lorg populotlon wlll
most llkly glv us nough vorlty to gnrot th dslrd phros [ond ln Port 2 o th
olgorlthm, w`ll hov onothr opportunlty to lntroduc vn mor vorlotlon ln cos thr lsn`t
nough ln th lrst plocj. 5o w con b mor spcllc ln dscrlblng 5tp J ond soy.
Crot o populotlon o rondomly gnrotd lmnts.
1hls brlngs up onothr lmportont qustlon. Whot ls th lmnt ltsl? As w mov through
th xompls ln thls choptr, w`ll s svrol dlrnt scnorlos, w mlght hov o populotlon
o lmogs or o populotlon o vhlcls lo Choptr 6 [s pog 308j. 1h ky, ond th port thot
ls nw or us ln thls choptr, ls thot och mmbr o th populotlon hos o vlrtuol LNA," o st
o proprtls [w con coll thm gns"j thot dscrlb how o glvn lmnt looks or bhovs.
|n th cos o th typlng monky, or xompl, th LNA ls slmply o strlng o choroctrs.
|n th lld o gntlcs, thr ls on lmportont dlstlnctlon btwn th concpts genotype ond
phenotype. 1h octuol gntlc codln our cos, th dlgltol lnormotlon ltslls on lmnt`s
2$.!&@A$ 2$.!&@A$. 1hls ls whot gts possd down rom gnrotlon to gnrotlon. 1h A+$.!&@A$ A+$.!&@A$,
howvr, ls th xprsslon o thot doto. 1hls dlstlnctlon ls ky to how you wlll us gntlc
olgorlthms ln your own work. Whot or th objcts ln your world? How wlll you dslgn th
1h Notur o Cod [v005j
395
gnotyp or your objcts [th doto structur to stor och objct`s proprtlsj os wll os
th phnotyp [whot or you uslng ths vorlobls to xprss?j W do thls oll th tlm ln
grophlcs progrommlng. 1h slmplst xompl ls probobly color.
R#1*'U:# R#1*'U:# 9"#1*'U:# 9"#1*'U:#
lnt c 255,
lnt c J27,
lnt c 0,
As w con s, th gnotyp ls th dlgltol lnormotlon. Loch color ls o vorlobl thot stors on
lntgr ond w choos to xprss thot lntgr os o color. But how w choos to xprss th
doto ls orbltrory. |n o dlrnt opprooch, w could hov usd th lntgr to dscrlb th
lngth o o lln, th wlght o o orc, tc.
O&7# R#1*'U:# O&7# R#1*'U:# ./++#)#1' 9"#1*'U:# W5/1# 5#16'"X ./++#)#1' 9"#1*'U:# W5/1# 5#16'"X
lnt c 255,
lnt c J27,
lnt c 0,
1h nlc thlng obout our monky-typlng xompl ls thot thr ls no dlrnc btwn
gnotyp ond phnotyp. 1h LNA doto ltsl ls o strlng o choroctrs ond th xprsslon o
thot doto ls thot vry strlng.
5o, w con lnolly nd th dlscusslon o thls lrst stp ond b mor spcllc wlth lts
dscrlptlon, soylng.
Crot o populotlon o N lmnts, och wlth rondomly gnrotd LNA.
Choptr 9. 1h Lvolutlon o Cod
396
W"? @,( e(;('&2 !%<*.&',E` 54.' CCD U(%(2'&*; W"? @,( e(;('&2 !%<*.&',E` 54.' CCD U(%(2'&*;
Hr ls whr w opply th Lorwlnlon prlnclpl o se|ect|on. W nd to voluot th
populotlon ond dtrmln whlch mmbrs or lt to b slctd os pornts or th nxt
gnrotlon. 1h procss o slctlon con b dlvldd lnto two stps.
5P =0(':(&$ ;/&.$))6 5P =0(':(&$ ;/&.$))6
|or our gntlc olgorlthm to unctlon proprly, w wlll nd to dslgn whot ls rrrd to os o
;/&.$)) ;:.%&/!. ;/&.$)) ;:.%&/!.. 1h unctlon wlll produc o numrlc scor to dscrlb th ltnss o o glvn
mmbr o th populotlon. 1hls, o cours, ls not how th rol world works ot oll. Croturs or
not glvn o scor, thy slmply survlv or not. But ln th cos o th trodltlonol gntlc
olgorlthm, whr w or trylng to volv on optlmol solutlon to o problm, w nd to b obl
to numrlcolly voluot ony glvn posslbl solutlon.
Lt`s xomln our currnt xompl, th typlng monky. Agoln, lt`s slmplly th scnorlo ond
soy w or ottmptlng to volv th word cot". W hov thr mmbrs o th populotlon.
hut, cot, ond box. Cot ls obvlously th most lt, glvn thot lt hos two corrct choroctrs, hut hos
only on, ond box hos zro. And thr lt ls, our ltnss unctlon.
92/#$.. " /H$ #456$) 89 :8))$:/ :H&)&:/$).
.%2 .%2 G/'1#88 G/'1#88
hut J
cor 2
box 0
W wlll vntuolly wont to look ot xompls wlth mor sophlstlcotd ltnss unctlons, but thls
ls o good ploc to stort.
XP M1$(&$ ( -(&/.2 A!!'6 XP M1$(&$ ( -(&/.2 A!!'6
Onc th ltnss hos bn colculotd or oll mmbrs o th populotlon, w con thn slct
whlch mmbrs or lt to bcom pornts ond ploc thm ln o motlng pool. 1hr or svrol
dlrnt opproochs w could tok hr. |or xompl, w could mploy whot ls known os th
$'/&/)& $'/&/)& mthod ond soy, Whlch two mmbrs o th populotlon scord th hlghst? You two
wlll mok oll th chlldrn or th nxt gnrotlon." 1hls ls probobly on o th oslr mthods
to progrom, howvr, lt lls ln th oc o th prlnclpl o vorlotlon. | two mmbrs o th
populotlon [out o prhops thousondsj or th only ons ovollobl to rproduc, th nxt
gnrotlon wlll hov llttl vorlty ond thls moy stunt th volutlonory procss. W could
lnstod mok o motlng pool out o o lorgr numbror xompl, th top 50 o th
1h Notur o Cod [v005j
397
populotlon, 500 out o J,000. 1hls ls olso just os osy to progrom, but lt wlll not produc
optlmol rsults. |n thls cos, th hlgh-scorlng top lmnts would hov th som chonc o
blng slctd os o pornt os th ons toword th mlddl. And why should lmnt numbr
500 hov o solld shot o rproduclng, whll lmnt numbr 50J hos no shot?
A bttr solutlon or th motlng pool ls to us o A1!"("/'/)&/% A1!"("/'/)&/% mthod, whlch w`ll coll th
whl o ortun" [olso known os th roultt whl"j. 1o lllustrot thls mthod, lt`s
consldr o slmpl xompl whr w hov o populotlon o lv lmnts, och wlth o ltnss
scor.
I5#7#1' I5#7#1' G/'1#88 G/'1#88
A 3
B 4
C 0.5
L J.5
L J
1h lrst thlng w`ll wont to do ls .!1-('/C$ .!1-('/C$ oll th scors. Rmmbr normollzlng o vctor?
1hot lnvolvd toklng on vctor ond stondordlzlng lts lngth, sttlng lt to J. Whn w
normollz o st o ltnss scors, w or stondordlzlng thlr rong to btwn 0 ond J, os o
prcntog o totol ltnss. Lt`s odd up oll th ltnss scors.
totol ltnss 3 4 0.5 J.5 J J0
1hn lt`s dlvld och scor by th totol ltnss, glvlng us th normollzd ltnss.
I5#7#1' I5#7#1' G/'1#88 G/'1#88 %*)7&5/V#- G/'1#88 %*)7&5/V#- G/'1#88
IJ:)#88#- &8 & IJ:)#88#- &8 &
9#)0#1'&6# 9#)0#1'&6#
A 3 0.3 30
B 4 0.4 40
C 0.5 0.05 5
L J.5 0.J5 J5
L J 0.J J0
Choptr 9. 1h Lvolutlon o Cod
398
Now lt`s tlm or th whl o ortun.
5pln th whl ond you`ll notlc thot Llmnt B hos th hlghst chonc o blng slctd,
ollowd by A, thn L, thn L, ond lnolly C. 1hls proboblllty-bosd slctlon occordlng to
ltnss ls on xcllnt opprooch. On, lt guoronts thot th hlghst-scorlng lmnts wlll b
most llkly to rproduc. 1wo, lt dos not ntlrly llmlnot ony vorlotlon rom th populotlon.
nllk wlth th lltlst mthod, vn th lowst-scorlng lmnt [ln thls cos Cj hos o chonc
to poss lts lnormotlon down to th nxt gnrotlon. |t`s qult posslbl [ond otn th cosj
thot vn low-scorlng lmnts hov o tlny nuggt o gntlc cod thot ls truly usul ond
should not ntlrly b llmlnotd rom th populotlon. |or xompl, ln th cos o volvlng to
b or not to b", w mlght hov th ollowlng lmnts.
hY /8 6$ 8) #8/ /8 G8
lY /8 6$ 8) #8/ /8 02
fY IIIIIIIIIIIIIIII6$
As you con s, lmnts A ond B or clorly th most lt ond would hov th hlghst scor.
But nlthr contolns th corrct choroctrs or th nd o th phros. Llmnt C, vn though
lt would rclv o vry low scor, hoppns to hov th gntlc doto or th nd o th phros.
And so whll w would wont A ond B to b plckd to gnrot th mojorlty o th nxt
gnrotlon, w would stlll wont C to hov o smoll chonc to portlclpot ln th rproductlv
procss.
Iiure p.z
W"K @,( e(;('&2 !%<*.&',E` 54.' CCCD Y(Q.*9:2'&*; W"K @,( e(;('&2 !%<*.&',E` 54.' CCCD Y(Q.*9:2'&*;
Now thot w hov o strotgy or plcklng pornts, w nd to lgur out how to us
teptoduct|on to mok th populotlon`s nxt gnrotlon, kplng ln mlnd th Lorwlnlon
prlnclpl o hrdltythot chlldrn lnhrlt proprtls rom thlr pornts. Agoln, thr or o
numbr o dlrnt tchnlqus w could mploy hr. |or xompl, on rosonobl [ond osy
to progromj strotgy ls osxuol rproductlon, monlng w plck just on pornt ond crot o
1h Notur o Cod [v005j
399
chlld thot ls on xoct copy o thot pornt. 1h stondord opprooch wlth gntlc olgorlthms,
howvr, ls to plck two pornts ond crot o chlld occordlng to th ollowlng stps.
5P M1!))!0$16 5P M1!))!0$16
Crossovr lnvolvs crotlng o chlld out o th gntlc cod o two pornts. |n th cos o
th monky-typlng xompl, lt`s ossum w`v plckd two phross rom th motlng pool
[os outllnd ln our slctlon stpj.
M&)$#/ hY ^cqv
M&)$#/ lY MohW
|t`s now up to us to mok o chlld phros rom ths two. Prhops th most obvlous woy
[lt`s coll thls th 50/50 mthodj would b to tok th lrst two choroctrs rom A ond th
scond two rom B, lovlng us wlth.
A vorlotlon o thls tchnlqu ls to plck o rondom mldpolnt. |n othr words, w don`t hov to
plck xoctly hol o th cod rom och pornt. W could somtlms nd up wlth |LAY, ond
somtlms wlth |ORY. 1hls ls prrobl to th 50/50 opprooch, slnc w lncros th
vorlty o posslbllltls or th nxt gnrotlon.
Iiure p.
Iiure p.(: Piclin c rcndom midpoint
Choptr 9. 1h Lvolutlon o Cod
400
Anothr posslblllty ls to rondomly slct o pornt or och choroctr ln th chlld strlng. You
con thlnk o thls os llpplng o coln our tlms. hods tok rom pornt A, tolls rom pornt B.
Hr w could nd up wlth mony dlrnt rsults such os. PLRY, |LRK, |LRY, |ORY, tc.
1hls strotgy wlll produc ssntlolly th som rsults os th rondom mldpolnt mthod,
howvr, l th ordr o th gntlc lnormotlon ploys som rol ln xprsslng th phnotyp,
you moy prr on solutlon ovr th othr.
XP [:&(&/!.6 XP [:&(&/!.6
Onc th chlld LNA hos bn crotd vlo crossovr, w opply on lnol procss bor oddlng
th chlld to th nxt gnrotlon-:&(&/!. -:&(&/!.. Mutotlon ls on optlonol stp, os thr or som
coss ln whlch lt ls unncssory. Howvr, lt xlsts bcous o th Lorwlnlon prlnclpl o
vorlotlon. W crotd on lnltlol populotlon rondomly, moklng sur thot w stort wlth o vorlty o
lmnts. Howvr, thr con only b so much vorlty whn sdlng th lrst gnrotlon, ond
mutotlon ollows us to lntroduc oddltlonol vorlty throughout th volutlonory procss ltsl.
Mutotlon ls dscrlbd ln trms o o tote. A
glvn gntlc olgorlthm mlght hov o
mutotlon rot o 5 or J or 0.J, tc. Lt`s
ossum w just lnlshd wlth crossovr ond
ndd up wlth th chlld |ORY. | w hov o
mutotlon rot o J, thls mons thot or och
choroctr ln th phros gnrotd rom
crossovr, thr ls o J chonc thot lt wlll
mutot. Whot dos lt mon or o choroctr to
mutot? |n thls cos, w dln mutotlon os
plcklng o nw rondom choroctr. A J
proboblllty ls olrly low, ond most o th tlm mutotlon wlll not occur ot oll ln o our-choroctr
strlng [96 o th tlm to b mor prclsj. Howvr, whn lt dos, th mutotd choroctr ls
rplocd wlth o rondomly gnrotd on [s |lgur 9.6j.
Iiure p.: Coin-jlippin cpprocch
Iiure p.
1h Notur o Cod [v005j
40J
As w`ll s ln som o th xompls, th mutotlon rot con grotly oct th bhovlor o
th systm. Crtolnly, o vry hlgh mutotlon rot [such os, soy, 80j would ngot th
volutlonory procss ltsl. | th mojorlty o o chlld`s gns or gnrotd rondomly, thn
w connot guoront thot th mor lt" gns occur wlth grotr rquncy wlth och
succsslv gnrotlon.
1h procss o slctlon [plcklng two porntsj ond rproductlon [crossovr ond mutotlonj ls
opplld ovr ond ovr ogoln k tlms untll w hov o nw populotlon o k lmnts. At thls
polnt, th nw populotlon o chlldrn bcoms th currnt populotlon ond w loop bock to
voluot ltnss ond prorm slctlon ond rproductlon ogoln.
Now thot w hov dscrlbd oll th stps o th gntlc olgorlthm ln dtoll, lt`s tlm to
tronslot ths stps lnto Procsslng cod. Bcous th prvlous dscrlptlon wos o blt
longwlndd, lt`s look ot on ovrvlw o th olgorlthm lrst. W`ll thn covr och o th
thr stps ln lts own sctlon, worklng out th cod.
Q=*RN3 Q=*RN3
5tp J. ]./&/('/C$ ]./&/('/C$. Crot o populotlon o N lmnts, och wlth rondomly gnrotd LNA.
_ddN3 _ddN3
5tp 2. Q$'$%&/!. Q$'$%&/!.. Lvoluot th ltnss o och lmnt o th populotlon ond bulld o motlng
pool.
5tp 3. S$A1!8:%&/!. S$A1!8:%&/!.. Rpot N tlms.
oj Plck two pornts wlth proboblllty occordlng to rlotlv ltnss.
bj Crossovrcrot o chlld" by comblnlng th LNA o ths two pornts.
cj Mutotlonmutot th chlld`s LNA bosd on o glvn proboblllty.
dj Add th nw chlld to o nw populotlon.
5tp 4. Rploc th old populotlon wlth th nw populotlon ond rturn to 5tp 2.
W"L P*9( +*. P.(4'&;< ',( 5*Q:%4'&*; W"L P*9( +*. P.(4'&;< ',( 5*Q:%4'&*;
U'(Q #D C;&'&4%&c( 5*Q:%4'&*; U'(Q #D C;&'&4%&c( 5*Q:%4'&*;
| w`r golng to crot o populotlon, w nd o doto structur to stor o llst o mmbrs o
th populotlon. |n most coss [such os our typlng-monky xomplj, th numbr o lmnts
ln th populotlon con b lxd, ond so w us on orroy. [Lotr w`ll s xompls thot
lnvolv o growlng/shrlnklng populotlon ond w`ll us on V//,"l:#2.j But on orroy o whot?
W nd on objct thot stors th gntlc lnormotlon or o mmbr o th populotlon. Lt`s
coll lt E^D E^D.
Choptr 9. 1h Lvolutlon o Cod
402
1h populotlon wlll thn b on orroy o \kV objcts.
But whot stu gos ln th \kV closs? |or o typlng monky, lts LNA ls th rondom phros lt
typs, o strlng o choroctrs.
Whll thls ls prctly rosonobl or thls portlculor xompl, w`r not golng to us on octuol
[2/:7? objct os th gntlc cod. |nstod, w`ll us on orroy o choroctrs.
By uslng on orroy, w`ll b obl to xtnd oll th cod w wrlt lnto othr xompls. |or
xompl, th LNA o o crotur ln o physlcs systm mlght b on orroy o ]`%028/sor or on
lmog, on orroy o lntgrs [RGB colorsj. W con dscrlb ony st o proprtls ln on orroy,
ond vn though o strlng ls convnlnt or thls portlculor sktch, on orroy wlll srv os o bttr
oundotlon or utur volutlonory xompls.
Our gntlc olgorlthm dlctots thot w crot o populotlon o N lmnts, och wlth tondom|y
genetoted DNA. 1hror, ln th objct`s constructor, w rondomly crot och choroctr o
th orroy.
Now thot w hov th constructor, w con rturn to #%23$45 ond lnltlollz och \kV objct ln
th populotlon orroy.
0-,## \kV 1
@
A population of 100 DNA objects \kVKL $8$3-,2:87 ' 7%; \kVK)BBL*
0-,## \kV 1
[2/:7? $</,#%*
@
0-,## \kV 1
Each "gene" is one element of the array. We
need 18 genes because "to be or not to be
is 18 characters long.
0<,/KL ?%7%# ' 7%; 0<,/K)XL*
@
0-,## \kV 1
0<,/KL ?%7%# ' 7%; 0<,/K)XL*
\kV45 1
E8/ 4:72 : ' B* : P ?%7%#N-%7?2<* :((5 1
Picking randomly from a range of characters
with ASC values between 32 and 128. For
more about ASC: http://en.wikipedia.org/
wiki/ASC
?%7%#K:L ' 40<,/5 /,7&894H>C)>X5*
@
@
@
1h Notur o Cod [v005j
403
Our \kV closs ls not ot oll complt. W`ll nd to odd unctlons to lt to prorm oll th othr
tosks ln our gntlc olgorlthm, whlch w`ll do os w wolk through stps 2 ond 3.
\kVKL $8$3-,2:87 ' 7%; \kVK)BBL*
A8:& #%23$45 1
E8/ 4:72 : ' B* : P $8$3-,2:87N-%7?2<* :((5 1
nitializing each member of the population $8$3-,2:87K:L ' 7%; \kV45*
@
@
U'(Q 0D U(%(2'&*; U'(Q 0D U(%(2'&*;
5tp 2 rods, "lvo|uote the t|tness ot eoch e|ement ot the popu|ot|on ond bu||d o mot|ng
poo|." Lt`s lrst voluot och objct`s ltnss. Lorllr w stotd thot on posslbl ltnss
unctlon or our typd phross ls th totol numbr o corrct choroctrs. Lt`s rvls thls
ltnss unctlon o llttl blt ond stot lt os th prcntog o corrct choroctrsl.., th totol
numbr o corrct choroctrs dlvldd by th totol choroctrs.
^2/#$.. " b8/&' w fH&)&:/$). f8))$:/;b8/&' w fH&)&:/$).
Whr should w colculot th ltnss? 5lnc th \kV closs contolns th gntlc lnormotlon
[th phros w wlll tst ogolnst th torgt phrosj, w con wrlt o unctlon lnsld th \kV
closs ltsl to scor lts own ltnss. Lt`s ossum w hov o torgt phros.
W con now compor och gn" ogolnst th corrspondlng choroctr ln th torgt phros,
lncrmntlng o countr och tlm w gt o corrct choroctr.
[2/:7? 2,/?%2 ' T28 I% 8/ 782 28 I%T*
0-,## \kV 1
We are adding another variable to the DNA
class to track fitness.
E-8,2 E:27%##*
Function to score fitness A8:& E:27%## 45 1
:72 #08/% ' B*
E8/ 4:72 : ' B* : P ?%7%#N-%7?2<* :((5 1
s the character correct? :E 4?%7%#K:L '' 2,/?%2N0<,/V24:55 1
f so, increment the score. #08/%((*
@
@
Fitness is the percentage correct. E:27%## ' E-8,24#08/%5=2,/?%2N-%7?2<45*
@
Choptr 9. 1h Lvolutlon o Cod
404
|n th moln tob`s &/,;45, th vry lrst stp w`ll tok ls to coll th ltnss unctlon or och
mmbr o th populotlon.
Atr w hov oll th ltnss scors, w con bulld th motlng pool" thot w`ll nd or th
rproductlon stp. 1h motlng pool ls o doto structur rom whlch w`ll contlnuously plck two
pornts. Rcolllng our dscrlptlon o th slctlon procss, w wont to plck pornts wlth
probobllltls colculotd occordlng to ltnss. |n othr words, th mmbrs o th populotlon
thot hov th hlghst ltnss scors should b most llkly to b plckd, thos wlth th lowst
scors, th lost llkly.
|n th |ntroductlon [s pog 7j, w covrd th boslcs o proboblllty ond gnrotlng o custom
dlstrlbutlon o rondom numbrs. W`r golng to us thos tchnlqus to osslgn o proboblllty
to och mmbr o th populotlon, plcklng pornts by splnnlng th whl o ortun." Lt`s
look ot |lgur 9.2 ogoln.
|t mlght b un to do somthlng rldlculous ond octuolly progrom o slmulotlon o o splnnlng
whl os dplctd obov. But thls ls qult unncssory.
A8:& &/,;45 1
E8/ 4:72 : ' B* : P $8$3-,2:87N-%7?2<* :((5 1
$8$3-,2:87K:LNE:27%##45*
@
Iiure p.z (ccin)
1h Notur o Cod [v005j
405
|nstod w con plck rom th lv optlons
[ABCLLj occordlng to thlr probobllltls by
llllng on V//,"l:#2 wlth multlpl lnstoncs
o och pornt. |n othr words, lt`s soy you
hod o buckt o woodn lttrs30 As, 40
Bs, 5 Cs, J5 Ls, ond J0 Ls.
| you plck o rondom lttr out o thot
buckt, thr`s o 30 chonc you`ll gt on
A, o 5 chonc you`ll gt o C, ond so on.
|or us, thot buckt ls on V//,"l:#2, ond
och woodn lttr ls o potntlol pornt.
W odd och pornt to th V//,"l:#2 N
numbr o tlms whr N ls quol to lts
prcntog scor.
Iiure p.;
Start with an empty mating pool. V//,"l:#2P\kV^ 9,2:7?]88- ' 7%;
V//,"l:#2P\kV^45*
E8/ 4:72 : ' B* : P $8$3-,2:87N-%7?2<* :((5 1
n is equal to fitness times 100, which
leaves us with an integer between 0 and
100.
:72 7 ' :724$8$3-,2:87K:LNE:27%## Q )BB5*
E8/ 4:72 o ' B* o P 7* o((5 1
Add each member of the population to the
mating pool N times.
9,2:7?]88-N,&&4$8$3-,2:87K:L5*
@
@
On o th othr mthods w usd to gnrot o custom dlstrlbutlon o rondom
numbrs ls colld th Mont Corlo mthod. 1hls tchnlqu lnvolvd plcklng two
rondom numbrs, wlth th scond numbr octlng os o quollylng numbr ond
dtrmlnlng l th lrst rondom numbr should b kpt or thrown owoy. Rwrlt th
obov motlng pool olgorlthm to us th Mont Corlo mthod lnstod.
MO(.2&-( W"0 MO(.2&-( W"0
Choptr 9. 1h Lvolutlon o Cod
406
|n som coss, th whl o ortun olgorlthm wlll hov on xtroordlnorlly hlgh
prrnc or som lmnts ovr othrs. 1ok th ollowlng probobllltls.
hY `BC
lY DC
fY DC
1hls ls somtlms undslrobl glvn how lt wlll dcros th omount o vorlty ln thls
systm. A solutlon to thls problm ls to rploc th colculotd ltnss scors wlth th
ordlnols o scorlng [monlng thlr ronkj.
hY =?C *E;U+
lY EEC *>;U+
fY D@C *D;U+
Rwrlt th motlng pool olgorlthm to us thls mthod lnstod.
MO(.2&-( W"= MO(.2&-( W"=
U'(Q =D Y(Q.*9:2'&*; U'(Q =D Y(Q.*9:2'&*;
Wlth th motlng pool rody to go, lt`s tlm to mok som bobls. 1h lrst stp ls to plck two
pornts. Agoln, lt`s somwhot o on orbltrory dclslon to plck two pornts. |t crtolnly mlrrors
humon rproductlon ond ls th stondord mons ln th trodltlonol GA, but ln trms o your
work, thr rolly orn`t ony rstrlctlons hr. You could choos to prorm osxuol"
rproductlon wlth on pornt, or com up wlth o schm or plcklng thr or our pornts rom
whlch to gnrot chlld LNA. |or thls cod dmonstrotlon, w`ll stlck to two pornts ond coll
thm $,/%72V ond $,/%72W.
|lrst thlng w nd or two rondom lndlcs lnto th motlng poolrondom numbrs btwn 0
ond th slz o th V//,"l:#2.
W con us ths lndlcs to rtrlv on octuol LNA lnstonc rom th motlng pool.
Bcous w hov multlpl lnstoncs o th som \kV objcts ln th motlng pool [not to
mntlon thot w could plck th som rondom numbr twlcj, lt`s posslbl thot $,/%72V ond
$,/%72W could b th som \kV objct. | w wontd to b strlct, w could wrlt som cod to
:72 , ' :724/,7&8949,2:7?]88-N#:F%4555*
:72 I ' :724/,7&8949,2:7?]88-N#:F%4555*
\kV $,/%72V ' 9,2:7?]88-N?%24,5*
\kV $,/%72W ' 9,2:7?]88-N?%24I5*
1h Notur o Cod [v005j
407
nsur thot w hovn`t plckd th som pornt twlc, but w would goln vry llttl
lclncy or oll thot xtro cod. 5tlll, lts worth trylng thls os on xrcls.
Onc w hov th two pornts, w con prorm %1!))!0$1 %1!))!0$1 to gnrot th chlld LNA,
ollowd by -:&(&/!. -:&(&/!..
O cours, th unctlons 0/8##8A%/45 ond 932,2%45 don`t moglcolly xlst ln our \kV closs,
w hov to wrlt thm. 1h woy w colld 0/8##8A%/45 obov lndlcots thot th unctlon
rclvs on lnstonc o LNA os on orgumnt ond rturns o nw lnstonc o LNA, th chlld.
1h obov crossovr unctlon uss th rondom mldpolnt" mthod o crossovr, ln whlch
th lrst sctlon o gns ls tokn rom pornt A ond th scond sctlon rom pornt B.
Add cod to th obov to guoront thot you hov plckd two unlqu pornts."
MO(.2&-( W"> MO(.2&-( W">
A function for crossover \kV 0<:-& ' $,/%72VN0/8##8A%/4$,/%72W5*
A function for mutation 0<:-&N932,2%45*
The function receives one argument (DNA)
and returns DNA.
\kV 0/8##8A%/4\kV $,/27%/5 1
The child is a new instance of DNA. Note
that the DNA is generated randomly in the
constructor, but we will overwrite it below
with DNA from parents.
\kV 0<:-& ' 7%; \kV45*
Picking a random "midpoint in the genes
array
:72 9:&$8:72 ' :724/,7&894?%7%#N-%7?2<55*
E8/ 4:72 : ' B* : P ?%7%#N-%7?2<* :((5 1
Before midpoint copy genes from one
parent, after midpoint copy genes from the
other parent
:E 4: ^ 9:&$8:725 0<:-&N?%7%#K:L ' ?%7%#K:L*
%-#% 0<:-&N?%7%#K:L ' $,/27%/N?%7%#K:L*
@
Return the new child DNA /%23/7 0<:-&*
@
Choptr 9. 1h Lvolutlon o Cod
408
1h mutot[j unctlon ls vn slmplr to wrlt thon crossovr[j. All w nd to do ls loop
through th orroy o gns ond or och rondomly plck o nw choroctr occordlng to th
mutotlon rot. Wlth o mutotlon rot o J, or xompl, w would plck o nw choroctr on
tlm out o o hundrd.
1h ntlr unctlon thror rods.
Rwrlt th crossovr unctlon to us th coln llpplng" mthod lnstod, ln whlch och
gn hos o 50 chonc o comlng rom pornt A ond o 50 chonc o comlng rom
pornt B.
MO(.2&-( W"? MO(.2&-( W"?
E-8,2 932,2:87Y,2% ' BNB)*
:E 4/,7&894)5 P 932,2:87Y,2%5 1
Any code here would be executed 1% of the
time.
@
A8:& 932,2%45 1
Looking at each gene in the array E8/ 4:72 : ' B* : P ?%7%#N-%7?2<* :((5 1
:E 4/,7&894)5 P 932,2:87Y,2%5 1
Mutation, a new random character ?%7%#K:L ' 40<,/5 /,7&894H>C)>X5*
@
@
@
W"N e(;('&2 !%<*.&',E-D 5:''&;< C' !%% @*<(',(. W"N e(;('&2 !%<*.&',E-D 5:''&;< C' !%% @*<(',(.
You moy hov notlcd thot w`v ssntlolly wolkd through th stps o th gntlc
olgorlthm twlc, onc dscrlblng lt ln norrotlv orm ond onothr tlm wlth cod snlppts
lmplmntlng och o th stps. Whot |`d llk to do ln thls sctlon ls condns th prvlous
two sctlons lnto on pog, wlth th olgorlthm dscrlbd ln just thr stps ond th
corrspondlng cod olongsld.
1h Notur o Cod [v005j
409
IJ&7:5# CK;L R#1#'/0 &56*)/'"7L IN*5N/16 O"&3#8:#&)#
VariabIes we need for our GA
Mutation rate E-8,2 932,2:87Y,2%*
Population total :72 282,-]8$3-,2:87 ' )JB*
Population array \kVKL $8$3-,2:87*
Mating pool ArrayList V//,"l:#2P\kV^ 9,2:7?]88-*
Target phrase [2/:7? 2,/?%2*
A8:& #%23$45 1
#:F%4>BBC >BB5*
nitializing target phrase and mutation rate 2,/?%2 ' T28 I% 8/ 782 28 I%T*
932,2:87Y,2% ' BNB)*
Step 1: InitiaIize PopuIation $8$3-,2:87 ' 7%; \kVK282,-]8$3-,2:87L*
E8/ 4:72 : ' B* : P $8$3-,2:87N-%7?2<* :((5 1
$8$3-,2:87K:L ' 7%; \kV45*
@
@
A8:& &/,;45 1
Step 2: SeIection
Step 2a: Calculate fitness. E8/ 4:72 : ' B* : P $8$3-,2:87N-%7?2<* :((5 1
$8$3-,2:87K:LNE:27%##45*
@
Choptr 9. 1h Lvolutlon o Cod
4J0
1h moln tob prclsly mlrrors th stps o th gntlc olgorlthm. Howvr, most o th
unctlonollty colld upon ls octuolly prsnt ln th \kV closs ltsl.
Step 2b: Build mating pool. V//,"l:#2P\kV^ 9,2:7?]88- ' 7%; V//,"l:#2P\kV^45*
E8/ 4:72 : ' B* : P $8$3-,2:87N-%7?2<* :((5 1
Add each member n times according to its
fitness score.
:72 7 ' :724$8$3-,2:87K:LNE:27%## Q )BB5*
E8/ 4:72 o ' B* o P 7* o((5 1
9,2:7?]88-N,&&4$8$3-,2:87K:L5*
@
@
Step 3: Reproduction E8/ 4:72 : ' B* : P $8$3-,2:87N-%7?2<* :((5 1
:72 , ' :724/,7&8949,2:7?]88-N#:F%4555*
:72 I ' :724/,7&8949,2:7?]88-N#:F%4555*
\kV $,/27%/V ' 9,2:7?]88-N?%24,5*
\kV $,/27%/W ' 9,2:7?]88-N?%24I5*
Step 3a: Crossover \kV 0<:-& ' $,/27%/VN0/8##8A%/4$,/27%/W5*
Step 3b: Mutation 0<:-&N932,2%4932,2:87Y,2%5*
Note that we are overwriting the population
with the new children. When draw() loops,
we will perform all the same steps with the
new population of children.
$8$3-,2:87K:L ' 0<:-&*
@
@
0-,## \kV 1
0<,/KL ?%7%#*
E-8,2 E:27%##*
Create DNA randomly. \kV45 1
?%7%# ' 7%; 0<,/K2,/?%2N-%7?2<45L*
E8/ 4:72 : ' B* : P ?%7%#N-%7?2<* :((5 1
?%7%#K:L ' 40<,/5 /,7&894H>C)>X5*
@
@
Calculate fitness. A8:& E:27%##45 1
:72 #08/% ' B*
E8/ 4:72 : ' B* : P ?%7%#N-%7?2<* :((5 1
:E 4?%7%#K:L '' 2,/?%2N0<,/V24:55 1
#08/%((*
@
@
E:27%## ' E-8,24#08/%5=2,/?%2N-%7?2<45*
@
1h Notur o Cod [v005j
4JJ
Crossover \kV 0/8##8A%/4\kV $,/27%/5 1
\kV 0<:-& ' 7%; \kV4?%7%#N-%7?2<5*
:72 9:&$8:72 ' :724/,7&894?%7%#N-%7?2<55*
E8/ 4:72 : ' B* : P ?%7%#N-%7?2<* :((5 1
:E 4: ^ 9:&$8:725 0<:-&N?%7%#K:L ' ?%7%#K:L*
%-#% 0<:-&N?%7%#K:L ' $,/27%/N?%7%#K:L*
@
/%23/7 0<:-&*
@
Mutation A8:& 932,2%4E-8,2 932,2:87Y,2%5 1
E8/ 4:72 : ' B* : P ?%7%#N-%7?2<* :((5 1
:E 4/,7&894)5 P 932,2:87Y,2%5 1
?%7%#K:L ' 40<,/5 /,7&894H>C)>X5*
@
@
@
Convert to StringPHENOTYPE. [2/:7? ?%2]</,#%45 1
/%23/7 7%; [2/:7?4?%7%#5*
@
@
Add oturs to th obov xompl to rport mor lnormotlon obout th progrss o
th gntlc olgorlthm ltsl. |or xompl, show th phros closst to th torgt och
gnrotlon, os wll os rport on th numbr o gnrotlons, ovrog ltnss, tc. 5top
th gntlc olgorlthm onc lt hos solvd th phros. Consldr wrltlng o ]8$3-,2:87
closs to monog th GA [lnstod o lncludlng oll th cod ln drow[jj.
MO(.2&-( W"K MO(.2&-( W"K
Choptr 9. 1h Lvolutlon o Cod
4J2
W"W e(;('&2 !%<*.&',E-D ]43( @,(E a*:. F8; W"W e(;('&2 !%<*.&',E-D ]43( @,(E a*:. F8;
1h nlc thlng obout uslng gntlc olgorlthms ln o projct ls thot xompl cod con oslly b
portd rom oppllcotlon to oppllcotlon. 1h cor mchonlcs o slctlon ond rproductlon
don`t nd to chong. 1hr or, howvr, thr ky componnts to gntlc olgorlthms thot
you, th dvlopr, wlll hov to customlz or och us. 1hls ls cruclol to movlng byond
trlvlol dmonstrotlons o volutlonory slmulotlons [os ln th 5hokspor xomplj to crotlv
uss ln projcts thot you mok ln Procsslng ond othr crotlv progrommlng nvlronmnts.
1(/ n#D R4./&;< ',( I4.&4)%(- 1(/ n#D R4./&;< ',( I4.&4)%(-
1hr orn`t o lot o vorlobls to th gntlc olgorlthm ltsl. |n oct, l you look ot th prvlous
xompl`s cod, you`ll s only two globol vorlobls [not lncludlng th orroys ond V//,"l:#2s
to stor th populotlon ond motlng poolj.
1hs two vorlobls con grotly oct th bhovlor o th systm, ond lt`s not such o good
ldo to orbltrorlly osslgn thm volus [though twoklng thm through trlol ond rror ls o
prctly rosonobl woy to orrlv ot optlmol volusj.
1h volus | chos or th 5hokspor dmonstrotlon wr plckd to vlrtuolly guoront thot
th gntlc olgorlthm would solv or th phros, but not too qulckly [opproxlmotly J,000
gnrotlons on ovrogj so os to dmonstrot th procss ovr o rosonobl prlod o tlm. A
much lorgr populotlon, howvr, would ylld ostr rsults [l th gool wr olgorlthmlc
lclncy rothr thon dmonstrotlonj. Hr ls o tobl o som rsults.
!*'&5 9*:(5&'/*1 !*'&5 9*:(5&'/*1 P('&'/*1 H&'# P('&'/*1 H&'#
%(7E#) *+ %(7E#) *+
R#1#)&'/*18 (1'/5 R#1#)&'/*18 (1'/5
9")&8# O*5N#- 9")&8# O*5N#-
!*'&5 !/7# W/1 !*'&5 !/7# W/1
8#0*1-8X (1'/5 9")&8# 8#0*1-8X (1'/5 9")&8#
O*5N#- O*5N#-
J50 J J089 J8.8
300 J 448 8.2
J,000 J 7J J.8
50,000 J 27 4.3
Notlc how lncroslng th populotlon slz drostlcolly rducs th numbr o gnrotlons
ndd to solv or th phros. Howvr, lt dosn`t ncssorlly rduc th omount o tlm.
Onc our populotlon bolloons to lty thousond lmnts, th sktch runs slowly, glvn th
E-8,2 932,2:87Y,2% ' BNB)*
:72 282,-]8$3-,2:87 ' )JB*
1h Notur o Cod [v005j
4J3
omount o tlm rqulrd to procss ltnss ond bulld o motlng pool out o so mony lmnts.
[1hr or, o cours, optlmlzotlons thot could b mod should you rqulr such o lorg
populotlon.j
|n oddltlon to th populotlon slz, th mutotlon rot con grotly oct prormonc.
!*'&5 9*:(5&'/*1 !*'&5 9*:(5&'/*1 P('&'/*1 H&'# P('&'/*1 H&'#
%(7E#) *+ %(7E#) *+
R#1#)&'/*18 (1'/5 R#1#)&'/*18 (1'/5
9")&8# O*5N#- 9")&8# O*5N#-
!*'&5 !/7# W/1 !*'&5 !/7# W/1
8#0*1-8X (1'/5 8#0*1-8X (1'/5
9")&8# O*5N#- 9")&8# O*5N#-
J,000 0 37 or nvr? J.2 or nvr?
J,000 J 7J J.8
J,000 2 60 J.6
J,000 J0 nvr? nvr?
Wlthout ony mutotlon ot oll [0j, you just hov to gt lucky. | oll th corrct choroctrs or
prsnt somwhr ln som mmbr o th lnltlol populotlon, you`ll volv th phros vry
qulckly. | not, thr ls no woy or th sktch to vr roch th xoct phros. Run lt o w
tlms ond you`ll s both lnstoncs. |n oddltlon, onc th mutotlon rot gts hlgh nough
[J0, or xomplj, thr ls so much rondomnss lnvolvd [J out o vry J0 lttrs ls
rondom ln och nw chlldj thot th slmulotlon ls prtty much bock to o rondom typlng
monky. |n thory, lt wlll vntuolly solv th phros, but you moy b woltlng much, much
longr thon ls rosonobl.
1(/ n0D @,( +&';(-- +:;2'&*; 1(/ n0D @,( +&';(-- +:;2'&*;
Ploylng oround wlth th mutotlon rot or populotlon totol ls prtty osy ond lnvolvs llttl
mor thon typlng numbrs ln your sktch. 1h rol hord work o o dvloplng o gntlc
olgorlthm ls ln wrltlng o ltnss unctlon. | you connot dln your problm`s gools ond
voluot numrlcolly how wll thos gools hov bn ochlvd, thn you wlll not hov
succssul volutlon ln your slmulotlon.
Bor w thlnk obout othr scnorlos wlth othr ltnss unctlons, lt`s look ot lows ln our
5hoksporon ltnss unctlon. Consldr solvlng or o phros thot ls not nlntn
choroctrs long, but on thousond. Now, lt`s soy thr or two mmbrs o th populotlon,
on wlth 800 choroctrs corrct ond on wlth 80J. Hr or thlr ltnss scors.
Phros A. 800 choroctrs corrct ltnss 80
Phros B. 80J choroctrs corrct ltnss 80.J
Choptr 9. 1h Lvolutlon o Cod
4J4
1hr or o coupl o problms hr. |lrst, w or oddlng lmnts to th motlng pool N
numbrs o tlms, whr N quols ltnss multlplld by on hundrd. Objcts con only b
oddd to on V//,"l:#2 o whol numbr o tlms, ond so A ond B wlll both b oddd 80 tlms,
glvlng thm on quol proboblllty o blng slctd. Lvn wlth on lmprovd solutlon thot toks
lootlng polnt probobllltls lnto occount, 80.J ls only o tny tlny blt hlghr thon 80. But
gttlng 80J choroctrs rlght ls o whol lot bttr thon 800 ln th volutlonory scnorlo. W
rolly wont to mok thot oddltlonol choroctr count. W wont th ltnss scor or 80J
choroctrs to b xponntlolly bttr thon th scor or 800.
1o put lt onothr woy, lt`s groph th ltnss unctlon.
1hls ls o llnor groph, os th numbr o choroctrs gos up, so dos th ltnss scor.
Howvr, whot l th ltnss lncrosd xponntlolly os th numbr o corrct choroctrs
lncrosd? Our groph could thn look somthlng llk.
1h mor corrct choroctrs, th vn grotr th ltnss. W con ochlv thls typ o rsult
ln o numbr o dlrnt woys. |or xompl, w could soy.
92/#$.. " *#456$) 89 :8))$:/ :H&)&:/$).+ F *#456$) 89 :8))$:/ :H&)&:/$).+
Lt`s soy w hov two mmbrs o th populotlon, on wlth lv corrct choroctrs ond on
wlth slx. 1h numbr 6 ls o 20 lncros ovr th numbr 5. Lt`s look ot th ltnss scors
squord.
Iiure p.8
Iiure p.p
1h Notur o Cod [v005j
4J5
,"&)&0'#)8 0*))#0' ,"&)&0'#)8 0*))#0' G/'1#88 G/'1#88
5 25
6 36
1h ltnss scors lncros xponntlolly rlotlv to th numbr o corrct choroctrs. 36 ls
o 44 lncros ovr 25.
Hr`s onothr ormulo.
92/#$.. " >
*#456$) 89 :8))$:/ :H&)&:/$).+
,"&)&0'#)8 0*))#0' ,"&)&0'#)8 0*))#0' G/'1#88 G/'1#88
J 2
2 4
3 8
4 J6
Hr, th ltnss scors lncros ot o ostr rot, doubllng wlth och oddltlonol corrct
choroctr.
Whll thls rothr spcllc dlscusslon o xponntlol vs. llnor ltnss unctlons ls on
lmportont dtoll ln th dslgn o o good ltnss unctlon, | don`t wont us to mlss th mor
lmportont polnt hr. Des|gn yout own t|tness tunct|on| | srlously doubt thot ony projct
you undrtok ln Procsslng wlth gntlc olgorlthms wlll octuolly lnvolv countlng th
corrct numbr o choroctrs ln o strlng. |n th contxt o thls book, lt`s mor llkly you wlll
b looklng to volv o crotur thot ls port o o physlcs systm. Prhops you or looklng to
optlmlz th wlghts o strlng bhovlors so o crotur con bst scop o prdotor or
ovold on obstocl or mok lt through o moz. You hov to osk yoursl whot you`r hoplng
to voluot.
Rwrlt th ltnss unctlon to lncros xponntlolly occordlng to th numbr o
corrct choroctrs. Not thot you wlll olso hov to normollz th ltnss volus to o
rong btwn 0 ond J so thy con b oddd to th motlng pool o rosonobl
numbr o tlms.
MO(.2&-( W"L MO(.2&-( W"L
Choptr 9. 1h Lvolutlon o Cod
4J6
Lt`s consldr o roclng slmulotlon ln whlch o vhlcl ls volvlng o dslgn optlmlzd or spd.
92/#$.. " /8/&' #456$) 89 9)&5$. )$X42)$1 98) L$H2:'$ /8 )$&:H /&)G$/
How obout o connon thot ls volvlng th optlmol woy to shoot o torgt?
92/#$.. " :&##8#6&'' 12./&#:$ /8 /&)G$/
1h dslgn o computr-controlld ployrs ln o gom ls olso o common scnorlo. Lt`s soy you
or progrommlng o soccr gom ln whlch th usr ls th gooll. 1h rst o th ployrs or
controlld by your progrom ond hov o st o poromtrs thot dtrmln how thy klck o boll
towords th gool. Whot would th ltnss scor or ony glvn ployr b?
92/#$.. " /8/&' G8&'. .:8)$1
1hls, obvlously, ls o slmpllstlc tok on th gom o soccr, but lt lllustrots th polnt. 1h mor
gools o ployr scors, th hlghr lts ltnss, ond th mor llkly lts gntlc lnormotlon wlll
oppor ln th nxt gom. Lvn wlth o ltnss unctlon os slmpl os th on dscrlbd hr,
thls scnorlo ls dmonstrotlng somthlng vry powrulth odoptoblllty o o systm. | th
ployrs contlnu to volv rom gom to gom to gom, whn o nw humon usr ntrs th
gom wlth o compltly dlrnt strotgy, th systm wlll qulckly dlscovr thot th ltnss
scors or golng down ond volv o nw optlmol strotgy. |t wlll odopt. [Lon`t worry, thr ls
vry llttl dongr ln thls rsultlng ln sntlnt robots thot wlll nslov oll humons.j
|n th nd, l you do not hov o ltnss unctlon thot ctlvly voluots th prormonc o
th lndlvlduol lmnts o your populotlon, you wlll not hov ony volutlon. And th ltnss
unctlon rom on xompl wlll llkly not opply to o totolly dlrnt projct. 5o thls ls th port
whr you gt to shln. You hov to dslgn o unctlon, somtlms rom scrotch, thot works or
your portlculor projct. And whr do you do thls? All you hov to dlt or thos w llns o
cod lnsld th unctlon thot computs th ltnss vorlobl.
A8:& E:27%##45 1
iiiiiiiiiiii
iiiiiiiiiiii
E:27%## ' iiiiiiiiii
@
1(/ n=D e(;*'/Q( 4;9 5,(;*'/Q( 1(/ n=D e(;*'/Q( 4;9 5,(;*'/Q(
1h lnol ky to dslgnlng your own gntlc olgorlthm rlots to how you choos to ncod
th proprtls o your systm. Whot or you trylng to xprss, ond how con you tronslot thot
xprsslon lnto o bunch o numbrs? Whot ls th gnotyp ond phnotyp?
Whn tolklng obout th ltnss unctlon, w hopplly ossumd w could crot computr-
controlld klckrs thot och hod o st o poromtrs thot dtrmln how thy klck o boll
towords th gool." Howvr, whot thos poromtrs or ond how you choos to ncod thm
ls up to you.
1h Notur o Cod [v005j
4J7
W stortd wlth th 5hokspor xompl bcous o how osy lt wos to dslgn both th
gnotyp [on orroy o choroctrsj ond lts xprsslon, th phnotyp [th strlng drown ln th
wlndowj.
1h good nws lsond w hlntd ot thls ot th stort o thls choptryou`v rolly bn
dolng thls oll olong. Anytlm you wrlt o closs ln Procsslng, you mok o whol bunch o
vorlobls.
All w nd to do to volv thos poromtrs ls to turn thm lnto on orroy, so thot th orroy
con b usd wlth oll o th unctlons0/8##8A%/45, 932,2%45, tc.ound ln th \kV closs.
On common solutlon ls to us on orroy o lootlng polnt numbrs btwn 0 ond J.
Notlc how w`v now put th gntlc doto [gnotypj ond lts xprsslon [phnotypj lnto
two sporot closss. 1h \kV closs ls th gnotyp ond th Vhlcl closs uss o \kV objct
to drlv lts bhovlors ond xprss thot doto vlsuollylt ls th phnotyp. 1h two con b
llnkd by crotlng o \kV lnstonc lnsld th vhlcl closs ltsl.
0-,## `%<:0-% 1
E-8,2 9,!#$%%&*
E-8,2 9,!E8/0%*
E-8,2 #:F%*
E-8,2 #%$,/,2:87+%:?<2*
== %20N
0-,## \kV 1
An array of floats E-8,2KL ?%7%#*
\kV4:72 7395 1
?%7%# ' 7%; E-8,2K739L*
E8/ 4:72 : ' B* : P ?%7%#N-%7?2<* :((5 1
Always pick a number between 0 and 1. ?%7%#K:L ' E-8,24)5*
@
@
0-,## `%<:0-% 1
A DNA object embedded into the Vehicle
class
\kV &7,*
E-8,2 9,!#$%%&*
E-8,2 9,!E8/0%*
E-8,2 #:F%*
E-8,2 #%$,/,2:87+%:?<2*
Etc.
`%<:0-%45 1
\kV ' 7%; \kV4D5*
Choptr 9. 1h Lvolutlon o Cod
4J8
O cours, you most llkly don`t wont oll your vorlobls to hov o rong btwn 0 ond J. But
rothr thon try to rmmbr how to odjust thos rongs ln th \kV closs ltsl, lt`s oslr to
pull th gntlc lnormotlon rom th LNA objct ond us Procsslng`s 9,$45 unctlon to
chong th rong. |or xompl, l you wont o slz vorlobl btwn J0 ond 72, you would soy.
|n othr coss, you wlll wont to dslgn o gnotyp thot ls on orroy o objcts. Consldr th
dslgn o o rockt wlth o srls o thrustr" nglns. You could dscrlb och thrustr wlth o
]`%028/ thot outllns lts dlrctlon ond rlotlv strngth.
1h phnotyp would b o Y80.%2 closs thot portlclpots ln o physlcs systm.
Whot`s grot obout thls tchnlqu o dlvldlng th gnotyp ond phnotyp lnto sporot
closss [\kV ond Y80.%2 or xomplj ls thot whn lt coms tlm to bulld oll o th cod, you`ll
notlc thot th LNA closs w dvlopd orllr rmolns lntoct. 1h only thlng thot chongs ls
th orroy`s doto typ [E-8,2, ]`%028/, tc.j ond th xprsslon o thot doto ln th phnotyp
closs.
|n th nxt sctlon, w`ll ollow thls ldo o blt urthr ond wolk through th ncssory stps or
on xompl thot lnvolvs movlng bodls ond on orroy o ]`%028/s os LNA.
Using the genes to set variables 9,!#$%%& ' &7,N?%7%#KBL*
9,!E8/0% ' &7,N?%7%#K)L*
#:F% ' &7,N?%7%#K>L*
#%$,/,2:87+%:?<2 ' &7,N?%7%#KHL*
Etc. @
#:F% ' 9,$4&7,N?%7%#K>LCBC)C)BCO>5*
0-,## \kV 1
The genotype is an array of PVectors. ]`%028/KL ?%7%#*
\kV4:72 7395 1
?%7%# ' 7%; E-8,2K739L*
E8/ 4:72 : ' B* : P ?%7%#N-%7?2<* :((5 1
A PVector pointing in a random direction ?%7%#K:L ' ]`%028/N/,7&89>\45*
And scaled randomly ?%7%#K:LN93-24/,7&894)B55*
@
@
0-,## Y80.%2 1
\kV &7,*
== %20N
1h Notur o Cod [v005j
4J9
W"#T MI*%I&;< S*.2(-D UE4.' Y*23('- W"#T MI*%I&;< S*.2(-D UE4.' Y*23('-
W plckd th rockt ldo or o spcllc roson. |n 2009, Jr 1horp [http.//blprnt.comj
rlosd o gntlc olgorlthms xompl on hls blog ntltld 5mort Rockts." Jr polnts out
thot NA5A uss volutlonory computlng tchnlqus to solv oll sorts o problms, rom
sotlllt ontnno dslgn to rockt lrlng pottrns. 1hls lnsplrd hlm to crot o |losh
dmonstrotlon o volvlng rockts. Hr ls o dscrlptlon o th scnorlo.
A populotlon o rockts lounchs rom th bottom o th scrn wlth th gool o hlttlng o
torgt ot th top o th scrn [wlth obstocls blocklng o strolght lln pothj.
Loch rockt ls qulppd wlth lv thrustrs
o vorlobl strngth ond dlrctlon. 1h
thrustrs don`t lr oll ot onc ond
contlnuously, rothr, thy lr on ot o tlm
ln o custom squnc.
|n thls sctlon, w`r golng to volv our
own slmpllld 5mort Rockts, lnsplrd by
Jr 1horp`s. Whn w gt to th nd o th
sctlon, w`ll lov lmplmntlng som o
Jr`s oddltlonol odvoncd oturs os on
xrcls.
Our rockts wlll hov only on thrustr, ond thls thrustr wlll b obl to lr ln ony dlrctlon
wlth ony strngth or vry rom o onlmotlon. 1hls lsn`t portlculorly rollstlc, but lt wlll
mok bulldlng out th romwork o llttl oslr. [W con olwoys mok th rockt ond lts
thrustrs mor odvoncd ond rollstlc lotr.j
Lt`s stort by toklng our boslc d8A%/ closs rom Choptr 2 xompls ond rnomlng lt Y80.%2.
Iiure p.:o
Iiure p.::
0-,## Y80.%2 1
Choptr 9. 1h Lvolutlon o Cod
420
slng th obov romwork, w con lmplmnt our smort rockt by soylng thot or vry rom
o onlmotlon, w coll ,$$-"b8/0%45 wlth o nw orc. 1h thrustr" opplls o slngl orc to
th rockt och tlm through &/,;45.
Consldrlng thls xompl, lt`s go through th thr kys to progrommlng our own custom
gntlc olgorlthm xompl os outllnd ln th prvlous sctlon.
f#U g;L 9*:(5&'/*1 8/V# &1- 7('&'/*1 )&'# f#U g;L 9*:(5&'/*1 8/V# &1- 7('&'/*1 )&'#
W con octuolly hold o on thls lrst ky or th momnt. Our strotgy wlll b to plck som
rosonobl numbrs [o populotlon o J00 rockts, mutotlon rot o Jj ond bulld out th
systm, ploylng wlth ths numbrs onc w hov our sktch up ond runnlng.
f#U g<L !"# +/'1#88 +(10'/*1 f#U g<L !"# +/'1#88 +(10'/*1
W stotd th gool o o rockt rochlng o torgt. |n othr words, th closr o rockt gts to
th torgt, th hlghr th ltnss. |ltnss ls lnvrsly proportlonol to dlstonc. th smollr th
dlstonc, th grotr th ltnss, th grotr th dlstonc, th smollr th ltnss.
Lt`s ossum w hov o ]`%028/ torgt.
1hls ls prhops th slmplst ltnss unctlon w could wrlt. By uslng on dlvldd by dlstonc,
lorg dlstoncs bcom smoll numbrs ond smoll dlstoncs bcom lorg.
A rocket has three vectors: location,
velocity, acceleration.
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
Accumulating forces into acceleration
(Newton's 2nd law)
A8:& ,$$-"b8/0%4]`%028/ E5 1
,00%-%/,2:87N,&&4E5*
@
Our simple physics model (Euler integration) A8:& 3$&,2%45 1
Velocity changes according to acceleration. A%-80:2"N,&&4,00%-%/,2:875*
Location changes according to velocity. -80,2:87N,&&4A%-80:2"5*
,00%-%/,2:87N93-24B5*
@
@
A8:& E:27%##45 1
How close did we get? E-8,2 & ' ]`%028/N&:#24-80,2:87C2,/?%25*
Fitness is inversely proportional to distance. E:27%## ' )=&*
@
1h Notur o Cod [v005j
42J
-/8'&10# -/8'&10# ; Z -/8'&10# ; Z -/8'&10#
300 J / 300 0.0033
J00 J / J00 0.0J
5 J / 5 0.2
J J / J J.0
0.J J / 0.J J0
And l w wontd to us our xponntlol trlck rom th prvlous sctlon, w could us on
dlvldd by dlstonc squord.
-/8'&10# -/8'&10# ; Z -/8'&10# ; Z -/8'&10#
W; Z -/8'&10#X W; Z -/8'&10#X
<<
300 J / 400 0.0025 0.00000625
J00 J / J00 0.0J 0.000J
5 J / 5 0.2 0.04
J J / J J.0 J.0
0.J J / 0.J J0 J00
1hr or svrol oddltlonol lmprovmnts w`ll wont to mok to th ltnss unctlon, but
thls slmpl on ls o good stort.
Ky #3. Gnotyp ond Phnotyp
W stotd thot och rockt hos o thrustr thot lrs ln o vorlobl dlrctlon wlth o vorlobl
mognltud ln och rom. And so w nd o ]`%028/ or och rom o onlmotlon. Our
gnotyp, th doto rqulrd to ncod th rockt`s bhovlor, ls thror on orroy o
]`%028/s.
A8:& E:27%##45 1
E-8,2 & ' ]`%028/N&:#24-80,2:87C2,/?%25*
Squaring 1 divided by distance E:27%## ' $8;4)=&C>5*
@
Choptr 9. 1h Lvolutlon o Cod
422
1h hoppy nws hr ls thot w don`t rolly hov to do onythlng ls to th \kV closs. All o
th unctlonollty w dvlopd or th typlng monky [crossovr ond mutotlonj opplls hr.
1h on dlrnc w do hov to consldr ls how w lnltlollz th orroy o gns. Wlth th
typlng monky, w hod on orroy o choroctrs ond plckd o rondom choroctr or och
lmnt o th orroy. Hr w`ll do xoctly th som thlng ond lnltlollz o LNA squnc os on
orroy o rondom ]`%028/s. Now, your lnstlnct ln crotlng o rondom ]`%028/ mlght b os
ollows.
1hls ls prctly ln ond wlll llkly do th
trlck. Howvr, l w wr to drow vry
slngl posslbl vctor w mlght plck, th
rsult would lll o squor [s |lgur 9.J2j. |n
thls cos, lt probobly dosn`t mottr, but
thr ls o sllght blos to dlogonols hr glvn
thot o ]`%028/ rom th cntr o o squor
to o cornr ls longr thon o purly vrtlcol or
horlzontol on.
Whot would b bttr hr ls to plck o
rondom ongl ond mok o ]`%028/ o lngth
on rom thot ongl, glvlng us o clrcl [s
|lgur 9.J3j. 1hls could b oslly don wlth
o qulck polor to Cortslon convrslon [s
pog JJ2j, but o qulckr poth to th rsult ls
just to us ]`%028/'s /,7&89>\45.
A ]`%028/ o lngth on ls octuolly golng to b qult o lorg orc. Rmmbr, orcs or
opplld to occlrotlon, whlch occumulots lnto vloclty thlrty tlms pr scond. 5o, or thls
xompl, w con olso odd on mor vorlobl to th \kV closs. o moxlmum orc thot scols oll
th ]`%028/s. 1hls wlll control th thrustr powr.
0-,## \kV 1
]`%028/KL ?%7%#*
]`%028/ A ' 7%; ]`%028/4/,7&8946)C)5C/,7&8946)C)55*
Iiure p.:z
Iiure p.:
E8/ 4:72 : ' B* : P ?%7%#N-%7?2<* :((5 1
Making a PVector from a random angle ?%7%#K:L ' ]`%028/N/,7&89>\45*
@
1h Notur o Cod [v005j
423
Notlc olso thot w crotd on orroy o ]`%028/s wlth lngth lltlm. W nd o ]`%028/
or och rom o th rockt`s ll, ond th obov ossums th xlstnc o o globol vorlobl
lltlm thot stors th totol numbr o roms ln och gnrotlon`s ll cycl.
1h xprsslon o thls orroy o ]`%028/s, th phnotyp, ls o Y80.%2 closs modld on our
boslc ]`%028/ ond orcs xompls rom Choptr 2. All w nd to do ls odd on lnstonc o
o \kV objct to th closs. 1h ltnss vorlobl wlll olso llv hr. Only th Y80.%2 objct
knows how to comput lts dlstonc to th torgt, ond thror th ltnss unctlon wlll llv
hr ln th phnotyp os wll.
Whot or w uslng th LNA or? W or morchlng through th orroy o ]`%028/s ond
opplylng thm on ot o tlm os o orc to th rockt. 1o do thls, w`ll olso hov to odd on
lntgr thot octs os o countr to wolk through th orroy.
0-,## \kV 1
The genetic sequence is an array of
PVectors.
]`%028/KL ?%7%#*
How strong can the thrusters be? E-8,2 9,!E8/0% ' BN)*
\kV45 1
We need a PVector for every frame of the
rocket's life.
?%7%# ' 7%; ]`%028/K-:E%2:9%L*
E8/ 4:72 : ' B* : P ?%7%#N-%7?2<* :((5 1
?%7%#K:L ' ]`%028/N/,7&89>\45*
Scaling the PVectors randomly, but no
stronger than maximum force
?%7%#K:LN93-24/,7&894BC 9,!E8/0%55*
@
@
0-,## Y80.%2 1
A Rocket has DNA. \kV &7,*
A Rocket has fitness. E-8,2 E:27%##*
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
:72 ?%7%M8372%/ ' B*
A8:& /3745 1
Apply a force from the genes array. ,$$-"b8/0%4&7,N?%7%#K?%7%M8372%/L5*
Go to the next force in the genes array. ?%7%M8372%/((*
Choptr 9. 1h Lvolutlon o Cod
424
Update the Rocket's physics. 3$&,2%45*
@
W"## UE4.' Y*23('-D 5:''&;< C' !%% @*<(',(. W"## UE4.' Y*23('-D 5:''&;< C' !%% @*<(',(.
W now hov our \kV closs [gnotypj ond our Y80.%2 closs [phnotypj. 1h lost plc o
th puzzl ls o ]8$3-,2:87 closs, whlch monogs on orroy o rockts ond hos th unctlonollty
or slctlon ond rproductlon. Agoln, th hoppy nws hr ls thot w borly hov to chong
onythlng rom th 5hokspor monky xompl. 1h procss or bulldlng o motlng pool ond
gnrotlng o nw orroy o chlld rockts ls xoctly th som os whot w dld wlth our populotlon
o strlngs.
1hr ls on olrly slgnllcont chong, howvr. Wlth typlng monkys, o rondom phros wos
voluotd os soon os lt wos crotd. 1h strlng o choroctrs hod no llspon, lt xlstd purly
or th purpos o colculotlng lts ltnss ond thn w movd on. 1h rockts, howvr, nd
to llv or o prlod o tlm bor thy con b voluotd, thy nd to b glvn o chonc to
mok thlr ottmpt ot rochlng th torgt. 1hror, w nd to odd on mor unctlon to th
]8$3-,2:87 closs thot runs th physlcs slmulotlon ltsl. 1hls ls ldntlcol to whot w dld ln th
/3745 unctlon o o portlcl systmupdot oll th portlcl locotlons ond drow thm.
|lnolly, w`r rody or #%23$45 ond &/,;45. Hr ln th moln tob, our prlmory rsponslblllty ls
to lmplmnt th stps o th gntlc olgorlthm ln th opproprlot ordr by colllng th
unctlons ln th ]8$3-,2:87 closs.
0-,## ]8$3-,2:87 1
Population has variables to keep track of
mutation rate, current population array,
mating pool, and number of generations.
E-8,2 932,2:87Y,2%*
Y80.%2KL $8$3-,2:87*
V//,"l:#2PY80.%2^ 9,2:7?]88-*
:72 ?%7%/,2:87#*
These functions haven't changed, so no
need to go through the code again.
A8:& E:27%##45 1@
A8:& #%-%02:8745 1@
A8:& /%$/8&302:8745 1@
A8:& -:A% 45 1
E8/ 4:72 : ' B* : P $8$3-,2:87N-%7?2<* :((5 1
The run function takes care of the forces,
updating the rocket's location, and
displaying it.
$8$3-,2:87K:LN/3745*
@
@
1h Notur o Cod [v005j
425
Howvr, unllk th 5hokspor xompl, w don`t wont to do thls vry rom. Rothr,
our stps work os ollows.
J. Crot o populotlon o rockts
2. Lt th rockts llv or N roms
3. Lvolv th nxt gnrotlon
5lctlon
Rproductlon
4. Rturn to 5tp #2
IJ&7:5# CK<L O/7:5# O7&)' H*03#'8
$8$3-,2:87NE:27%##45*
$8$3-,2:87N#%-%02:8745*
$8$3-,2:87N/%$/8&302:8745*
How many frames does a generation live
for?
:72 -:E%2:9%*
What frame are we on? :72 -:E%M8372%/*
The population ]8$3-,2:87 $8$3-,2:87*
A8:& #%23$45 1
#:F%4GDBC DXB5*
-:E%2:9% ' JBB*
-:E%M8372%/ ' B*
E-8,2 932,2:87Y,2% ' BNB)*
Choptr 9. 1h Lvolutlon o Cod
426
1h obov xompl works, but lt lsn`t portlculorly lntrstlng. Atr oll, th rockts slmply
volv to hovlng LNA wlth o bunch o vctors thot polnt strolght upwords. |n th nxt
xompl, w`r golng to tolk through two suggstd lmprovmnts or th xompl ond
provld cod snlppts thot lmplmnt ths lmprovmnts.
|mprovmnt #J. Obstocls
Addlng obstocls thot th rockts must ovold wlll mok th systm mor complx ond
dmonstrot th powr o th volutlonory olgorlthm mor ctlvly. W con mok
rctongulor, stotlonory obstocls olrly oslly by crotlng o closs thot stors o locotlon ond
dlmnslons.
Step 1: Create the population. Here is where
we could play with the mutation rate and
population size.
$8$3-,2:87 ' 7%; ]8$3-,2:874932,2:87Y,2%C JB5*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
The revised genetic algorithm :E 4-:E%M8372%/ P -:E%2:9%5 1
Step 2: The rockets live their life until
lifeCounter reaches lifetime.
$8$3-,2:87N-:A%45*
-:E%M8372%/((*
@ %-#% 1
When lifetime is reached, reset lifeCounter
and evolve the next generation (Steps 3 and
4, selection and reproduction).
-:E%M8372%/ ' B*
$8$3-,2:87NE:27%##45*
$8$3-,2:87N#%-%02:8745*
$8$3-,2:87N/%$/8&302:8745*
@
@
1h Notur o Cod [v005j
427
IJ&7:5# CK=L O7&)' H*03#'8
W con olso wrlt o 0872,:7#45 unctlon thot wlll /%23/7 2/3% or /%23/7 E,-#% to
dtrmln l o rockt hos hlt th obstocl.
Assumlng w mok on V//,"l:#2 o obstocls, w con thn hov och rockt chck to s
l lt hos collldd wlth on obstocl ond st o I88-%,7 log to b tru l lt dos, oddlng o
unctlon to th rockt closs.
| th rockt hlts on obstocl, w choos to stop lt rom updotlng lts locotlon.
And w olso hov on opportunlty to odjust th rockt`s ltnss. W consldr lt to b prtty
trrlbl l th rockt hlts on obstocl, ond so lts ltnss should b grotly rducd.
0-,## UI#2,0-% 1
An obstacle is a location (top left corner of
rectangle) with a width and height.
]`%028/ -80,2:87*
E-8,2 ;C<*
I88-%,7 0872,:7#4]`%028/ A5 1
:E 4AN! ^ -80,2:87N! mm AN! P -80,2:87N! ( ; mm AN" ^ -80,2:87N" mm AN" P
-80,2:87N" ( <5 1
/%23/7 2/3%*
@ %-#% 1
/%23/7 E,-#%*
@
@
This new function lives in the rocket class
and checks if a rocket has hit an obstacle.
A8:& 8I#2,0-%#45 1
E8/ 4UI#2,0-% 8I# q 8I#2,0-%#5 1
:E 48I#N0872,:7#4-80,2:8755 1
#28$$%& ' 2/3%*
@
@
@
A8:& /3745 1
Only run the rocket if it doesn't hit an
obstacle.
29 *m./800$1+ O
,$$-"b8/0%4&7,N?%7%#K?%7%M8372%/L5*
?%7%M8372%/ ' 4?%7%M8372%/ ( )5 x &7,N?%7%#N-%7?2<*
3$&,2%45*
86./&:'$.*+,
@
@
Choptr 9. 1h Lvolutlon o Cod
428
|mprovmnt #2. Lvolv rochlng th torgt ostr
| you look closly ot our lrst 5mort Rockts xompl, you`ll notlc thot th rockts or not
rwordd or gttlng to th torgt ostr. 1h only vorlobl ln thlr ltnss colculotlon ls th
dlstonc to th torgt ot th nd o th gnrotlon`s ll. |n oct, ln th vnt thot th rockts
gt vry clos to th torgt but ovrshoot lt ond ly post, thy moy octuolly b pnollzd or
gttlng to th torgt ostr. 5low ond stody wlns th roc ln thls cos.
W could lmprov th olgorlthm to optlmlz or spd o numbr o woys. |lrst, lnstod o
uslng th dlstonc to th torgt ot th nd o th gnrotlon, w could us th dlstonc thot ls
th closst to th torgt ot ony polnt durlng th rockt`s ll. W would coll thls th rockt`s
rcord" dlstonc. [All o th cod snlppts ln thls sctlon llv lnsld th Y80.%2 closs.j
|n oddltlon, o rockt should b rwordd occordlng to how qulckly lt rochs th torgt. 1h
ostr lt rochs th torgt, th hlghr th ltnss. 1h slowr, th lowr. 1o occompllsh thls,
w con lncrmnt o countr vry cycl o th rockt`s ll untll lt rochs th torgt. At th
nd o lts ll, th countr wlll quol th omount o tlm th rockt took to roch thot torgt.
|ltnss ls olso lnvrsly proportlonol to E:7:#<n:9%, ond so w con lmprov our ltnss
unctlon os ollows.
A8:& E:27%##45 1
E-8,2 & ' &:#24-80,2:87N!C -80,2:87N"C 2,/?%2N-80,2:87N!C 2,/?%2N-80,2:87N"5*
E:27%## ' $8;4)=&C >5*
29 *./800$1+ 92/#$.. F" ?-D,
@
A8:& 0<%0.n,/?%245 1
E-8,2 & ' &:#24-80,2:87N!C -80,2:87N"C 2,/?%2N-80,2:87N!C 2,/?%2N-80,2:87N"5*
Every frame, we check its distance and see
if it's closer than the "record distance. f it is,
we have a new record.
:E 4& P /%08/&\:#25 /%08/&\:#2 ' &*
f the object reaches the target, set a
boolean flag to true.
:E 42,/?%2N0872,:7#4-80,2:8755 1
<:2n,/?%2 ' 2/3%*
@ %-#% :E 4S<:2n,/?%25 1
As long as we haven't yet reached the
target, keep incrementing the counter.
E:7:#<n:9%((*
@
@
A8:& E:27%##45 1
Finish time and record distance! E:27%## ' 4)=4E:7:#<n:9%Q/%08/&\:#255*
1h Notur o Cod [v005j
429
1hs lmprovmnts or both lncorporotd lnto th cod or Lxompl 9.3. 5mort Rockts.
On o th mor omous lmplmntotlons o gntlc olgorlthms ln computr grophlcs ls Korl
5lms`s Lvolvd Vlrtuol Croturs." |n 5lms`s work, o populotlon o dlgltol croturs [ln o
slmulotd physlcs nvlronmntj ls voluotd or th croturs' oblllty to prorm tosks, such
os swlmmlng, runnlng, jumplng, ollowlng, ond comptlng or o grn cub.
Make it exponential. E:27%## ' $8;4E:27%##C >5*
Fitness goes way down if you hit an
obstacle.
:E 4#28$$%&5 E:27%## Q' BN)*
You are rewarded for reaching the target. :E 4<:2n,/?%25 E:27%## Q' >*
@
Crot o mor complx obstocl cours. As you mok lt mor dllcult or th rockts
to roch th torgt, do you nd to lmprov othr ospcts o th GAor xompl,
th ltnss unctlon?
MO(.2&-( W"N MO(.2&-( W"N
|mplmnt th rockt lrlng pottrn o Jr 1horp`s 5mort Rockts. Loch rockt only
gts lv thrustrs [o ony dlrctlon ond strngthj thot ollow o lrlng squnc [o
orbltrory lngthj. Jr`s slmulotlon [http.//www.blprnt.com/smortrockts/j olso glvs th
rockts o lnlt omount o ul.
MO(.2&-( W"W MO(.2&-( W"W
Vlsuollz th rockts dlrntly. Con you drow o lln or th shortst poth to th
torgt? Con you odd portlcl systms thot oct os smok ln th dlrctlon o th rockt
thrustrs?
MO(.2&-( W"#T MO(.2&-( W"#T
Anothr woy to ochlv o slmllor rsult ls to volv o low lld. Con you mok th
gnotyp o o rockt o low lld o ]`%028/s?
MO(.2&-( W"## MO(.2&-( W"##
Choptr 9. 1h Lvolutlon o Cod
430
On o th lnnovotlons ln 5lms`s work ls o nod-bosd gnotyp. |n othr words, th
crotur`s LNA ls not o llnor llst o ]`%028/s or numbrs, but o mop o nods. [|or on
xompl o thls, tok o look ot Lxrcls 5.J5 [s pog 256j, toxlcllbs' |orc Llrctd Groph.j
1h phnotyp ls th crotur`s dslgn ltsl, o ntwork o llmbs connctd wlth muscls.
slng toxlcllbs or Box2L os th physlcs
modl, con you crot o slmpllld 2L
vrslon o 5lms`s croturs? |or o
lngthlr dscrlptlon o 5lms`s
tchnlqus, | suggst you wotch th
vldo ond rod 5lms`s popr Vlrtuol
Croturs [http.//www.korlslms.com/
volvd-vlrtuol-croturs.htmlj. |n
oddltlon, you con lnd o slmllor xompl
thot uss Box2L to volv o cor".
BoxCor2L [http.//boxcor2d.com/j.
MO(.2&-( W"#0 MO(.2&-( W"#0
W"#0 C;'(.42'&I( U(%(2'&*; W"#0 C;'(.42'&I( U(%(2'&*;
|n oddltlon to Lvolvd Vlrtuol Croturs, 5lms ls olso wll known or hls musum lnstollotlon
Go|opogos. Orlglnolly lnstolld ln th |ntrcommunlcotlon Cntr ln 1okyo ln J997, th
lnstollotlon conslsts o twlv monltors dlsploylng computr-gnrotd lmogs. 1hs lmogs
volv ovr tlm, ollowlng th gntlc olgorlthm stps o slctlon ond rproductlon. 1h
lnnovotlon hr ls not th us o th gntlc olgorlthm ltsl, but rothr th strotgy bhlnd
th ltnss unctlon. |n ront o och monltor ls o snsor on th loor thot con dtct th
prsnc o o usr vlwlng th scrn. 1h ltnss o on lmog ls tld to th lngth o tlm
thot vlwrs look ot th lmog. 1hls ls known os |ntetoct|ve se|ect|on, o gntlc olgorlthm wlth
ltnss volus osslgnd by usrs.
1hlnk o oll th rotlng systms you`v vr usd. Could you volv th prct movl by
scorlng oll llms occordlng to your Ntllx rotlngs? 1h prct slngr occordlng to Amrlcon
|dol votlng?
1h Notur o Cod [v005j
43J
1o lllustrot thls tchnlqu, w`r golng to
bulld o populotlon o slmpl ocs. Loch
oc wlll hov o st o proprtls. hod
slz, hod color, y locotlon, y slz,
mouth color, mouth locotlon, mouth wldth,
ond mouth hlght.
1h oc`s LNA [gnotypj ls on orroy o
lootlng polnt numbrs btwn 0 ond J,
wlth o slngl volu or och proprty.
1h phnotyp ls o b,0% closs thot lncluds on lnstonc o o \kV objct.
Whn lt coms tlm to drow th oc on scrn, w con us Procsslng`s 9,$45 unctlon to
convrt ony gn volu to th opproprlot rong or plxl dlmnslons or color volus. [|n
thls cos, w or olso uslng 08-8/d8&%45 to st th RGB rongs btwn 0 ond J.j
Iiure p.:(
0-,## \kV 1
E-8,2KL ?%7%#*
We need 20 numbers to draw the face. :72 -%7 ' >B*
\kV45 1
?%7%# ' 7%; E-8,2K-%7L*
E8/ 4:72 : ' B* : P ?%7%#N-%7?2<* :((5 1
Each gene is a random float between 0
and 1.
?%7%#K:L ' /,7&894BC)5*
@
@
0-,## b,0% 1
\kV &7,*
E-8,2 E:27%##*
A8:& &:#$-,"45 1
Using map() to convert the genes to a
range for drawing the face.
E-8,2 / ' 9,$4&7,N?%7%#KBLCBC)CBCOB5*
08-8/ 0 ' 08-8/4&7,N?%7%#K)LC&7,N?%7%#K>LC&7,N?%7%#KHL5*
E-8,2 %"%a" ' 9,$4&7,N?%7%#KDLCBC)CBCJ5*
E-8,2 %"%a! ' 9,$4&7,N?%7%#KJLCBC)CBC)B5*
E-8,2 %"%a#:F% ' 9,$4&7,N?%7%#KJLCBC)CBC)B5*
08-8/ %"%08-8/ ' 08-8/4&7,N?%7%#KDLC&7,N?%7%#KJLC&7,N?%7%#KGL5*
08-8/ 9832<M8-8/ ' 08-8/4&7,N?%7%#KOLC&7,N?%7%#KXLC&7,N?%7%#KpL5*
E-8,2 9832<a" ' 9,$4&7,N?%7%#KJLCBC)CBC>J5*
E-8,2 9832<a! ' 9,$4&7,N?%7%#KJLCBC)C6>JC>J5*
E-8,2 9832<; ' 9,$4&7,N?%7%#KJLCBC)CBCJB5*
E-8,2 9832<< ' 9,$4&7,N?%7%#KJLCBC)CBC)B5*
Choptr 9. 1h Lvolutlon o Cod
432
5o or, w`r not rolly dolng onythlng nw. 1hls ls whot w`v don ln vry GA xompl so
or. Whot`s nw ls thot w or not golng to wrlt o E:27%##45 unctlon ln whlch th scor ls
computd bosd on o moth ormulo. |nstod, w or golng to osk th usr to osslgn th
ltnss.
Now, how bst to osk o usr to osslgn ltnss ls rolly mor o on lntroctlon dslgn problm,
ond lt lsn`t rolly wlthln th scop o thls book. 5o w`r not golng to lounch lnto on loborot
dlscusslon o how to progrom slldrs or bulld your own hordwor dlols or bulld o Wb opp or
usrs to submlt onlln scors. How you choos to ocqulr ltnss scors ls rolly up to you
ond th portlculor oppllcotlon you or dvloplng.
|or thls slmpl dmonstrotlon, w`ll lncros ltnss whnvr o usr rolls th mous ovr o
oc. 1h nxt gnrotlon ls crotd whn th usr prsss o button wlth on volv nxt
gnrotlon" lobl.
Lt`s look ot how th stps o th gntlc olgorlthm or opplld ln th moln tob, notlng how
ltnss ls osslgnd occordlng to mous lntroctlon ond th nxt gnrotlon ls crotd on o
button prss. 1h rst o th cod or chcklng mous locotlons, button lntroctlons, tc. con
b ound ln th occomponylng xompl cod.
IJ&7:5# CK>L F1'#)&0'/N# 8#5#0'/*1
]8$3-,2:87 $8$3-,2:87*
W32287 I32287*
A8:& #%23$45 1
#:F%4OXBC>BB5*
E-8,2 932,2:87Y,2% ' BNBJ*
$8$3-,2:87 ' 7%; ]8$3-,2:874932,2:87Y,2%C)B5*
I32287 ' 7%; W322874)JC)JBC)GBC>BC T%A8-A% 7%; ?%7%/,2:87T5*
@
A8:& &/,;45 1
$8$3-,2:87N&:#$-,"45*
1h Notur o Cod [v005j
433
1hls xompl, lt should b notd, ls rolly just o dmonstrotlon o th ldo o lntroctlv
slctlon ond dos not ochlv o portlculorly monlngul rsult. |or on, w dldn`t tok
much cor ln th vlsuol dslgn o th ocs, thy or just o w slmpl shops wlth slzs ond
colors. 5lms, or xompl, usd mor loborot mothmotlcol unctlons os hls lmogs`
gnotyp. You mlght olso consldr o vctor-bosd opprooch, ln whlch o dslgn`s gnotyp
ls o st o polnts ond/or poths.
1h mor slgnllcont problm hr, howvr, ls on o tlm. |n th noturol world, volutlon
occurs ovr mllllons o yors. |n th computr slmulotlon world o our prvlous xompls,
w wr obl to volv bhovlors rlotlvly qulckly bcous w wr produclng nw
gnrotlons olgorlthmlcolly. |n th 5hokspor monky xompl, o nw gnrotlon wos
born ln och rom o onlmotlon [opproxlmotly slxty pr scondj. 5lnc th ltnss volus
wr computd occordlng to o moth ormulo, w could olso hov hod orbltrorlly lorg
populotlons thot lncrosd th spd o volutlon. |n th cos o lntroctlv slctlon,
howvr, w hov to slt ond wolt or o usr to rot och ond vry mmbr o th
populotlon bor w con gt to th nxt gnrotlon. A lorg populotlon would b
unrosonobly tdlous to dol wlthnot to mntlon, how mony gnrotlons could you stond
to slt through?
1hr or crtolnly clvr solutlons oround thls. 5lms`s Golopogos xhlblt concold th
rotlng procss rom th usrs, os lt occurrd through th normol bhovlor o looklng ot
ortwork ln o musum sttlng. Bulldlng o Wb oppllcotlon thot would ollow mony usrs to rot
o populotlon ln o dlstrlbutd oshlon ls olso o good strotgy or ochlvlng mony rotlngs or
lorg populotlons qulckly.
|n th nd, th ky to o succssul lntroctlv slctlon systm bolls down to th som kys
w prvlously stobllshd. Whot ls th gnotyp ond phnotyp? And how do you colculot
ltnss, whlch ln thls cos w con rvls to soy. Whot ls your strotgy or osslgnlng ltnss
occordlng to usr lntroctlon?"
The mouse location is passed to the
population, which will score each face
according to rollover time.
0804'&/28#-)8''8L$)*584.$VJ584.$W+,
I32287N&:#$-,"45*
@
A8:& 983#%]/%##%&45 1
When a button is pressed, the new
generation is created via selection and
reproduction.
29 *64//8#-:'2:($1*584.$VJ584.$W++ O
$8$3-,2:87N#%-%02:8745*
$8$3-,2:87N/%$/8&302:8745*
@
@
Choptr 9. 1h Lvolutlon o Cod
434
Bulld your own lntroctlv slctlon projct. |n oddltlon to o vlsuol dslgn, consldr
volvlng soundsor xompl, o short squnc o tons. Con you dvls o strotgy,
such os o Wb oppllcotlon or physlcol snsor systm, to ocqulr rotlngs rom mony
usrs ovr tlm?
MO(.2&-( W"#> MO(.2&-( W"#>
W"#= M2*-/-'(E U&E:%4'&*; W"#= M2*-/-'(E U&E:%4'&*;
You moy hov notlcd somthlng o blt odd obout vry slngl volutlonory systm w`v bullt
so or ln thls choptr. Atr oll, ln th rol world, o populotlon o bobls lsn`t born oll ot th
som tlm. 1hos bobls don`t thn grow up ond oll rproduc ot xoctly th som tlm, thn
lnstontly dl to lov th populotlon slz prctly stobl. 1hot would b rldlculous. Not to
mntlon th oct thot thr ls crtolnly no on runnlng oround th orst wlth o colculotor
crunchlng numbrs ond osslgnlng ltnss volus to oll th croturs.
|n th rol world, w don`t rolly hov survlvol o th lttst", w hov survlvol o th
survlvors." 1hlngs thot hoppn to llv longr, or whotvr roson, hov o grotr chonc o
rproduclng. Bobls or born, thy llv or o whll, moyb thy thmslvs hov bobls,
moyb thy don`t, ond thn thy dl.
You won`t ncssorlly lnd slmulotlons o rol-world" volutlon ln ortllclol lntlllgnc
txtbooks. Gntlc olgorlthms or gnrolly usd ln th mor ormol monnr w outllnd ln
thls choptr. Howvr, slnc w or rodlng thls book to dvlop slmulotlons o noturol
systms, lt`s worth looklng ot som woys ln whlch w mlght us o gntlc olgorlthm to bulld
somthlng thot rsmbls o llvlng cosystm", much llk th on w`v dscrlbd ln th
xrclss ot th nd o och choptr.
Lt`s bgln by dvloplng o vry slmpl scnorlo. W`ll crot o crotur colld o "bloop," o
clrcl thot movs obout th scrn occordlng to Prlln nols. 1h crotur wlll hov o rodlus
ond o moxlmum spd. 1h blggr lt ls, th slowr lt movs, th smollr, th ostr.
0-,## W-88$ 1
A location ]`%028/ -80,2:87*
Variables for size and speed E-8,2 /*
E-8,2 9,!#$%%&*
1h Notur o Cod [v005j
435
1h obov ls mlsslng o w dtolls [such os lnltlollzlng th vorlobls ln th constructorj, but
you gt th ldo.
|or thls xompl, w`ll wont to stor th populotlon o bloops ln on V//,"l:#2, rothr thon
on orroy, os w xpct th populotlon to grow ond shrlnk occordlng to how otn bloops dl
or or born. W con stor thls V//,"l:#2 ln o closs colld +8/-&, whlch wlll monog oll th
lmnts o th bloops` world.
5o or, whot w hov ls just o rhoshlng o our portlcl systm xompl rom Choptr 5. W
hov on ntlty [W-88$j thot movs oround th wlndow ond o closs [+8/-&j thot monogs o
vorlobl quontlty o ths ntltls. 1o turn thls lnto o systm thot volvs, w nd to odd
two oddltlonol oturs to our world.
- T'!!A) 8/$6 T'!!A) 8/$6
- T'!!A) (1$ "!1.6 T'!!A) (1$ "!1.6
Some variables for Perlin noise
calculations
E-8,2 !8EEC "8EE*
A8:& 3$&,2%45 1
E-8,2 A! ' 9,$478:#%4!8EE5CBC)C69,!#$%%&C9,!#$%%&5*
E-8,2 A" ' 9,$478:#%4"8EE5CBC)C69,!#$%%&C9,!#$%%&5*
A little Perlin noise algorithm to calculate a
velocity
]`%028/ A%-80:2" ' 7%; ]`%028/4A!CA"5*
!8EE (' BNB)*
"8EE (' BNB)*
The bloop moves. -80,2:87N,&&4A%-80:2"5*
@
A bloop is a circle. A8:& &:#$-,"45 1
%--:$#%4-80,2:87N!C -80,2:87N"C /C /5*
@
@
0-,## +8/-& 1
A list of bloops V//,"l:#2PW-88$^ I-88$#*
+8/-&4:72 7395 1
I-88$# ' 7%; V//,"l:#2PW-88$^45*
E8/ 4:72 : ' B* : P 739* :((5 1
Making an initial population of bloops I-88$#N,&&47%; W-88$455*
@
@
Choptr 9. 1h Lvolutlon o Cod
436
Bloops dylng ls our rplocmnt or o ltnss unctlon, th procss o slctlon." | o bloop
dls, lt connot b slctd to b o pornt, bcous lt slmply no longr xlsts! On woy w con
bulld o mchonlsm to nsur bloop doths ln our world ls by oddlng o <%,-2< vorlobl to th
W-88$ closs.
|n och rom o onlmotlon, o bloop loss som holth.
| holth drops blow 0, th bloop dls.
1hls ls o good lrst stp, but w hovn`t rolly ochlvd onythlng. Atr oll, l oll bloops stort
wlth J00 holth polnts ond los J polnt pr rom, thn oll bloops wlll llv or th xoct som
omount o tlm ond dl togthr. | vry slngl bloop llvs th som omount o tlm, thy oll
hov quol choncs o rproduclng ond thror nothlng wlll volv.
1hr or mony woys w could ochlv vorlobl llspons wlth o mor sophlstlcotd world. |or
xompl, w could lntroduc prdotors thot ot bloops. Prhops th ostr bloops would b
obl to scop blng otn mor oslly, ond thror our world would volv to hov ostr
ond ostr bloops. Anothr optlon would b to lntroduc ood. Whn o bloop ots ood, lt
lncross lts holth polnts, ond thror xtnds lts ll.
Lt`s ossum w hov on V//,"l:#2 o ]`%028/ locotlons or ood, nomd ood." W could
tst och bloop`s proxlmlty to och ood locotlon. | th bloop ls clos nough, lt ots th ood
[whlch ls thn rmovd rom th worldj ond lncross lts holth.
0-,## W-88$ 1
A bloop is born with 100 health points. E-8,2 <%,-2< ' )BB*
A8:& 3$&,2%45 1
All that other stuff for movement
Death is always looming! <%,-2< 6' )*
@
We add a function to the Bloop class to test
if the bloop is alive or dead.
I88-%,7 &%,&45 1
:E 4<%,-2< P BNB5 1
/%23/7 2/3%*
@ %-#% 1
/%23/7 E,-#%*
@
@
A8:& %,245 1
E8/ 4:72 : ' E88&N#:F%456)* : ^' B* :665 1
]`%028/ E88&l80,2:87 ' E88&N?%24:5*
E-8,2 & ' ]`%028/N&:#24-80,2:87C E88&l80,2:875*
1h Notur o Cod [v005j
437
Now w hov o scnorlo ln whlch bloops thot ot mor ood llv longr ond hov o grotr
llkllhood o rproduclng. 1hror, w xpct thot our systm would volv bloops wlth
on optlmol oblllty to lnd ond ot ood.
Now thot w hov bullt our world, lt`s tlm to odd th componnts rqulrd or volutlon.
|lrst w should stobllsh our gnotyp ond phnotyp.
s the Bloop close to the food? :E 4& P /=>5 1
f so, it gets 100 more health points. <%,-2< (' )BB*
The food is no longer available for other
Bloops.
E88&N/%98A%4:5*
@
@
@
e(;*'/Q( 4;9 5,(;*'/Q( e(;*'/Q( 4;9 5,(;*'/Q(
1h oblllty or o bloop to lnd ood ls tld to two vorloblsslz ond spd. Blggr bloops
wlll lnd ood mor oslly slmply bcous thlr slz wlll ollow thm to lntrsct wlth ood
locotlons mor otn. And ostr bloops wlll lnd mor ood bcous thy con covr mor
ground ln o shortr prlod o tlm.
5lnc slz ond spd or lnvrsly rlotd
[lorg bloops or slow, smoll bloops or
ostj, w only nd o gnotyp wlth o
slngl numbr.
Iiure p.:
0-,## \kV 1
E-8,2KL ?%7%#*
\kV45 1
Choptr 9. 1h Lvolutlon o Cod
438
1h phnotyp thn ls th bloop ltsl, whos slz ond spd ls osslgnd by oddlng on
lnstonc o o \kV objct to th W-88$ closs.
Notlc thot wlth 9,!#$%%&, th rong ls moppd to btwn J5 ond 0, monlng o bloop wlth o
gn volu o 0 movs ot o spd o J5 ond o bloop wlth o gn volu o J dosn`t mov ot oll
[spd o 0j.
t may seem absurd to use an array when all
we have is a single value, but we stick with
an array in case we want to make more
sophisticated bloops later.
?%7%# ' 7%; E-8,2K)L*
E8/ 4:72 : ' B* : P ?%7%#N-%7?2<* :((5 1
?%7%#K:L ' /,7&894BC)5*
@
@
0-,## W-88$ 1
]`%028/ -80,2:87*
E-8,2 <%,-2<*
A bloop now has DNA. \kV &7,*
E-8,2 /*
E-8,2 9,!#$%%&*
W-88$4\kV &7,a5 1
-80,2:87 ' 7%; ]`%028/4;:&2<=>C<%:?<2=>5*
<%,-2< ' >BB*
&7, ' &7,a*
maxspeed and r (radius) are mapped to
values according to the DNA.
9,!#$%%& ' 9,$4&7,N?%7%#KBLC BC )C )JC B5*
/ ' 9,$4&7,N?%7%#KBLC BC )C BC JB5*
@
U(%(2'&*; 4;9 Y(Q.*9:2'&*; U(%(2'&*; 4;9 Y(Q.*9:2'&*;
Now thot w hov th gnotyp ond phnotyp, w nd to mov on to dvlslng o mons or
bloops to b slctd os pornts. W stotd bor thot th longr o bloop llvs, th mor
choncs lt hos to rproduc. 1h lngth o ll ls th bloop`s ltnss.
On optlon would b to soy thot whnvr two bloops com lnto contoct wlth och othr, thy
mok o nw bloop. 1h longr o bloop llvs, th mor llkly lt ls to com lnto contoct wlth
onothr bloop. [1hls would olso oct th volutlonory outcom glvn thot, ln oddltlon to
otlng ood, thlr oblllty to lnd othr bloops ls o octor ln th llkllhood o hovlng o boby.j
A slmplr optlon would b to hov osxuol" rproductlon, monlng o bloop dos not rqulr
o portnr. |t con, ot ony momnt, mok o clon o ltsl, onothr bloop wlth th som gntlc
mokup. | w stot thls slctlon olgorlthm os ollows.
D& (.@ 2/0$. -!-$.&I ( "'!!A +() ( 5h %+(.%$ !; 1$A1!8:%/.26 D& (.@ 2/0$. -!-$.&I ( "'!!A +() ( 5h %+(.%$ !; 1$A1!8:%/.26
1h Notur o Cod [v005j
439
.thn th longr o bloop llvs, th mor llkly lt wlll mok ot lost on chlld. 1hls ls
qulvolnt to soylng th mor tlms you ploy th lottry, th grotr th llkllhood you`ll wln
[though |`m sorry to soy your choncs o thot or stlll ssntlolly zroj.
1o lmplmnt thls slctlon olgorlthm, w con wrlt o unctlon ln th W-88$ closs thot plcks
o rondom numbr vry rom. | th numbr ls lss thon 0.0J [Jj, o nw bloop ls born.
How dos o bloop rproduc? |n our prvlous xompls, th rproductlon procss lnvolvd
colllng th 0/8##8A%/45 unctlon ln th \kV closs ond moklng o nw objct rom th nwly
mod LNA. Hr, slnc w or moklng o chlld rom o slngl pornt, w`ll coll o unctlon
colld 08$"45 lnstod.
Not olso thot w`v rducd th proboblllty o rproduclng rom J to 0.05. 1hls volu
moks qult o dlrnc, wlth o hlgh proboblllty o rproduclng, th systm wlll qulckly tnd
towords ovrpopulotlon. 1oo low o proboblllty, ond vrythlng wlll llkly qulckly dl out.
Wrltlng th 08$"45 unctlon lnto th \kV closs ls osy slnc Procsslng lncluds o unctlon
,//,"08$"45 thot copls th contnts o on orroy lnto onothr.
This function will return a new bloop, the
child.
W-88$ /%$/8&30%45 1
A 1% chance of executing the code in this
conditional, i.e. a 1% chance of
reproducing
:E 4/,7&894)5 P BNB)5 1
== d,.% 2<% W-88$ I,I"
@
@
W-88$ /%$/8&30%45 1
:E 4/,7&894)5 P BNBBBJ5 1
Make a copy of the DNA. Zph :H2'1Zph " 1#&-:803*+,
1% mutation rate :H2'1Zph-54/&/$*?-?D+,
Make a new bloop at the same location
with the new DNA.
)$/4)# #$! l'880*'8:&/28#J :H2'1Zph+,
P $'.$ O
f the bloop does not reproduce, return null. )$/4)# #4'',
@
@
0-,## \kV 1
This copy() function replaces crossover() in
this example.
\kV 08$"45 1
Choptr 9. 1h Lvolutlon o Cod
440
Now thot w hov oll th plcs ln ploc or slctlon ond rproductlon, w con lnollz th
+8/-& closs thot monogs th llst o oll W-88$ objcts [os wll os o b88& objct, whlch ltsl ls
o llst o ]`%028/ locotlons or oodj.
Bor you run th xompl, tok o momnt to guss whot slz ond spd o bloops th
systm wlll volv towords. W`ll dlscuss ollowlng th cod.
IJ&7:5# CK?L IN*5('/*1 #0*8U8'#7
Make a new array the same length and copy
its contents.
E-8,2KL 7%;?%7%# ' 7%; E-8,2K?%7%#N-%7?2<L*
,//,"08$"4?%7%#C7%;?%7%#5*
/%23/7 7%; \kV47%;?%7%#5*
@
@
+8/-& ;8/-&*
setup() and draw() do nothing more than
create and run a World object.
A8:& #%23$45 1
#:F%4GBBCDBB5*
;8/-& ' 7%; +8/-&4>B5*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
;8/-&N/3745*
@
0-,## +8/-& 1
The World object keeps track of the
population bloops as well as the food.
V//,"l:#2PW-88$^ I-88$#*
b88& E88&*
+8/-&4:72 7395 1
E88& ' 7%; b88&47395*
I-88$# ' 7%; V//,"l:#2PW-88$^45*
1h Notur o Cod [v005j
44J
| you gussd mdlum-slzd bloops wlth mdlum spd, you wr rlght. Wlth th dslgn o
thls systm, bloops thot or lorg or slmply too slow to lnd ood. And bloops thot or ost
or too smoll to lnd ood. 1h ons thot or obl to llv th longst tnd to b ln th
mlddl, lorg nough ond ost nough to lnd ood [but not too lorg or too ostj. 1hr or
olso som onomolls. |or xompl, l lt so hoppns thot o bunch o lorg bloops nd up ln
th som locotlon [ond borly mov bcous thy or so lorgj, thy moy oll dl out
suddnly, lovlng o lot o ood or on lorg bloop who hoppns to b thr to ot ond
ollowlng o mlnl-populotlon o lorg bloops to sustoln thmslvs or o prlod o tlm ln on
locotlon.
1hls xompl ls rothr slmpllstlc glvn lts slngl gn ond osxuol rproductlon. Hr or
som suggstlons or how you mlght opply th bloop xompl ln o mor loborot
cosystm slmulotlon.
Creating the population E8/ 4:72 : ' B* : P 739* :((5 1
]`%028/ -80,2:87 ' 7%; ]`%028/4/,7&894;:&2<5C/,7&894<%:?<255*
\kV &7, ' 7%; \kV45*
I-88$#N,&&47%; W-88$4-C&7,55*
@
@
A8:& /3745 1
E88&N/3745*
E8/ 4:72 : ' I-88$#N#:F%456)* : ^' B* :665 1
The bloops live their life. W-88$ I ' I-88$#N?%24:5*
IN/3745*
IN%,24E88&5*
f one dies, it is removed from the
population and food is added at its
location.
:E 4IN&%,&455 1
I-88$#N/%98A%4:5*
E88&N,&&4IN-80,2:875*
@
Here is where each living bloop has a
chance to reproduce. As long as a child is
made (i.e. not null) it is added to the
population.
W-88$ 0<:-& ' IN/%$/8&30%45*
:E 40<:-& S' 73--5 I-88$#N,&&40<:-&5*
@
@
@
Choptr 9. 1h Lvolutlon o Cod
442
@,( M2*-/-'(E 5.*G(2' @,( M2*-/-'(E 5.*G(2'
U'(Q W MO(.2&-(D
!99 (I*%:'&*; '* /*:. (2*-/-'(E` ):&%9&;< +.*E ',( (O4EQ%(- &; ',&- 2,4Q'(."
h !99 4 Q*Q:%4'&*; *+ Q.(94'*.- '* /*:. (2*-/-'(E" b&*%*<&24% (I*%:'&*;
)('8((; Q.(94'*.- 4;9 Q.(/ ^*. Q4.4-&'(- 4;9 ,*-'-_ &- *+'(; .(+(..(9 '* 4-
4; A4.E- .42(`B &; 8,&2, ',( 2.(4':.(- 2*;'&;:*:-%/ 494Q' 4;9 2*:;'(.Z
494Q' '* (42, *',(." P4; /*: 42,&(I( ',&- )(,4I&*. &; 4 -/-'(E *+ E:%'&Q%(
2.(4':.(-7
h f*8 8*:%9 /*: &EQ%(E(;' 2.*--*I(. 4;9 E:'4'&*; )('8((; '8* Q4.(;'- &;
4; (2*-/-'(E E*9(%(9 4+'(. ',( )%**Q-7 @./ &EQ%(E(;'&;< 4; 4%<*.&',E -*
',4' '8* 2.(4':.(- E((' 4;9 E4'( 8,(; 8&',&; 4 2(.'4&; Q.*O&E&'/" P4;
/*: E43( 2.(4':.(- 8&', <(;9(.7
h @./ :-&;< ',( 8(&<,'- *+ E:%'&Q%( -'((.&;< +*.2(- 4- 4 2.(4':.(H- \X!" P4;
/*: 2.(4'( 4 -2(;4.&* &; 8,&2, 2.(4':.(- (I*%I( '* 2**Q(.4'( 8&', (42,
*',(.7
h F;( *+ ',( <.(4'(-' 2,4%%(;<(- &; (2*-/-'(E -&E:%4'&*;- &- 42,&(I&;< 4
;&2( )4%4;2(" a*: 8&%% %&3(%/ +&;9 ',4' E*-' *+ /*:. 4''(EQ'- .(-:%' &; (&',(.
E4-- *I(.Q*Q:%4'&*; ^+*%%*8(9 )/ E4-- (O'&;2'&*;_ *. -&EQ%/ E4--
(O'&;2'&*; -'.4&<,' 484/" 6,4' '(2,;&m:(- 24; /*: (EQ%*/ '* 42,&(I(
)4%4;2(7 P*;-&9(. :-&;< ',( <(;('&2 4%<*.&',E &'-(%+ '* (I*%I( *Q'&E4%
Q4.4E('(.- +*. 4; (2*-/-'(E"
1h Notur o Cod [v005j
443
,"&:'#) ;DK %#()&5 ,"&:'#) ;DK %#()&5
%#'4*)38 %#'4*)38
You ccn't process me uith c normcl brcin.
! @E$2?-& 6E&&,
W`r ot th nd o our story. 1hls ls th lost olclol choptr o thls book [though | nvlslon
oddltlonol supplmntol motrlol or th wbslt ond prhops nw choptrs ln th uturj.
W bgon wlth lnonlmot objcts llvlng ln o world o orcs ond gov thos objcts dslrs,
outonomy, ond th oblllty to tok octlon occordlng to o systm o ruls. Nxt, w ollowd
thos objcts to llv ln o populotlon ond volv ovr tlm. Now w osk. Whot ls och
objct`s dclslon-moklng procss? How con lt odjust lts cholcs by lornlng ovr tlm? Con
o computotlonol ntlty procss lts nvlronmnt ond gnrot o dclslon?
1h humon broln con b dscrlbd os o blologlcol nurol ntworkon lntrconnctd wb
o nurons tronsmlttlng loborot pottrns o lctrlcol slgnols. Lndrlts rclv lnput
slgnols ond, bosd on thos lnputs, lr on output slgnol vlo on oxon. Or somthlng llk thot.
How th humon broln octuolly works ls on loborot ond complx mystry, on thot w
crtolnly or not golng to ottmpt to tockl ln rlgorous dtoll ln thls choptr.
Choptr J0. Nurol Ntworks
444
1h good nws ls thot dvloplng ngoglng onlmotd systms wlth cod dos not rqulr
sclntllc rlgor or occurocy, os w`v lornd throughout thls book. W con slmply b lnsplrd
by th ldo o broln unctlon.
|n thls choptr, w`ll bgln wlth o concptuol ovrvlw o th proprtls ond oturs o nurol
ntworks ond bulld th slmplst posslbl xompl o on [o ntwork thot conslsts o o slngl
nuronj. Atrwords, w`ll xomln strotgls or crotlng o Broln" objct thot con b lnsrtd
lnto our `%<:0-% closs ond usd to dtrmln strlng. |lnolly, w`ll olso look ot tchnlqus
or vlsuollzlng ond onlmotlng o ntwork o nurons.
Iiure :o.:
#T"# !.'&+&2&4% X(:.4% X('8*.3-D C;'.*9:2'&*; 4;9 #T"# !.'&+&2&4% X(:.4% X('8*.3-D C;'.*9:2'&*; 4;9
!QQ%&24'&*; !QQ%&24'&*;
Computr sclntlsts hov long bn lnsplrd by th humon broln. |n J943, Worrn 5.
McCulloch, o nurosclntlst, ond Woltr Pltts, o loglclon, dvlopd th lrst concptuol modl
o on ortllclol nurol ntwork. |n thlr popr, "A loglcol colculus o th ldos lmmlnnt ln
nrvous octlvlty," thy dscrlb th concpt o o nuron, o slngl cll llvlng ln o ntwork o
clls thot rclvs lnputs, procsss thos lnputs, ond gnrots on output.
1hlr work, ond th work o mony sclntlsts ond rsorchrs thot ollowd, wos not mont to
occurotly dscrlb how th blologlcol broln works. Rothr, on ortllclol nurol ntwork [whlch
w wlll now slmply rr to os o nurol ntwork"j wos dslgnd os o computotlonol modl
bosd on th broln to solv crtoln klnds o problms.
|t`s probobly prtty obvlous to you thot thr or problms thot or lncrdlbly slmpl or o
computr to solv, but dllcult or you. 1ok th squor root o 964,324, or xompl. A qulck
lln o cod producs th volu 982, o numbr Procsslng computd ln lss thon o
mllllscond. 1hr or, on th othr hond, problms thot or lncrdlbly slmpl or you or m to
solv, but not so osy or o computr. 5how ony toddlr o plctur o o klttn or puppy ond
thy`ll b obl to tll you vry qulckly whlch on ls whlch. 5oy hllo ond shok my hond on
mornlng ond you should b obl to plck m out o o crowd o popl th nxt doy. But nd o
mochln to prorm on o ths tosks? 5clntlsts hov olrody spnt ntlr corrs
rsorchlng ond lmplmntlng complx solutlons.
1h Notur o Cod [v005j
445
1h most common oppllcotlon o nurol ntworks ln computlng todoy ls to prorm on o
ths osy-or-o-humon, dllcult-or-o-mochln" tosks, otn rrrd to os pottrn
rcognltlon. Appllcotlons rong rom optlcol choroctr rcognltlon [turnlng prlntd or
hondwrlttn scons lnto dlgltol txtj to oclol rcognltlon. W don`t hov th tlm or nd to
us som o ths mor loborot ortllclol lntlllgnc olgorlthms hr, but l you or
lntrstd ln rsorchlng nurol ntworks, |`d rcommnd th books Att|t|c|o| lnte|||gence. A
Modetn Apptooch by 5tuort J. Russll ond Ptr Norvlg ond Al tot Gome Deve|opets by
Lovld M. Bourg ond Glnn 5monn.
A nurol ntwork ls o connctlonlst"
computotlonol systm. 1h computotlonol
systms w wrlt or procdurol, o
progrom storts ot th lrst lln o cod,
xcuts lt, ond gos on to th nxt,
ollowlng lnstructlons ln o llnor oshlon. A
tru nurol ntwork dos not ollow o llnor
poth. Rothr, lnormotlon ls procssd
collctlvly, ln porolll throughout o
ntwork o nods [th nods, ln thls cos,
blng nuronsj.
Hr w hov yt onothr xompl o o
complx systm, much llk th ons w
xomlnd ln Choptrs 6, 7, ond 8. 1h
lndlvlduol lmnts o th ntwork, th nurons, or slmpl. 1hy rod on lnput, procss lt,
ond gnrot on output. A ntwork o mony nurons, howvr, con xhlblt lncrdlbly rlch
ond lntlllgnt bhovlors.
On o th ky lmnts o o nurol ntwork ls lts oblllty to |eotn. A nurol ntwork ls not
just o complx systm, but o complx (8(A&/0$ (8(A&/0$ systm, monlng lt con chong lts lntrnol
structur bosd on th lnormotlon lowlng through lt. 1yplcolly, thls ls ochlvd through th
odjustlng o we|ghts. |n th dlogrom obov, och lln rprsnts o connctlon btwn two
nurons ond lndlcots th pothwoy or th low o lnormotlon. Loch connctlon hos o
>$/2+& >$/2+&, o numbr thot controls th slgnol btwn th two nurons. | th ntwork
gnrots o good" output [whlch w`ll dln lotrj, thr ls no nd to odjust th wlghts.
Howvr, l th ntwork gnrots o poor" outputon rror, so to spokthn th systm
odopts, oltrlng th wlghts ln ordr to lmprov subsqunt rsults.
1hr or svrol strotgls or lornlng, ond w`ll xomln two o thm ln thls choptr.
- Q:A$10/)$8 _$(1./.2 Q:A$10/)$8 _$(1./.2 Lssntlolly, o strotgy thot lnvolvs o tochr thot ls
smortr thon th ntwork ltsl. |or xompl, lt`s tok th oclol rcognltlon
xompl. 1h tochr shows th ntwork o bunch o ocs, ond th tochr
olrody knows th nom ossoclotd wlth och oc. 1h ntwork moks lts
gusss, thn th tochr provlds th ntwork wlth th onswrs. 1h ntwork
con thn compor lts onswrs to th known corrct" ons ond mok odjustmnts
Iiure :o.z
Choptr J0. Nurol Ntworks
446
occordlng to lts rrors. Our lrst nurol ntwork ln th nxt sctlon wlll ollow thls
modl.
- R.):A$10/)$8 _$(1./.2 R.):A$10/)$8 _$(1./.2 Rqulrd whn thr lsn`t on xompl doto st wlth known
onswrs. |mogln sorchlng or o hlddn pottrn ln o doto st. An oppllcotlon o thls
ls clustrlng, l.. dlvldlng o st o lmnts lnto groups occordlng to som unknown
pottrn. W won`t b looklng ot ony xompls o unsuprvlsd lornlng ln thls
choptr, os thls strotgy ls lss rlvont or our xompls.
- S$/.;!1%$-$.& _$(1./.2 S$/.;!1%$-$.& _$(1./.2 A strotgy bullt on obsrvotlon. 1hlnk o o llttl mous
runnlng through o moz. | lt turns lt, lt gts o plc o chs, l lt turns rlght, lt
rclvs o llttl shock. [Lon`t worry, thls ls just o prtnd mous.j Prsumobly, th
mous wlll lorn ovr tlm to turn lt. |ts nurol ntwork moks o dclslon wlth on
outcom [turn lt or rlghtj ond obsrvs lts nvlronmnt [yum or ouchj. | th
obsrvotlon ls ngotlv, th ntwork con odjust lts wlghts ln ordr to mok o
dlrnt dclslon th nxt tlm. Rlnorcmnt lornlng ls common ln robotlcs. At
tlm 2, th robot prorms o tosk ond obsrvs th rsults. Lld lt crosh lnto o woll or
oll o o tobl? Or ls lt unhormd? W`ll look ot rlnorcmnt lornlng ln th contxt
o our slmulotd strlng vhlcls.
1hls oblllty o o nurol ntwork to lorn, to mok odjustmnts to lts structur ovr tlm, ls whot
moks lt so usul ln th lld o ortllclol lntlllgnc. Hr or som stondord uss o nurol
ntworks ln sotwor todoy.
- N(&&$1. S$%!2./&/!. N(&&$1. S$%!2./&/!. W`v mntlond thls svrol tlms olrody ond lt`s probobly
th most common oppllcotlon. Lxompls or oclol rcognltlon, optlcol choroctr
rcognltlon, tc.
- */-$ Q$1/$) N1$8/%&/!. */-$ Q$1/$) N1$8/%&/!. Nurol ntworks con b usd to mok prdlctlons. Wlll th
stock rls or oll tomorrow? Wlll lt roln or b sunny?
- Q/2.(' N1!%$))/.2 Q/2.(' N1!%$))/.2 Cochlor lmplonts ond horlng olds nd to lltr out
unncssory nols ond omplly th lmportont sounds. Nurol ntworks con b
trolnd to procss on oudlo slgnol ond lltr lt opproprlotly.
- M!.&1!' M!.&1!' You moy hov rod obout rcnt rsorch odvoncs ln sl-drlvlng cors.
Nurol ntworks or otn usd to monog strlng dclslons o physlcol vhlcls
[or slmulotd onsj.
- Q!;& Q$.)!1) Q!;& Q$.)!1) A sot snsor rrs to th procss o onolyzlng o collctlon o mony
mosurmnts. A thrmomtr con tll you th tmprotur o th olr, but whot l
you olso knw th humldlty, boromtrlc prssur, dwpolnt, olr quollty, olr dnslty,
tc.? Nurol ntworks con b mployd to procss th lnput doto rom mony
lndlvlduol snsors ond voluot thm os o whol.
- D.!-('@ E$&$%&/!. D.!-('@ E$&$%&/!. Bcous nurol ntworks or so good ot rcognlzlng pottrns,
thy con olso b trolnd to gnrot on output whn somthlng occurs thot dosn`t
1h Notur o Cod [v005j
447
lt th pottrn. 1hlnk o o nurol ntwork monltorlng your dolly routln ovr o long
prlod o tlm. Atr lornlng th pottrns o your bhovlor, lt could olrt you whn
somthlng ls omlss.
1hls ls by no mons o comprhnslv llst o oppllcotlons o nurol ntworks. But hopully lt
glvs you on ovroll sns o th oturs ond posslbllltls. 1h thlng ls, nurol ntworks
or compllcotd ond dllcult. 1hy lnvolv oll sorts o oncy mothmotlcs. Whll thls ls oll
osclnotlng [ond lncrdlbly lmportont to sclntllc rsorchj, o lot o th tchnlqus or not
vry proctlcol ln th world o bulldlng lntroctlv, onlmotd Procsslng sktchs. Not to
mntlon thot ln ordr to covr oll thls motrlol, w would nd onothr bookor mor llkly,
o srls o books.
5o lnstod, w`ll bgln our lost hurroh ln th notur o cod wlth th slmplst o oll nurol
ntworks, ln on ort to undrstond how th ovroll concpts or opplld ln cod. 1hn
w`ll look ot som Procsslng sktchs thot gnrot vlsuol rsults lnsplrd by ths
concpts.
#T"0 @,( 5(.2(Q'.*; #T"0 @,( 5(.2(Q'.*;
|nvntd ln J957 by |ronk Rosnblott ot th Cornll Aronoutlcol Loborotory, o prcptron ls
th slmplst nurol ntwork posslbl. o computotlonol modl o o slngl nuron. A
prcptron conslsts o on or mor lnputs, o procssor, ond o slngl output.
A prcptron ollows th d-orword" modl, monlng lnputs or snt lnto th nuron,
or procssd, ond rsult ln on output. |n th dlogrom obov, thls mons th ntwork [on
nuronj rods rom lt to rlght. lnputs com ln, output gos out.
Lt`s ollow och o ths stps ln mor dtoll.
5tp J. Rclv lnputs.
5oy w hov o prcptron wlth two lnputslt`s coll thm x! ond x2.
Iiure :o.: The perceptron
Choptr J0. Nurol Ntworks
448
e#04/ ?Y ID " D>
e#04/ DY I> " <
5tp 2. Wlght lnputs.
Loch lnput thot ls snt lnto th nuron must lrst b wlghtd, l.. multlplld by som volu
[otn o numbr btwn -J ond Jj. Whn crotlng o prcptron, w`ll typlcolly bgln by
osslgnlng rondom wlghts. Hr, lt`s glv th lnputs th ollowlng wlghts.
%$2GH/ ?Y ?-=
%$2GH/ DY TD
W tok och lnput ond multlply lt by lts wlght.
e#04/ ? F %$2GH/ ? _ D> F ?-= " U
e#04/ D F %$2GH/ D _ < F TD " T<
5tp 3. 5um lnputs.
1h wlghtd lnputs or thn summd.
k45 " U K T< " >
5tp 4. Gnrot output.
1h output o o prcptron ls gnrotd by posslng thot sum through on octlvotlon unctlon. |n
th cos o o slmpl blnory output, th octlvotlon unctlon ls whot tlls th prcptron whthr
to lr" or not. You con nvlslon on LLL connctd to th output slgnol. l lt lrs, th llght
gos on, l not, lt stoys o.
Actlvotlon unctlons con gt o llttl blt holry. | you stort rodlng on o thos ortllclol
lntlllgnc txtbooks looklng or mor lno obout octlvotlon unctlons, you moy soon lnd
yoursl rochlng or o colculus txtbook. Howvr, wlth our rlnd th slmpl prcptron,
w`r golng to do somthlng rolly osy. Lt`s mok th octlvotlon unctlon th slgn o th
sum. |n othr words, l th sum ls o posltlv numbr, th output ls J, l lt ls ngotlv, th output
ls -J.
c4/04/ " .2G#*.45+ _ .2G#*>+ _ KD
1h Notur o Cod [v005j
449
Lt`s rvlw ond condns ths stps so w con lmplmnt thm wlth o cod snlppt.
*+$ N$1%$A&1!. D'2!1/&+-3 *+$ N$1%$A&1!. D'2!1/&+-3
J. |or vry lnput, multlply thot lnput by lts wlght.
2. 5um oll o th wlghtd lnputs.
3. Comput th output o th prcptron bosd on thot sum possd through on
octlvotlon unctlon [th slgn o th sumj.
Lt`s ossum w hov two orroys o numbrs, th lnputs ond th wlghts. |or xompl.
|or vry lnput" lmplls o loop thot multlplls och lnput by lts corrspondlng wlght.
5lnc w nd th sum, w con odd up th rsults ln thot vry loop.
Onc w hov th sum w con comput th output.
E-8,2KL :7$32# ' 1)> C D@*
E-8,2KL ;%:?<2# ' 1BNJC6)@*
Steps 1 and 2: Add up all the weighted
inputs.
E-8,2 #39 ' B*
E8/ 4:72 : ' B* : P :7$32#N-%7?2<* :((5 1
#39 (' :7$32#K:LQ;%:?<2#K:L*
@
Step 3: Passing the sum through an
activation function
E-8,2 832$32 ' ,02:A,2%4#395*
The activation function :72 ,02:A,2%4E-8,2 #395 1
Return a 1 if positive, -1 if negative. :E 4#39 ^ B5 /%23/7 )*
%-#% /%23/7 6)*
@
#T"= U&EQ%( 54''(.; Y(2*<;&'&*; [-&;< 4 #T"= U&EQ%( 54''(.; Y(2*<;&'&*; [-&;< 4
5(.2(Q'.*; 5(.2(Q'.*;
Now thot w undrstond th computotlonol procss o o prcptron, w con look ot on
xompl o on ln octlon. W stotd thot nurol ntworks or otn usd or pottrn
rcognltlon oppllcotlons, such os oclol rcognltlon. Lvn slmpl prcptrons con
dmonstrot th boslcs o clossllcotlon, os ln th ollowlng xompl.
Choptr J0. Nurol Ntworks
450
Consldr o lln ln two-dlmnslonol spoc.
Polnts ln thot spoc con b closslld os
llvlng on lthr on sld o th lln or th
othr. Whll thls ls o somwhot sllly xompl
[slnc thr ls clorly no nd or o nurol
ntwork, w con dtrmln on whlch sld o
polnt lls wlth som slmpl olgbroj, lt
shows how o prcptron con b trolnd to
rcognlz polnts on on sld vrsus
onothr.
Lt`s soy o prcptron hos 2 lnputs [th x-
ond y-coordlnots o o polntj. slng o slgn octlvotlon unctlon, th output wlll lthr b -J or
Jl.., th lnput doto ls closslld occordlng to th slgn o th output. |n th obov dlogrom,
w con s how och polnt ls lthr blow th lln [-Jj or obov [Jj.
1h prcptron ltsl con b dlogrommd os ollows.
W con s how thr or two lnputs [x ond yj, o wlght or och lnput [we|ght
x
ond we|ght
y
j,
os wll os o procsslng nuron thot gnrots th output.
1hr ls o prtty slgnllcont problm hr, howvr. Lt`s consldr th polnt [0,0j. Whot l w
snd thls polnt lnto th prcptron os lts lnput. x 0 ond y 0? Whot wlll th sum o lts
wlghtd lnputs b? No mottr whot th wlghts or, th sum wlll olwoys b 0! But thls con`t
b rlghtotr oll, th polnt [0,0j could crtolnly b obov or blow vorlous llns ln our two-
dlmnslonol world.
1o ovold thls dllmmo, our prcptron wlll rqulr o thlrd lnput, typlcolly rrrd to os o "/() "/()
lnput. A blos lnput olwoys hos th volu o J ond ls olso wlghtd. Hr ls our prcptron wlth
th oddltlon o th blos.
Iiure :o.(
Iiure :o.
1h Notur o Cod [v005j
45J
Lt`s go bock to th polnt [0,0j. Hr or our lnputs.
? F !$2GH/ 98) I " ?
? F !$2GH/ 98) 3 " ?
D F !$2GH/ 98) 62&. " !$2GH/ 98) 62&.
1h output ls th sum o th obov thr volus, 0 plus 0 plus th blos`s wlght. 1hror,
th blos, on lts own, onswrs th qustlon os to whr [0,0j ls ln rlotlon to th lln. | th
blos`s wlght ls posltlv, [0,0j ls obov th lln, ngotlv, lt ls blow. |t bloss" th
prcptron`s undrstondlng o th lln`s posltlon rlotlv to [0,0j.
Iiure :o.
#T"> P*9&;< ',( 5(.2(Q'.*; #T"> P*9&;< ',( 5(.2(Q'.*;
W`r now rody to ossmbl th cod or o ]%/0%$2/87 closs. 1h only doto th
prcptron nds to trock or th lnput wlghts, ond w could us on orroy o loots to stor
ths.
1h constructor could rclv on orgumnt lndlcotlng th numbr o lnputs [ln thls cos
thr. x, y, ond o blosj ond slz th orroy occordlngly.
A prcptron nds to b obl to rclv lnputs ond gnrot on output. W con pockog
ths rqulrmnts lnto o unctlon colld E%%&E8/;,/&45. |n thls xompl, w`ll hov th
0-,## ]%/0%$2/87 1
E-8,2KL ;%:?<2#*
]%/0%$2/874:72 75 1
;%:?<2# ' 7%; E-8,2K7L*
E8/ 4:72 : ' B* : P ;%:?<2#N-%7?2<* :((5 1
The weights are picked randomly to start. ;%:?<2#K:L ' /,7&8946)C)5*
@
@
Choptr J0. Nurol Ntworks
452
prcptron rclv lts lnputs os on orroy [whlch should b th som lngth os th orroy o
wlghtsj ond rturn th output os on lntgr.
Prsumobly, w could now crot o ]%/0%$2/87 objct ond osk lt to mok o guss or ony
glvn polnt.
Lld th prcptron gt lt rlght? At thls polnt, th prcptron hos no bttr thon o 50/50
chonc o orrlvlng ot th rlght onswr. Rmmbr, whn w crotd lt, w gov och wlght o
rondom volu. A nurol ntwork lsn`t moglc. |t`s not golng to b obl to guss onythlng
corrctly unlss w toch lt how to!
1o troln o nurol ntwork to onswr corrctly, w`r golng to mploy th mthod o
supetv|sed |eotn|ng thot w dscrlbd ln sctlon J0.J [s pog 445j.
Wlth thls mthod, th ntwork ls provldd wlth lnputs or whlch thr ls o known onswr. 1hls
woy th ntwork con lnd out l lt hos mod o corrct guss. | lt`s lncorrct, th ntwork con
lorn rom lts mlstok ond odjust lts wlghts. 1h procss ls os ollows.
J. Provld th prcptron wlth lnputs or whlch thr ls o known onswr.
:72 E%%&E8/;,/&4E-8,2KL :7$32#5 1
E-8,2 #39 ' B*
E8/ 4:72 : ' B* : P ;%:?<2#N-%7?2<* :((5 1
#39 (' :7$32#K:LQ;%:?<2#K:L*
@
Result is the sign of the sum, -1 or +1. Here
the perceptron is making a guess. s it on
one side of the line or the other?
/%23/7 ,02:A,2%4#395*
@
Iiure :o.;
Create the Perceptron. ]%/0%$2/87 $ ' 7%; ]%/0%$2/874H5*
The input is 3 values: x,y and bias. E-8,2KL $8:72 ' 1JBC6)>C)@*
The answer! :72 /%#3-2 ' $NE%%&E8/;,/&4$8:725*
1h Notur o Cod [v005j
453
2. Ask th prcptron to guss on onswr.
3. Comput th rror. [Lld lt gt th onswr rlght or wrong?j
4. Adjust oll th wlghts occordlng to th rror.
5. Rturn to 5tp J ond rpot!
5tps J through 4 con b pockogd lnto o unctlon. Bor w con wrlt th ntlr unctlon,
howvr, w nd to xomln 5tps 3 ond 4 ln mor dtoll. How do w dln th
prcptron`s rror? And how should w odjust th wlghts occordlng to thls rror?
1h prcptron`s rror con b dlnd os th dlrnc btwn th dslrd onswr ond lts
guss.
nqqcq " ZnkeqnZ csbMsb T rsnkk csbMsb
1h obov ormulo moy look omlllor to you. |n Choptr 6 [s pog 263j, w computd o
strlng orc os th dlrnc btwn our dslrd vloclty ond our currnt vloclty.
kbnnqepr " ZnkeqnZ NnocfebW T fsqqnpb NnocfebW
1hls wos olso on rror colculotlon. 1h currnt vloclty octs os o guss ond th rror [th
strlng orcj tlls us how to odjust th vloclty ln th rlght dlrctlon. |n o momnt, w`ll
s how odjustlng th vhlcl`s vloclty to ollow o torgt ls just llk odjustlng th wlghts
o o nurol ntwork to orrlv ot th rlght onswr.
|n th cos o th prcptron, th output hos only two posslbl volus. B5 B5 or H5 H5. 1hls mons
thr or only thr posslbl rrors.
| th prcptron gusss th corrct onswr, thn th guss quols th dslrd output ond
th rror ls 0. | th corrct onswr ls -J ond w`v gussd J, thn th rror ls -2. | th
corrct onswr ls J ond w`v gussd -J, thn th rror ls 2.
.#8/)#- .#8/)#- R(#88 R(#88 I))*) I))*)
-J -J 0
-J J -2
J -J 2
J J 0
Choptr J0. Nurol Ntworks
454
1h rror ls th dtrmlnlng octor ln how th prcptron`s wlghts should b odjustd. |or
ony glvn wlght, whot w or looklng to colculot ls th chong ln wlght, otn colld
Awe|ght [or dlto" wlght, dlto blng th Grk lttr j.
pn% %nerxb " %nerxb K y%nerxb
wlght ls colculotd os th rror multlplld by th lnput.
y%nerxb " nqqcq F epMsb
1hror.
pn% %nerxb " %nerxb K nqqcq F epMsb
1o undrstond why thls works, w con ogoln rturn to strlng [s pog 263j. A strlng
orc ls ssntlolly on rror ln vloclty. | w opply thot orc os our occlrotlon [vlocltyj,
thn w odjust our vloclty to mov ln th corrct dlrctlon. 1hls ls whot w wont to do wlth
our nurol ntwork`s wlghts. W wont to odjust thm ln th rlght dlrctlon, os dlnd by th
rror.
Wlth strlng, howvr, w hod on oddltlonol vorlobl thot controlld th vhlcl`s oblllty to
str. th mox|mum totce. Wlth o hlgh moxlmum orc, th vhlcl wos obl to occlrot ond
turn vry qulckly, wlth o lowr orc, th vhlcl would tok longr to odjust lts vloclty. 1h
nurol ntwork wlll mploy o slmllor strotgy wlth o vorlobl colld th lornlng constont."
W`ll odd ln th lornlng constont os ollows.
pn% %nerxb " %nerxb K nqqcq F epMsb F onhqpepr fcpkbhpb
Notlc thot o hlgh lornlng constont mons th wlght wlll chong mor drostlcolly. 1hls moy
hlp us orrlv ot o solutlon mor qulckly, but wlth such lorg chongs ln wlght lt`s posslbl
w wlll ovrshoot th optlmol wlghts. Wlth o smoll lornlng constont, th wlghts wlll b
odjustd slowly, rqulrlng mor trolnlng tlm but ollowlng th ntwork to mok vry smoll
odjustmnts thot could lmprov th ntwork`s ovroll occurocy.
Assumlng th oddltlon o o vorlobl 0 or th lornlng constont, w con now wrlt o trolnlng
unctlon or th prcptron ollowlng th obov stps.
A new variable is introduced to control the
learning rate.
E-8,2 0 ' BNB)*
Step 1: Provide the inputs and known
answer. These are passed in as arguments
to train().
A8:& 2/,:74E-8,2KL :7$32#C :72 &%#:/%&5 1
Step 2: Guess according to those inputs. :72 ?3%## ' E%%&E8/;,/&4:7$32#5*
Step 3: Compute the error (difference
between answer and guess).
E-8,2 %//8/ ' &%#:/%& 6 ?3%##*
1h Notur o Cod [v005j
455
W con now s th ]%/0%$2/87 closs os o whol.
1o troln th prcptron, w nd o st o lnputs wlth o known onswr. W could pockog
thls up ln o closs llk so.
Step 4: Adjust all the weights according to
the error and learning constant.
E8/ 4:72 : ' B* : P ;%:?<2#N-%7?2<* :((5 1
;%:?<2#K:L (' 0 Q %//8/ Q :7$32#K:L*
@
@
0-,## ]%/0%$2/87 1
The Perceptron stores its weights and
learning constants.
E-8,2KL ;%:?<2#*
E-8,2 0 ' BNB)*
]%/0%$2/874:72 75 1
;%:?<2# ' 7%; E-8,2K7L*
Weights start off random. E8/ 4:72 : ' B* : P ;%:?<2#N-%7?2<* :((5 1
;%:?<2#K:L ' /,7&8946)C)5*
@
@
Return an output based on inputs. :72 E%%&E8/;,/&4E-8,2KL :7$32#5 1
E-8,2 #39 ' B*
E8/ 4:72 : ' B* : P ;%:?<2#N-%7?2<* :((5 1
#39 (' :7$32#K:LQ;%:?<2#K:L*
@
/%23/7 ,02:A,2%4#395*
@
Output is a +1 or -1. :72 ,02:A,2%4E-8,2 #395 1
:E 4#39 ^ B5 /%23/7 )*
%-#% /%23/7 6)*
@
Train the network against known data. A8:& 2/,:74E-8,2KL :7$32#C :72 &%#:/%&5 1
:72 ?3%## ' E%%&E8/;,/&4:7$32#5*
E-8,2 %//8/ ' &%#:/%& 6 ?3%##*
E8/ 4:72 : ' B* : P ;%:?<2#N-%7?2<* :((5 1
;%:?<2#K:L (' 0 Q %//8/ Q :7$32#K:L*
@
@
@
0-,## n/,:7%/ 1
Choptr J0. Nurol Ntworks
456
Now th qustlon bcoms, how do w plck o polnt ond know whthr lt ls obov or blow o
lln? Lt`s stort wlth th ormulo or o lln, whr " ls colculotd os o unctlon o !.
3 " 9*I+
|n gnrlc trms, o lln con b dscrlbd os.
3 " &I K 6
Hr`s o spcllc xompl.
3 " >FI K D
W con thn wrlt o Procsslng unctlon wlth thls ln mlnd.
5o, l w mok up o polnt.
How do w know l thls polnt ls obov or blow th lln? 1h lln unctlon E4!5 glvs us th "
volu on th lln or thot ! posltlon. Lt`s coll thot "-:7%.
| th " volu w or xomlnlng ls obov th lln, lt wlll b lss thon "-:7%.
A "Trainer" object stores the inputs and the
correct answer.
E-8,2KL :7$32#*
:72 ,7#;%/*
n/,:7%/4E-8,2 !C E-8,2 "C :72 ,5 1
:7$32# ' 7%; E-8,2KHL*
:7$32#KBL ' !*
:7$32#K)L ' "*
Note that the Trainer has the bias input built
into its array.
:7$32#K>L ' )*
,7#;%/ ' ,*
@
@
A function to calculate y based on x along a
line
E-8,2 E4E-8,2 !5 1
/%23/7 >Q!()*
@
E-8,2 ! ' /,7&894;:&2<5*
E-8,2 " ' /,7&894<%:?<25*
The y position on the line E-8,2 "-:7% ' E4!5*
1h Notur o Cod [v005j
457
W con thn mok o n/,:7%/ objct wlth th lnputs ond th corrct onswr.
Assumlng w hod o ]%/0%$2/87 objct $2/87, w could thn troln lt by sndlng th lnputs
olong wlth th known onswr.
Now, lt`s lmportont to rmmbr thot thls ls just o dmonstrotlon. Rmmbr our
5hokspor-typlng monkys [s pog 392j? W oskd our gntlc olgorlthm to solv or
to b or not to b"on onswr w olrody knw. W dld thls to mok sur our gntlc
olgorlthm workd proprly. 1h som rosonlng opplls to thls xompl. W don`t nd o
prcptron to tll us whthr o polnt ls obov or blow o lln, w con do thot wlth slmpl
moth. W or uslng thls scnorlo, on thot w con oslly solv wlthout o prcptron, to
dmonstrot th prcptron`s olgorlthm os wll os oslly conlrm thot lt ls worklng proprly.
Lt`s look ot how th prcptron works wlth on orroy o mony trolnlng polnts.
Iiure :o.8
:E 4" P "-:7%5 1
The answer is -1 if y is above the line. ,7#;%/ ' 6)*
@ %-#% 1
,7#;%/ ' )*
@
n/,:7%/ 2 ' 7%; n/,:7%/4!C "C ,7#;%/5*
$2/87N2/,:742N:7$32#C2N,7#;%/5*
Choptr J0. Nurol Ntworks
458
IJ&7:5# ;DK;L !"# 9#)0#:')*1
The Perceptron ]%/0%$2/87 $2/87*
2,000 training points n/,:7%/KL 2/,:7:7? ' 7%; n/,:7%/K>BBBL*
:72 08372 ' B*
The formula for a line E-8,2 E4E-8,2 !5 1
/%23/7 >Q!()*
@
A8:& #%23$45 1
#:F%4DBBC DBB5*
$2/87 ' 7%; ]%/0%$2/874H5*
Make 2,000 training points. E8/ 4:72 : ' B* : P 2/,:7:7?N-%7?2<* :((5 1
E-8,2 ! ' /,7&8946;:&2<=>C;:&2<=>5*
E-8,2 " ' /,7&8946<%:?<2=>C<%:?<2=>5*
s the correct answer 1 or -1? :72 ,7#;%/ ' )*
:E 4" P E4!55 ,7#;%/ ' 6)*
2/,:7:7?K:L ' 7%; n/,:7%/4!C "C ,7#;%/5*
@
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
2/,7#-,2%4;:&2<=>C<%:?<2=>5*
$2/87N2/,:742/,:7:7?K08372LN:7$32#C 2/,:7:7?K08372LN,7#;%/5*
For animation, we are training one point at a
time.
08372 ' 408372 ( )5 x 2/,:7:7?N-%7?2<*
E8/ 4:72 : ' B* : P 08372* :((5 1
#2/8.%4B5*
:72 ?3%## ' $2/87NE%%&E8/;,/&42/,:7:7?K:LN:7$32#5*
1h Notur o Cod [v005j
459
Show the classificationno fill for -1,
black for +1.
:E 4?3%## ^ B5 78b:--45*
%-#% E:--4B5*
%--:$#%42/,:7:7?K:LN:7$32#KBLC 2/,:7:7?K:LN:7$32#K)LC XC X5*
@
@
|nstod o uslng th suprvlsd lornlng modl obov, con you troln th nurol
ntwork to lnd th rlght wlghts by uslng o gntlc olgorlthm?
MO(.2&-( #T"# MO(.2&-( #T"#
Vlsuollz th prcptron ltsl. Lrow th lnputs, th procsslng nod, ond th output.
MO(.2&-( #T"0 MO(.2&-( #T"0
#T"? ! U'((.&;< 5(.2(Q'.*; #T"? ! U'((.&;< 5(.2(Q'.*;
Whll closslylng polnts occordlng to thlr posltlon obov or blow o lln wos o usul
dmonstrotlon o th prcptron ln octlon, lt dosn`t hov much proctlcol rlvonc to th
othr xompls throughout thls book. |n thls sctlon, w`ll tok th concpts o o prcptron
[orroy o lnputs, slngl outputj, opply lt to strlng bhovlors, ond dmonstrot
rlnorcmnt lornlng olong th woy.
W or now golng to tok slgnllcont crotlv llcns wlth th concpt o o nurol ntwork.
1hls wlll ollow us to stlck wlth th boslcs ond ovold som o th hlghly complx olgorlthms
ossoclotd wlth mor sophlstlcotd nurol ntworks. Hr w`r not so concrnd wlth
ollowlng ruls outllnd ln ortllclol lntlllgnc txtbooksw`r just hoplng to mok
somthlng lntrstlng ond broln-llk.
Rmmbr our good rlnd th `%<:0-% closs? You know, thot on or moklng objcts wlth
o locotlon, vloclty, ond occlrotlon? 1hot could oby Nwton`s lows wlth on
,$$-"b8/0%45 unctlon ond mov oround th wlndow occordlng to o vorlty o strlng
ruls?
Whot l w oddd on mor vorlobl to our `%<:0-% closs?
0-,## `%<:0-% 1
Choptr J0. Nurol Ntworks
460
Hr`s our scnorlo. Lt`s soy w hov o Procsslng sktch wlth on V//,"l:#2 o torgts ond
o slngl vhlcl.
Lt`s soy thot th vhlcl sks oll o th torgts. Accordlng to th prlnclpls o Choptr 6, w
would nxt wrlt o unctlon thot colculots o strlng orc towords och torgt, opplylng och
orc on ot o tlm to th objct`s occlrotlon. Assumlng th torgts or on V//,"l:#2 o
]`%028/ objcts, lt would look somthlng llk.
|n Choptr 6, w olso xomlnd how w could crot mor dynomlc slmulotlons by wlghtlng
och strlng orc occordlng to som rul. |or xompl, w could soy thot th orthr you
or rom o torgt, th strongr th orc.
Giving the vehicle a brain! ]%/0%$2/87 I/,:7*
]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
==%20NNN
Iiure :o.p
A8:& #%%.4V//,"l:#2P]`%028/^ 2,/?%2#5 1
E8/ 4]`%028/ 2,/?%2 q 2,/?%2#5 1
For every target, apply a steering force
towards the target.
]`%028/ E8/0% ' #%%.42,/?%2#N?%24:55*
,$$-"b8/0%4E8/0%5*
@
@
A8:& #%%.4V//,"l:#2P]`%028/^ 2,/?%2#5 1
E8/ 4]`%028/ 2,/?%2 q 2,/?%2#5 1
]`%028/ E8/0% ' #%%.42,/?%2#N?%24:55*
E-8,2 & ' ]`%028/N&:#242,/?%2C-80,2:875*
E-8,2 ;%:?<2 ' 9,$4&CBC;:&2<CBCJ5*
1h Notur o Cod [v005j
46J
But whot l lnstod w could osk our broln [l.. prcptronj to tok ln oll th orcs os on
lnput, procss thm occordlng to wlghts o th prcptron lnputs, ond gnrot on output
strlng orc? Whot l w could lnstod soy.
|n othr words, lnstod o wlghtlng ond occumulotlng th orcs lnsld our vhlcl, w
slmply poss on orroy o orcs to th vhlcl`s broln" objct ond ollow th broln to wlght
ond sum th orcs or us. 1h output ls thn opplld os o strlng orc. 1hls opns up o
rong o posslbllltls. A vhlcl could mok dclslons os to how to str on lts own, lornlng
rom lts mlstoks ond rspondlng to stlmull ln lts nvlronmnt. Lt`s s how thls works.
W con us th lln clossllcotlon prcptron os o modl, wlth on lmportont dlrncth
lnputs or not slngl numbrs, but vctors! Lt`s look ot how th E%%&E8/;,/&45 unctlon
works ln our vhlcl`s prcptron, olongsld th on rom our prvlous xompl.
Q#"/05# 9Q#0'*) /1:('8 Q#"/05# 9Q#0'*) /1:('8 _/1# +5*&' /1:('8 _/1# +5*&' /1:('8
]`%028/ E%%&E8/;,/&4]`%028/KL E8/0%#5 1
== [39 :# , ]`%028/N
MN$:/8) .45 " #$! MN$:/8)*+,
E8/ 4:72 : ' B* : P ;%:?<2#N-%7?2<* :((5 1
== `%028/ ,&&:2:87 ,7& 93-2:$-:0,2:87
98):$.[2\-54'/*!$2GH/.[2\+,
.45-&11*98):$.[2\+,
@
== k8 ,02:A,2:87 E3702:87
)$/4)# .45,
@
:72 E%%&E8/;,/&4E-8,2KL :7$32#5 1
== [39 :# , E-8,2N
9'8&/ .45 " ?,
E8/ 4:72 : ' B* : P ;%:?<2#N-%7?2<* :((5 1
== [0,-,/ ,&&:2:87 ,7& 93-2:$-:0,2:87
.45 K" 2#04/.[2\F!$2GH/.[2\,
@
== V02:A,2:87 E3702:87
)$/4)# &:/2L&/$*.45+,
@
Weighting each steering force individually E8/0%N93-24;%:?<25*
,$$-"b8/0%4E8/0%5*
@
@
A8:& #%%.4V//,"l:#2P]`%028/^ 2,/?%2#5 1
Make an array of inputs for our brain. ]`%028/KL E8/0%# ' 7%;
]`%028/K2,/?%2#N#:F%45L*
E8/ 4:72 : ' B* : P E8/0%#N-%7?2<* :((5 1
Fill the array with a steering force for each
target.
E8/0%#K:L ' #%%.42,/?%2#N?%24:55*
@
Ask our brain for a result and apply that as
the force!
]`%028/ 832$32 ' I/,:7N$/80%##4E8/0%#5*
,$$-"b8/0%4832$325*
@
Choptr J0. Nurol Ntworks
462
Not how ths two unctlons lmplmnt norly ldntlcol olgorlthms, wlth two dlrncs.
J. Q:--/.2 NW$%&!1)6 Q:--/.2 NW$%&!1)6 |nstod o o srls o numbrs oddd togthr, och lnput ls o
]`%028/ ond must b multlplld by th wlght ond oddd to o sum occordlng to th
mothmotlcol ]`%028/ unctlons.
2. ^! (%&/0(&/!. ;:.%&/!.6 ^! (%&/0(&/!. ;:.%&/!.6 |n thls cos, w`r toklng th rsult ond opplylng lt dlrctly
os o strlng orc or th vhlcl, so w`r not osklng or o slmpl boolon volu
thot closslls lt ln on o two cotgorls. Rothr, w`r osklng or row output ltsl,
th rsultlng ovroll orc.
Onc th rsultlng strlng orc hos bn opplld, lt`s tlm to glv dbock to th broln, l..
te|ntotcement |eotn|ng. Wos th dclslon to str ln thot portlculor dlrctlon o good on or o
bod on? Prsumobly l som o th torgts wr prdotors [rsultlng ln blng otnj ond
som o th torgts wr ood [rsultlng ln grotr holthj, th ntwork would odjust lts
wlghts ln ordr to str owoy rom th prdotors ond towords th ood.
Lt`s tok o slmplr xompl, whr th vhlcl slmply wonts to stoy clos to th cntr o th
wlndow. W`ll troln th broln os ollows.
Hr w or posslng th broln o copy o oll
th lnputs [whlch lt wlll nd or rror
corrctlonj os wll os on obsrvotlon obout
lts nvlronmnt. o ]`%028/ thot polnts rom
lts currnt locotlon to whr lt dslrs to b.
1hls ]`%028/ ssntlolly srvs os th
rrorth longr th ]`%028/, th wors th vhlcl ls prormlng, th shortr, th bttr.
1h broln con thn opply thls rror" vctor [whlch hos two rror volus, on or ! ond on or
"j os o mons or odjustlng th wlghts, just os w dld ln th lln clossllcotlon xompl.
!)&/1/16 '"# Q#"/05# !)&/1/16 '"# Q#"/05# !)&/1/16 '"# _/1# ,5&88/+/#) !)&/1/16 '"# _/1# ,5&88/+/#)
A8:& 2/,:74]`%028/KL E8/0%#C ]`%028/ %//8/5 1
E8/ 4:72 : ' B* : P ;%:?<2#N-%7?2<* :((5 1
;%:?<2#K:L (' 0Q%//8/N!QE8/0%#K:LN!*
;%:?<2#K:L (' 0Q%//8/N"QE8/0%#K:LN"*
@
@
A8:& 2/,:74E-8,2KL :7$32#C :72 &%#:/%&5 1
:72 ?3%## ' E%%&E8/;,/&4:7$32#5*
E-8,2 %//8/ ' &%#:/%& 6 ?3%##*
E8/ 4:72 : ' B* : P ;%:?<2#N-%7?2<* :((5 1
;%:?<2#K:L (' 0 Q %//8/ Q :7$32#K:L*
@
@
]`%028/ &%#:/%& ' 7%; ]`%028/4;:&2<=>C<%:?<2=>5*
]`%028/ %//8/ ' ]`%028/N#3I4&%#:/%&C -80,2:875*
I/,:7N2/,:74E8/0%#C%//8/5*
Iiure :o.:o
1h Notur o Cod [v005j
463
Bcous th vhlcl obsrvs lts own rror, thr ls no nd to colculot on, w con
slmply rclv th rror os on orgumnt. Notlc how th chong ln wlght ls procssd
twlc, onc or th rror olong th x-oxls ond onc or th y-oxls.
W con now look ot th `%<:0-% closs ond s how th #2%%/ unctlon uss o prcptron to
control th ovroll strlng orc. 1h nw contnt rom thls choptr ls hlghllghtd.
IJ&7:5# ;DK<L 9#)0#:')*1 8'##)/16
;%:?<2#K:L (' 0Q%//8/N!QE8/0%#K:LN!*
;%:?<2#K:L (' 0Q%//8/N"QE8/0%#K:LN"*
0-,## `%<:0-% 1
The Vehicle now has a brain. M$):$0/)8# 6)&2#,
Same old variables for physics ]`%028/ -80,2:87*
]`%028/ A%-80:2"*
]`%028/ ,00%-%/,2:87*
E-8,2 9,!E8/0%*
E-8,2 9,!#$%%&*
The Vehicle creates a perceptron with n
inputs and a learning constant.
`%<:0-%4:72 7C E-8,2 !C E-8,2 "5 1
6)&2# " #$! M$):$0/)8#*#J?-??D+,
,00%-%/,2:87 ' 7%; ]`%028/4BCB5*
A%-80:2" ' 7%; ]`%028/4BCB5*
-80,2:87 ' 7%; ]`%028/4!C"5*
9,!#$%%& ' D*
9,!E8/0% ' BN)*
@
Choptr J0. Nurol Ntworks
464
Same old update() function A8:& 3$&,2%45 1
A%-80:2"N,&&4,00%-%/,2:875*
A%-80:2"N-:9:249,!#$%%&5*
-80,2:87N,&&4A%-80:2"5*
,00%-%/,2:87N93-24B5*
@
Same old applyForce() function A8:& ,$$-"b8/0%4]`%028/ E8/0%5 1
,00%-%/,2:87N,&&4E8/0%5*
@
A8:& #2%%/4V//,"l:#2P]`%028/^ 2,/?%2#5 1
]`%028/KL E8/0%# ' 7%; ]`%028/K2,/?%2#N#:F%45L*
E8/ 4:72 : ' B* : P E8/0%#N-%7?2<* :((5 1
E8/0%#K:L ' #%%.42,/?%2#N?%24:55*
@
All the steering forces are inputs. MN$:/8) )$.4'/ " 6)&2#-9$$198)!&)1*98):$.+,
The result is applied. ,$$-"b8/0%4/%#3-25*
MN$:/8) 1$.2)$1 " #$! MN$:/8)*!21/H;>JH$2GH/;>+,
MN$:/8) $))8) " MN$:/8)-.46*1$.2)$1J '8:&/28#+,
6)&2#-/)&2#*98):$.J$))8)+,
@
The brain is trained according to the
distance to the center.
Same old seek() function ]`%028/ #%%.4]`%028/ 2,/?%25 1
]`%028/ &%#:/%& ' ]`%028/N#3I42,/?%2C-80,2:875*
&%#:/%&N78/9,-:F%45*
&%#:/%&N93-249,!#$%%&5*
]`%028/ #2%%/ ' ]`%028/N#3I4&%#:/%&CA%-80:2"5*
#2%%/N-:9:249,!E8/0%5*
/%23/7 #2%%/*
@
@
1h Notur o Cod [v005j
465
Vlsuollz th wlghts o th ntwork. 1ry mopplng och torgt`s corrspondlng
wlght to lts brlghtnss.
MO(.2&-( #T"= MO(.2&-( #T"=
1ry dlrnt ruls or rlnorcmnt lornlng. Whot l som torgts or dslrobl ond
som or undslrobl?
MO(.2&-( #T"> MO(.2&-( #T">
#T"K C'H- 4 AX('8*.3`B Y(E(E)(.7 #T"K C'H- 4 AX('8*.3`B Y(E(E)(.7
Ys, o prcptron con hov multlpl lnputs, but lt ls stlll o lonly nuron. 1h powr o
nurol ntworks coms ln th ntworklng ltsl. Prcptrons or, sodly, lncrdlbly llmltd ln
thlr obllltls. | you rod on A| txtbook, lt wlll soy thot o prcptron con only solv '/.$(1'@ '/.$(1'@
)$A(1("'$ )$A(1("'$ problms. Whot`s o llnorly sporobl problm? Lt`s tok o look ot our lrst
xompl, whlch dtrmlnd whthr polnts wr on on sld o o lln or th othr.
On th lt o |lgur J0.JJ, w hov closslc llnorly sporobl doto. Groph oll o th
posslbllltls, l you con clossly th doto wlth o strolght lln, thn lt ls llnorly sporobl. On
th rlght, howvr, ls non-llnorly sporobl doto. You con`t drow o strolght lln to sporot
th block dots rom th groy ons.
On o th slmplst xompls o o non-llnorly sporobl problm ls XOR, or xcluslv or."
W`r oll omlllor wlth AND. |or A AND B to b tru, both A ond B must b tru. Wlth OR,
lthr A or B con b tru or A OR B to voluot os tru. 1hs or both llnorly sporobl
problms. Lt`s look ot th solutlon spoc, o truth tobl."
Iiure :o.::
Choptr J0. Nurol Ntworks
466
5 how you con drow o lln to sporot th tru outputs rom th ols ons?
XOR ls th qulvolnt o OR ond NO7 AND. |n othr words, A XOR B only voluots to tru l
on o thm ls tru. | both or ols or both or tru, thn w gt ols. 1ok o look ot th
ollowlng truth tobl.
1hls ls not llnorly sporobl. 1ry to drow o strolght lln to sporot th tru outputs rom th
ols onsyou con`t!
5o prcptrons con`t vn solv somthlng os slmpl os XOR. But whot l w mod o ntwork
out o two prcptrons? | on prcptron con solv OR ond on prcptron con solv NO7
AND, thn two prcptrons comblnd con solv XOR.
Iiure :o.:z
Iiure :o.:
1h Notur o Cod [v005j
467
1h obov dlogrom ls known os o mu|t|-|oyeted petceptton, o ntwork o mony nurons.
5om or lnput nurons ond rclv th lnputs, som or port o whot`s colld o hlddn"
loyr [os thy or connctd to nlthr th lnputs nor th outputs o th ntwork dlrctlyj,
ond thn thr or th output nurons, rom whlch w rod th rsults.
1rolnlng ths ntworks ls much mor compllcotd. Wlth th slmpl prcptron, w could
oslly voluot how to chong th wlghts occordlng to th rror. But hr thr or so
mony dlrnt connctlons, och ln o dlrnt loyr o th ntwork. How dos on know
how much och nuron or connctlon contrlbutd to th ovroll rror o th ntwork?
1h solutlon to optlmlzlng wlghts o o multl-loyrd ntwork ls known os "(%JA1!A(2(&/!. "(%JA1!A(2(&/!..
1h output o th ntwork ls gnrotd ln th som monnr os o prcptron. 1h lnputs
multlplld by th wlghts or summd ond d orword through th ntwork. 1h dlrnc
hr ls thot thy poss through oddltlonol loyrs o nurons bor rochlng th output.
1rolnlng th ntwork [l.. odjustlng th wlghtsj olso lnvolvs toklng th rror [dslrd rsult
- gussj. 1h rror, howvr, must b d bockwords through th ntwork. 1h lnol rror
ultlmotly odjusts th wlghts o oll th connctlons.
Bockpropogotlon ls o blt byond th scop o thls book ond lnvolvs o onclr octlvotlon
unctlon [colld th slgmold unctlonj os wll os som boslc colculus. | you or lntrstd ln
how bockpropogotlon works, chck th book wbslt [ond GltHub rposltoryj or on
xompl thot solvs XOR uslng o multl-loyrd d orword ntwork wlth bockpropogotlon.
|nstod, hr w`ll ocus on o cod romwork or bulldlng th vlsuol orchltctur o o
ntwork. W`ll mok k%3/87 objcts ond M877%02:87 objcts rom whlch o k%2;8/. objct
con b crotd ond onlmotd to show th d orword procss. 1hls wlll closly rsmbl
som o th orc-dlrctd groph xompls w xomlnd ln Choptr 5 [toxlcllbsj.
Iiure :o.:(
#T"L X(:.4% X('8*.3 \&4<.4E #T"L X(:.4% X('8*.3 \&4<.4E
Our gool wlll b to crot th ollowlng slmpl ntwork dlogrom.
Choptr J0. Nurol Ntworks
468
1h prlmory bulldlng block or thls dlogrom ls o nuron. |or th purpos o thls xompl, th
k%3/87 closs dscrlbs on ntlty wlth on (x,yI locotlon.
1h k%2;8/. closs con thn monog on V//,"l:#2 o nurons, os wll os hov lts own
locotlon [so thot och nuron ls drown rlotlv to th ntwork`s cntrj. 1hls ls portlcl
systms J0J. W hov o slngl lmnt [o nuronj ond o ntwork [o systm" o mony
nuronsj.
Iiure :o.:
An incredibly simple Neuron class stores
and displays the location of a single neuron.
0-,## k%3/87 1
]`%028/ -80,2:87*
k%3/874E-8,2 !C E-8,2 "5 1
-80,2:87 ' 7%; ]`%028/4!C "5*
@
A8:& &:#$-,"45 1
#2/8.%4B5*
E:--4B5*
%--:$#%4-80,2:87N!C -80,2:87N"C )GC )G5*
@
@
A Network is a list of neurons. 0-,## k%2;8/. 1
V//,"l:#2Pk%3/87^ 7%3/87#*
]`%028/ -80,2:87*
k%2;8/.4E-8,2 !C E-8,2 "5 1
-80,2:87 ' 7%; ]`%028/4!C"5*
7%3/87# ' 7%; V//,"l:#2Pk%3/87^45*
@
We can add an neuron to the network. A8:& ,&&k%3/874k%3/87 75 1
7%3/87#N,&&475*
@
1h Notur o Cod [v005j
469
Now w con prtty oslly mok th dlogrom obov.
1h obov yllds.
We can draw the entire network. A8:& &:#$-,"45 1
$3#<d,2/:!45*
2/,7#-,2%4-80,2:87N!C -80,2:87N"5*
E8/ 4k%3/87 7 q 7%3/87#5 1
7N&:#$-,"45*
@
$8$d,2/:!45*
@
@
k%2;8/. 7%2;8/.*
A8:& #%23$45 1
#:F%4GDBC HGB5*
Make a Network. 7%2;8/. ' 7%; k%2;8/.4;:&2<=>C<%:?<2=>5*
Make the Neurons. k%3/87 , ' 7%; k%3/8746>BBCB5*
k%3/87 I ' 7%; k%3/874BC)BB5*
k%3/87 0 ' 7%; k%3/874BC6)BB5*
k%3/87 & ' 7%; k%3/874>BBCB5*
Add the Neurons to the network. 7%2;8/.N,&&k%3/874,5*
7%2;8/.N,&&k%3/874I5*
7%2;8/.N,&&k%3/87405*
7%2;8/.N,&&k%3/874&5*
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
Show the network. 7%2;8/.N&:#$-,"45*
@
Choptr J0. Nurol Ntworks
470
Whot`s mlsslng, o cours, ls th connctlon. W con consldr o M877%02:87 objct to b
mod up o thr lmnts, two nurons [rom k%3/87 , to k%3/87 Ij ond o ;%:?<2.
Onc w hov th ldo o o M877%02:87 objct, w con wrlt o unctlon [lt`s put lt lnsld th
k%2;8/. clossj thot conncts two nurons togthrth gool blng thot ln oddltlon to moklng
th nurons ln #%23$45, w con olso connct thm.
1h k%2;8/. closs thror nds o nw unctlon colld 0877%0245, whlch moks o
M877%02:87 objct btwn th two spclld nurons.
0-,## M877%02:87 1
A connection is between two neurons. k%3/87 ,*
k%3/87 I*
A connection has a weight. E-8,2 ;%:?<2*
M877%02:874k%3/87 E/89C k%3/87 28CE-8,2 ;5 1
;%:?<2 ' ;*
, ' E/89*
I ' 28*
@
A connection is drawn as a line. A8:& &:#$-,"45 1
#2/8.%4B5*
#2/8.%+%:?<24;%:?<2QD5*
-:7%4,N-80,2:87N!C ,N-80,2:87N"C IN-80,2:87N!C IN-80,2:87N"5*
@
@
A8:& #%23$45 1
#:F%4GDBC HGB5*
7%2;8/. ' 7%; k%2;8/.4;:&2<=>C<%:?<2=>5*
k%3/87 , ' 7%; k%3/8746>BBCB5*
k%3/87 I ' 7%; k%3/874BC)BB5*
k%3/87 0 ' 7%; k%3/874BC6)BB5*
k%3/87 & ' 7%; k%3/874>BBCB5*
Making connections between the neurons 7%2;8/.N0877%024,CI5*
7%2;8/.N0877%024,C05*
7%2;8/.N0877%024IC&5*
7%2;8/.N0877%0240C&5*
7%2;8/.N,&&k%3/874,5*
7%2;8/.N,&&k%3/874I5*
7%2;8/.N,&&k%3/87405*
7%2;8/.N,&&k%3/874&5*
@
1h Notur o Cod [v005j
47J
Prsumobly, w mlght thlnk thot th k%2;8/. should stor on V//,"l:#2 o connctlons,
just llk lt stors on V//,"l:#2 o nurons. Whll usul, ln thls cos such on V//,"l:#2 ls
not ncssory ond ls mlsslng on lmportont otur thot w nd. ltlmotly w plon to d
orword" th nurons through th ntwork, so th k%3/87 objcts thmslvs must know to
whlch nurons thy or connctd ln th orword" dlrctlon. |n othr words, och nuron
should hov lts own llst o M877%02:87 objcts. Whn , conncts to I, w wont , to stor o
rrnc o thot connctlon so thot lt con poss lts output to I whn th tlm coms.
|n som coss, w olso mlght wont k%3/87 I to know obout thls connctlon, but ln thls
portlculor xompl w or only golng to poss lnormotlon ln on dlrctlon.
|or thls to work, w hov to odd on V//,"l:#2 o connctlons to th k%3/87 closs. 1hn w
lmplmnt th ,&&M877%02:8745 unctlon thot stors th connctlon ln thot V//,"l:#2.
1h nuron`s &:#$-,"45 unctlon con drow th connctlons os wll. And lnolly, w hov
our ntwork dlogrom.
A8:& 0877%024k%3/87 ,C k%3/87 I5 1
Connection has a random weight. M877%02:87 0 ' 7%; M877%02:874,C IC
/,7&894)55*
== W32 ;<,2 &8 ;% &8 ;:2< 2<% M877%02:87 8Io%02i
@
A8:& 0877%024k%3/87 ,C k%3/87 I5 1
M877%02:87 0 ' 7%; M877%02:874,C IC /,7&894)55*
,N,&&M877%02:87405*
@
0-,## k%3/87 1
]`%028/ -80,2:87*
The neuron stores its connections. V//,"l:#2PM877%02:87^ 0877%02:87#*
k%3/874E-8,2 !C E-8,2 "5 1
-80,2:87 ' 7%; ]`%028/4!C "5*
0877%02:87# ' 7%; V//,"l:#2PM877%02:87^45*
@
Adding a connection to this neuron A8:& ,&&M877%02:874M877%02:87 05 1
0877%02:87#N,&&405*
@
Choptr J0. Nurol Ntworks
472
IJ&7:5# ;DK=L %#()&5 1#'4*)3 -/&6)&7
A8:& &:#$-,"45 1
#2/8.%4B5*
#2/8.%+%:?<24)5*
E:--4B5*
%--:$#%4-80,2:87N!C -80,2:87N"C )GC )G5*
Drawing all the connections E8/ 4M877%02:87 0 q 0877%02:87#5 1
0N&:#$-,"45*
@
@
@
#T"N !;&E4'&;< S((9 S*.84.9 #T"N !;&E4'&;< S((9 S*.84.9
An lntrstlng problm to consldr ls how to vlsuollz th low o lnormotlon os lt trovls
throughout o nurol ntwork. Our ntwork ls bullt on th d orword modl, monlng thot on
lnput orrlvs ot th lrst nuron [drown on th lthond sld o th wlndowj ond th output o
thot nuron lows ocross th connctlons to th rlght untll lt xlts os output rom th ntwork
ltsl.
Our lrst stp ls to odd o unctlon to th ntwork to rclv thls lnput, whlch w`ll mok o
rondom numbr btwn 0 ond J.
A8:& #%23$45 1
All our old network set up code
A new function to send in an input 7%2;8/.NE%%&E8/;,/&4/,7&894)55*
@
1h Notur o Cod [v005j
473
1h ntwork, whlch monogs oll th nurons, con choos to whlch nurons lt should opply
thot lnput. |n thls cos, w`ll do somthlng slmpl ond just d o slngl lnput lnto th lrst
nuron ln th V//,"l:#2, whlch hoppns to b th lt-most on.
Whot dld w do? Wll, w mod lt ncssory to odd o unctlon colld E%%&E8/;,/&45 ln th
k%3/87 closs thot wlll rclv th lnput ond procss lt.
| you rcoll rom worklng wlth our prcptron, th stondord tosk thot th procsslng unlt
prorms ls to sum up oll o lts lnputs. 5o l our k%3/87 closs odds o vorlobl colld #39, lt
con slmply occumulot th lnputs os thy or rclvd.
1h nuron con thn dcld whthr lt should lr," or poss on output through ony o lts
connctlons to th nxt loyr ln th ntwork. Hr w con crot o rolly slmpl octlvotlon
unctlon. l th sum ls grotr thon J, lr!
0-,## k%2;8/. 1
A new function to feed an input into the
neuron
A8:& E%%&E8/;,/&4E-8,2 :7$325 1
k%3/87 #2,/2 ' 7%3/87#N?%24B5*
#2,/2NE%%&E8/;,/&4:7$325*
@
0-,## k%3/87
A8:& E%%&E8/;,/&4E-8,2 :7$325 1
What do we do with the input?
@
0-,## k%3/87
2#/ .45 " ?,
A8:& E%%&E8/;,/&4E-8,2 :7$325 1
Accumulate the sums. .45 K" 2#04/,
@
A8:& E%%&E8/;,/&4E-8,2 :7$325 1
#39 (' :7$32*
Activate the neuron and fire the outputs? :E 4#39 ^ )5 1
E:/%45*
f we've fired off our output, we can reset
our sum to 0.
#39 ' B*
@
@
Choptr J0. Nurol Ntworks
474
Now, whot do w do ln th E:/%45 unctlon? | you rcoll, och nuron kps trock o lts
connctlons to othr nurons. 5o oll w nd to do ls loop through thos connctlons ond
E%%&E8/;,/&45 th nuron`s output. |or thls slmpl xompl, w`ll just tok th nuron`s #39
vorlobl ond mok lt th output.
Hr`s whr thlngs gt o llttl trlcky. Atr oll, our job hr ls not to octuolly mok o
unctlonlng nurol ntwork, but to onlmot o slmulotlon o on. | th nurol ntwork wr just
contlnulng lts work, lt would lnstontly poss thos lnputs [multlplld by th connctlon`s wlghtj
olong to th connctd nurons. W`d soy somthlng llk.
But thls ls not whot w wont. Whot w wont to do ls drow somthlng thot w con s trovllng
olong th connctlon rom k%3/87 , to k%3/87 I.
Lt`s lrst thlnk obout how w mlght do thot. W know th locotlon o k%3/87 ,, lt`s th
]`%028/ ,N-80,2:87. k%3/87 I ls locotd ot IN-80,2:87. W nd to stort somthlng movlng
rom k%3/87 , by crotlng onothr ]`%028/ thot wlll stor th poth o our trovllng doto.
Onc w hov o copy o thot locotlon, w con us ony o th motlon olgorlthms thot w`v
studld throughout thls book to mov olong thls poth. Hrlt`s plck somthlng vry slmpl
ond just lntrpolot rom , to I.
Along wlth th connctlon`s lln, w con thn drow o clrcl ot thot locotlon.
1hls rsmbls th ollowlng.
A8:& E:/%45 1
E8/ 4M877%02:87 0 q 0877%02:87#5 1
The Neuron sends the sum out through all
of its connections
0NE%%&E8/;,/&4#395*
@
@
0-,## M877%02:87 1
A8:& E%%&E8/;,/&4E-8,2 A,-5 1
INE%%&E8/;,/&4A,-Q;%:?<25*
@
]`%028/ #%7&%/ ' ,N-80,2:87N?%245*
#%7&%/N! ' -%/$4#%7&%/N!C IN-80,2:87N!C BN)5*
#%7&%/N" ' -%/$4#%7&%/N"C IN-80,2:87N"C BN)5*
#2/8.%4B5*
-:7%4,N-80,2:87N!C ,N-80,2:87N"C IN-80,2:87N!C IN-80,2:87N"5*
E:--4B5*
$''20.$*.$#1$)-IJ .$#1$)-3J BJ B+,
1h Notur o Cod [v005j
475
OK, so thot`s how w mlght mov somthlng olong th connctlon. But how do w know
whn to do so? W stort thls procss th momnt th M877%02:87 objct rclvs th
dorword" slgnol. W con kp trock o thls procss by mploylng o slmpl I88-%,7 to
know whthr th connctlon ls sndlng or not. Bor, w hod.
Now, lnstod o sndlng th volu on strolght owoy, w`ll trlggr on onlmotlon.
Notlc how our M877%02:87 closs now nds thr nw vorlobls. W nd o I88-%,7
sndlng" thot storts os ols ond thot wlll trock whthr or not th connctlon ls octlvly
sndlng [l.. onlmotlngj. W nd o ]`%028/ sndr" or th locotlon whr w`ll drow th
trovllng dot. And slnc w orn`t posslng th output olong thls lnstont, w`ll nd to stor lt
ln o vorlobl thot wlll do th job lotr.
1h E%%&E8/;,/&45 unctlon ls colld th momnt th connctlon bcoms octlv. Onc lt`s
octlv, w`ll nd to coll onothr unctlon contlnuously [och tlm through &/,;45j, on thot
wlll updot th locotlon o th trovllng doto.
Iiure :o.:
A8:& E%%&E8/;,/&4E-8,2 A,-5 1
INE%%&E8/;,/&4A,-Q;%:?<25*
@
0-,## M877%02:87 1
I88-%,7 #%7&:7? ' E,-#%*
]`%028/ #%7&%/*
E-8,2 832$32*
A8:& E%%&E8/;,/&4E-8,2 A,-5 1
Sending is now true. #%7&:7? ' 2/3%*
Start the animation at the location of
Neuron A.
#%7&%/ ' ,N-80,2:87N?%245*
Store the output for when it is actually time
to feed it forward.
832$32 ' A,-Q;%:?<2*
@
A8:& 3$&,2%45 1
:E 4#%7&:7?5 1
As long as we're sending, interpolate our
points.
#%7&%/N! ' -%/$4#%7&%/N!C IN-80,2:87N!C
BN)5*
#%7&%/N" ' -%/$4#%7&%/N"C IN-80,2:87N"C BN)5*
@
@
Choptr J0. Nurol Ntworks
476
W`r mlsslng o ky lmnt, howvr. W nd to chck l th sndr hos orrlvd ot locotlon
b, ond l lt hos, d orword thot output to th nxt nuron.
Lt`s look ot th M877%02:87 closs oll togthr, os wll os our nw &/,;45 unctlon.
IJ&7:5# ;DK>L 21/7&'/16 1#()&5 1#'4*)3 -/&6)&7
A8:& 3$&,2%45 1
:E 4#%7&:7?5 1
#%7&%/N! ' -%/$4#%7&%/N!C IN-80,2:87N!C BN)5*
#%7&%/N" ' -%/$4#%7&%/N"C IN-80,2:87N"C BN)5*
How far are we from neuron b? 9'8&/ 1 " MN$:/8)-12./*.$#1$)J 6-'8:&/28#+,
f we're close enough (within one pixel) pass
on the output. Turn off sending.
29 *1 S D+ O
6-9$$198)!&)1*84/04/+,
.$#12#G " 9&'.$,
@
@
@
A8:& &/,;45 1
I,0.?/837&4>JJ5*
The Network now has a new update()
method that updates all of the Connection
objects.
#$/!8)(-401&/$*+,
7%2;8/.N&:#$-,"45*
29 *9)&5$f84#/ C E? "" ?+ O
We are choosing to send in an input every
30 frames.
#$/!8)(-9$$198)!&)1*)&#185*D++,
P
@
0-,## M877%02:87 1
1h Notur o Cod [v005j
477
The Connection's data E-8,2 ;%:?<2*
k%3/87 ,*
k%3/87 I*
Variables to track the animation I88-%,7 #%7&:7? ' E,-#%*
]`%028/ #%7&%/*
E-8,2 832$32 ' B*
M877%02:874k%3/87 E/89C k%3/87 28C E-8,2 ;5 1
;%:?<2 ' ;*
, ' E/89*
I ' 28*
@
The Connection is active with data
traveling from a to b.
A8:& E%%&E8/;,/&4E-8,2 A,-5 1
832$32 ' A,-Q;%:?<2*
#%7&%/ ' ,N-80,2:87N?%245*
#%7&:7? ' 2/3%*
@
Update the animation if it is sending. A8:& 3$&,2%45 1
:E 4#%7&:7?5 1
#%7&%/N! ' -%/$4#%7&%/N!C IN-80,2:87N!C BN)5*
#%7&%/N" ' -%/$4#%7&%/N"C IN-80,2:87N"C BN)5*
E-8,2 & ' ]`%028/N&:#24#%7&%/C IN-80,2:875*
:E 4& P )5 1
INE%%&E8/;,/&4832$325*
#%7&:7? ' E,-#%*
@
@
@
Draw the connection as a line and traveling
circle.
A8:& &:#$-,"45 1
#2/8.%4B5*
#2/8.%+%:?<24)(;%:?<2QD5*
-:7%4,N-80,2:87N!C ,N-80,2:87N"C IN-80,2:87N!C IN-80,2:87N"5*
:E 4#%7&:7?5 1
E:--4B5*
#2/8.%+%:?<24)5*
%--:$#%4#%7&%/N!C #%7&%/N"C )GC )G5*
@
@
@
Choptr J0. Nurol Ntworks
478
1h ntwork ln th obov xompl wos monuolly conlgurd by sttlng th locotlon o
och nuron ond lts connctlons wlth hord-codd volus. Rwrlt thls xompl to
gnrot th ntwork`s loyout vlo on olgorlthm. Con you mok o clrculor ntwork
dlogrom? A rondom on? An xompl o o multl-loyrd ntwork ls blow.
MO(.2&-( #T"? MO(.2&-( #T"?
Rwrlt th xompl so thot och nuron kps trock o lts orword ond bockword
connctlons. Con you d lnputs through th ntwork ln ony dlrctlon?
MO(.2&-( #T"K MO(.2&-( #T"K
|nstod o -%/$45, us movlng bodls wlth strlng orcs to vlsuollz th low o
lnormotlon ln th ntwork.
MO(.2&-( #T"L MO(.2&-( #T"L
1h Notur o Cod [v005j
479
@,( M2*-/-'(E 5.*G(2' @,( M2*-/-'(E 5.*G(2'
U'(Q #T MO(.2&-(D
@./ &;2*.Q*.4'&;< ',( 2*;2(Q' *+ 4 A).4&;B &;'* /*:. 2.(4':.(-"
h [-( .(&;+*.2(E(;' %(4.;&;< &; ',( 2.(4':.(-H 9(2&-&*;ZE43&;< Q.*2(--"
h P.(4'( 4 2.(4':.( ',4' +(4':.(- 4 I&-:4%&c4'&*; *+ &'- ).4&; 4- Q4.' *+ &'-
9(-&<; ^(I(; &+ ',( ).4&; &'-(%+ &- ;*' +:;2'&*;4%_"
h P4; ',( (2*-/-'(E 4- 4 8,*%( (E:%4'( ',( ).4&;7 P4; (%(E(;'- *+ ',(
(;I&.*;E(;' )( ;(:.*;- 4;9 ',( 2.(4':.(- 42' 4- &;Q:'- 4;9 *:'Q:'-7
@,( (;9 @,( (;9
| you`r stlll rodlng, thonk you! You`v rochd th nd o th book. But or os much
motrlol os thls book contolns, w`v borly scrotchd th suroc o th world w lnhoblt
ond o tchnlqus or slmulotlng lt. |t`s my lntntlon or thls book to llv os on ongolng
projct, ond | hop to contlnu oddlng nw tutorlols ond xompls to th book`s wbslt
[http.//noturocod.comj os wll os xpond ond updot th prlntd motrlol. Your dbock
ls truly opprclotd, so plos gt ln touch vlo moll ot [donllyshlmon.ntj or by
contrlbutlng to th GltHub rposltory [http.//glthub.com/shlmon/1h-Notur-o-Cod/j, ln
kplng wlth th opn-sourc splrlt o th projct. 5hor your work. Kp ln touch. Lt`s b
two wlth notur.
Choptr J0. Nurol Ntworks
480
G()'"#) H#&-/16 G()'"#) H#&-/16
b**3- b**3-
- Alxondr, R. McNlll. lt|nc|p|es ot An|mo| locomot|on [http.//t.co/|0lronLj.
Prlncton, NJ. Prlncton nlvrslty Prss, 2002.
- Bntly, Ptr. lvo|ut|onoty Des|gn by Computets [http.//t.co/X|p7bJzwj. 5on
|ronclsco. Morgon Koumonn Publlshrs, J999.
- Bohnockr, Hortmut, Bndlkt Gross, Jullo Loub, ond Cloudlus Lozzronl. Genetot|ve
Des|gn. V|suo||ze, ltogtom, ond Cteote w|th ltocess|ng [http.//t.co/8ykmokLj. Nw
York. Prlncton Archltcturol Prss, 20J2.
- |lok, Gory Wllllom. 7he Computot|ono| Beouty ot Notute. Computet lxp|otot|ons ot
ltocto|s, Choos, Comp|ex 5ystems, ond Adoptot|on [http.//t.co/Kdb1oJZXj.
Combrldg, MA. M|1 Prss, J998.
- Hol, Nothon Cobot. Absttoct|on |n Att ond Notute [http.//t.co/ztbJzCLj. Nw York.
Lovr, J993.
- Hlldbrondt, 5ton, ond Anthony J. 1rombo. Mothemot|cs ond Opt|mo| lotm
[http.//t.co/|0lronLj. Nw York. 5clntllc Amrlcon Llbrory, J985. Llstrlbutd by W.
H. |rmon.
- Klln, Morrls. Mothemot|cs ond the lhys|co| ot|d [http.//t.co/v845ZnGxj. Nw York.
Crowll, J959.
- Kodlck, Lonny. Mothemot|cs ond lhys|cs tot ltogtommets [http.//t.co/ygLdHMokj.
Hlnghom, MA. Chorls Rlvr Mdlo, 2005.
1h Notur o Cod [v005j
48J
- McMohon, 1homos A., ond John 1ylr Bonnr. On 5|ze ond l|te [http.//t.co/
LhX3KwZBj. Nw York. 5clntllc Amrlcon Llbrory, J983. Llstrlbutd by W. H.
|rmon.
- Mondlbrot, Bnolt B. 7he ltocto| Geometty ot Notute [http.//t.co/jHR5sCj. 5on
|ronclsco. W. H. |rmon, J982.
- Porc, Ptr. 5ttuctute |n Notute ls o 5ttotegy tot Des|gn [http.//t.co/zoGMOMcj.
Combrldg, MA. M|1 Prss, J980.
- Porson, Mott. Genetot|ve Att [http.//t.co/bXCWgOCj. Grnwlch, C1. Monnlng
Publlcotlons, 20JJ. Llstrlbutd by Porson Lducotlon.
- Pruslnklwlcz, Przmysow, ond Arlstld Llndnmoyr. 7he A|got|thm|c Beouty ot
l|onts [http.//t.co/koL7|hJj. Nw York. 5prlngr-Vrlog, J990.
- Ros, Cosy, ond Chondlr McWlllloms. lotm-Code |n Des|gn, Att, ond
Atch|tectute [http.//t.co/JjGgwhvj. Lslgn Brls. Nw York. Prlncton
Archltcturol Prss, 20J0.
- Ros, Cosy, ond Bn |ry. ltocess|ng. A ltogtomm|ng Hondboo| tot V|suo|
Des|gnets ond Att|sts [http.//t.co/dtOLdOpj. Combrldg, MA. M|1 Prss, 2007.
- 1hompson, L`Arcy Wntworth. On Gtowth ond lotm. 7he Comp|ete Rev|sed
ld|t|on [http.//t.co/vncWoJuWj. Nw York. Lovr, J992.
- Vogl., 5tvn. l|te |n Mov|ng l|u|ds [http.//t.co/y1bVtoJj. Prlncton, NJ. Prlncton
nlvrslty Prss, J994.
- Wod, Lovld. l|. Dynom|c lotm |n Notute [http.//t.co/JYLlsLHj. Woodn Books.
Nw York. Wolkr & Co., 2003.
- Wotrmon, 1olbot H. An|mo| Nov|got|on [http.//t.co/c2otv8LZj. Nw York. 5clntllc
Amrlcon Llbrory, J989. Llstrlbutd by W. H. |rmon.
- Whyt, Lonclot Low. Aspects ot lotm. A 5ympos|um on lotm |n Notute ond Att
[http.//t.co/7kVLMj. Mldlond Books, MB 3J. Bloomlngton. |ndlono nlvrslty
Prss, J966.
|or othr books thot us Procsslng, s Procsslng Books [http.//www.procsslng.org/
lornlng/booksj.
54Q(.- 4;9 !.'&2%(- 54Q(.- 4;9 !.'&2%(-
- Golontr, Phlllp. "1h Problm wlth Lvolutlonory Art |s." [http.//blt.ly/57dhnqj
Popr prsntd ot LvoCOMNL1`J0. 1h 7th Luropon Lvnt on th Appllcotlon o
|urthr Rodlng
482
Notur-lnsplrd 1chnlqus or 1lcommunlcotlon Ntworks ond othr Porolll ond
Llstrlbutd 5ystms, Aprll 7-9, 20J0.
- Gordnr, Mortln. "Mothmotlcol Goms. 1h |ontostlc Comblnotlons o John
Conwoy`s Nw 5olltolr Gom Ll." [http.//www.lblbllo.org/llpottrns/
octobrJ970.htmlj 5c|ent|t|c Amet|con 229 [Octobr J970j. J20-23.
- Rvs, Wllllom 1. "Portlcl 5ystmsA 1chnlqu or Modllng o Closs o |uzzy
Objcts." [http.//dl.ocm.org/cltotlon.cm?ld357320j ACM 7tonsoct|ons on Gtoph|cs
2.2 [Aprll J983j. 9J-J08.
- 5lms, Korl. "Artllclol Lvolutlon or Computr Grophlcs." [http.//www.korlslms.com/
poprs/slggroph9J.htmlj Popr prsntd ot 5|GGRAPH '9J. 1h J8th Annuol
Conrnc on Computr Grophlcs ond |ntroctlv 1chnlqus, Los Vgos, NV, July
28-August 2, J99J.
- ---. "Lvolvlng Vlrtuol Croturs." [http.//www.korlslms.com/poprs/slggroph94.pdj
Popr prsntd ot 5|GGRAPH '94. 1h 2Jst Annuol Conrnc on Computr
Grophlcs ond |ntroctlv 1chnlqus, Orlondo, |L, July 24-29, J994.
- ---. "Portlcl Anlmotlon ond Rndrlng slng Loto Porolll Computotlon."
[http.//www.korlslms.com/poprs/Portlcls5lggroph90.pdj Popr prsntd ot
5|GGRAPH '90. 1h J7th Annuol Conrnc on Computr Grophlcs ond |ntroctlv
1chnlqus, Lollos, 1X, August 6-J0, J990.
1h Notur o Cod [v005j
483
F1-#J F1-#J
2
A loglcol colculus o th ldos lmmlnnt ln nrvous
octlvlty [McCulloch/Plttsj
>>?
occlrotlon >W , ?T , KL , KW , #T> , #0L , #=#
Nwton's scond low KL
olgorlthms or ?T
ongulor, dtrmlnlng #0L
domplng #=#
orc occumulotlon ond KW
rototlon #T>
occlrotlon olgorlthms ?T , ?= , ?L
constont ?T
lntroctlv ?L
rondom ?=
octlon slctlon 0K0
octlvotlon unctlons o nurol ntworks >>W
Adoptot|on |n Notuto| ond Att|t|c|o| 5ystems
[Hollondj
=W0
odd[j unctlon [PVctor clossj == , =>
lmplmntotlon o =>
odd[j unctlon [Vc2 clossj #W?
odd|orc[j unctlon [toxlcllbsj 0?K
oddltlon oprotor ==
oddltlv blnd mod #NK
oddLocol[j unctlon [Vc2j #W?
oddPortlcl[j unctlon [toxlcllbsj 0>K
Al tot Gome Deve|opets [Bourg/5monnj >>?
A|got|thm|c Beouty ot l|onts, 7he [Pruslnklwlcz/
Llndnmoyrj
=NW
ollgnmnt [locklngj =TW , =##
lmplmntlng =##
olphobt [L-systm componntj =N=
omplltud ##L
onglBtwn[j unctlon [PVctor clossj =L
ongls #T# , #T0 , #T> , ##0
mosurlng ln dgrs #T#
mosurlng ln rodlons #T0
motlon #T>
thto [j ##0
Angry Blrds #WT
ongulor occlrotlon #0L
ongulor vloclty, osclllotlon wlth ##W
onomoly dtctlon >>L
onts, modllng or 0WW
opply|orc[j unctlon [Box2Lj 0=0
Arlstotl K>
ArroyLlst closs [Jovoj #>W , #?T , #?# , #?= , =KK
|trotor closs ond #?=
roctols ond =KK
gnrlcs, uslng #?T
rslzoblllty o #?#
orroys N , #?
|ndx
484
Lvy llghts, lmplmntlng wlth #?
custom dlstrlbutlons, crotlng wlth N
orroys [2Lj 0LL
orrlvlng bhovlor 0LT , 0L=
strlng orc ond 0L=
ortllclol lntlllgnc >>> , >>?
pottrn rcognltlon >>?
Att|t|c|o| lnte|||gence. A Modetn Apptooch [Russll/
Norvlgj
>>?
oton[j unctlon [Procsslngj ##T
oton2[j unctlon [Procsslngj ###
AttroctlonBhovlor closs [toxlcllbsj 0?K
outonomous ognts 0KT , 0K# , 0K0 , 0K= , 0LT ,
0L> , 0LK , 0N0 , 0NK , 0WN , =TK , =TN , =#L
octlon slctlon 0K0
orrlvlng bhovlor 0LT
comblnotlons =TK
complx systms ond 0WN
dslrd vloclty 0L>
dot product 0N0
lclncy =#L
locklng =TN
low lld ollowlng 0LK
ky componnts o 0K#
locomotlon 0K=
poth ollowlng 0NK
strlng 0K0
oxlom [L-systm componntj =N=
S
bockpropogotlon >KN
bglnContoct[j unctlon [PBox2Lj 0=?
bgln5hop[j unctlon [Procsslngj 0#L
bll curv ##
mon ond ##
blos lnput, prcptron >?T
Blg O Nototlon =#?
Blg O Nototlon N-5quord =#?
bln-lottlc spotlol subdlvlslon =#K
blnd mods #NK , #NL
oddltlv #NK
llst o #NL
body [Box2L lmntj #W> , #WN , #WW , 0TT , 0T0 ,
0#N
BodyL typ #WN
ottochlng lxtur lmnt to 0T0
bulldlng #WN
bullt sttlng or 0TT
lnltlol sttlngs or 0TT
multlpl shops ond 0#N
objct, crotlng 0TT
typs o #WW
body llsts, molntolnlng ln Procsslng 0T=
BodyL typ [body lmntj #WN , #WW , 0TW
51A1|C typ 0TW
conlgurlng #WW
bolds modl 0K#
bounclng boll sktch 0N , =?
lmplmntlng wlth vctors =?
boundorls 0TW , 0##
curvy 0##
lxd 0TW
Bourg, Lovld M. >>?
Box2L #WT , #W0 , #W> , #WK , 0TW , 0#? , 0#K , 0>#
|lslco #W0
JBox2L ond #W0
PBox2L hlpr closs #W0
PVctor vs. #W>
Procsslng ond #W0
complx orms ln 0#?
concov shops ond 0#K
coordlnot systm vs. Procsslng #WK
cor lmnts #W>
lxd objcts ln 0TW
ordr o vrtlcs 0#K
ovrhod wlth #WT
toxlcllbs vs. 0>#
usog #W0
Broltnbrg, Volntlno 0K0
brut orc mthod =W0
1h Notur o Cod [v005j
485
,
Contor st =?N , =K= , =NK
L-systms ond =NK
rcurslon ond =K=
Contor, Gorg =?N
Cortslon coordlnots ##0 , ##=
polor coordlnots, convrtlng rom ##=
Cotto, Lrln #WT
cllulor outomoton [outomotoj =0> , =0? , =0K ,
=0N , ==T , ==> , =>T , =>0 , =?# , =?0 , =?=
5lrplskl trlongl =0N
Wolrom olgorlthm or =0?
Wolrom clossllcotlon =>T
choroctrlstlcs o =0>
contlnuous =?0
dlnd =0>
lmntory =0?
lmntory, lmplmntlng ==T
hlstorlcol =?=
lmog procsslng =?0
movlng clls =?=
nstlng =?=
non-rctongulor grlds ond =?#
proboblllstlc =?0
rulsts, dlnlng ==>
sl-rpllcotlng clls =0>
tlm ond =0K
two-dlmnslonol =>0
vorlotlons o =?#
Choln5hop closs 0##
conlgurlng 0##
closs [Procsslngj 0 , = , >L
constructor = , >L
dlnd 0
unctlonollty =
cod dupllcotlon, lnhrltonc ond #K#
colclnt o rlctlon NT
mu [j NT
cohslon [locklngj =TW , =#0
lmplmntlng =#0
colllslons #WT , 0=> , 0=? , 0># , =T#
Box2L ond 0=>
ovoldlng ln group bhovlor =T#
bglnContoct[j unctlon [PBox2Lj 0=?
toxlcllbs ond 0>#
comblnotlons =TK
complx systms 0WN , 0WW , =TT , =0= , =>0 ,
>>K
Gom o Ll os =>0
cllulor outomoto =0=
comptltlon/cooprotlon componnt =TT
connctlonlst computotlonol systm >>K
dbock componnt =TT
group bhovlor =TT
ky prlnclpls o 0WW
non-llnorlty componnt 0WW
suprorgonlsms 0WW
Complxlty closs [Wolrom clossllcotlonj =>#
Computot|ono| Beouty ot Notute [|lokj =#>
connctd systms 0>W , 0?=
orc-dlrctd grophs 0?=
strlngs 0>W
connctlonlst computotlonol systm >>K
constroln[j unctlon [Procsslngj 0NT
constructor = , >L , L?
orgumnts, oddlng to L?
Contoct objcts [PBox2Lj 0=K
ContoctLlstnr closs [JBox2Lj 0=>
contlnuous [cllulor outomotoj =?0
controct[j unctlon [Procsslngj #>W
control [o physlcol objctsj >>L
Conwoy's Gom o Ll [Kllsj =>?
Conwoy, John =>0
coordlnot systms ##0 , #WK
Box2L vs. Procsslng #WK
Cortslon ##0
Procsslng ond ##0
polor ##0
coordPlxls1oWorld[j unctlon [PBox2Lj #WL
coordWorld1oPlxls[j unctlon [PBox2Lj #WN
Cornll Aronoutlcol Loborotory >>N
cos[j unctlon [Procsslngj ##=
cosln lookup tobls =#N
|ndx
486
Croyon Physlcs #WT
crotBody[j unctlon [PBox2Lj 0TT
crot|lxtur[j unctlon [PBox2Lj 0T0
cross[j unctlon [PVctor clossj =L
crossovr [noturol slctlon olgorlthmsj >TT , >TN
lmplmntlng >TN
.
domplng #=#
domplngRotlo sttlng [Box2L jolnt lmntj 00=
Lorwlnlon noturol slctlon =W>
dgrs #T# , #T=
rodlons, convrtlng to #T=
dlto wlght >?>
dnslty KL
drlvotlvs 0=N
Lscorts, Rn ##0
dslrd vloclty 0K> , 0L>
dstroyBody[j unctlon [PBox2Lj 0TN
dlrntlotlon 0=N
dlsslpotlv orc NT
dlst[j unctlon [PVctor clossj =L
dlstonc jolnts 000
LlstoncJolntL [Box2L jolnt typj 00=
dlstrlbutlons, custom #>
dlstrlbutlons, non-unlorm L , N , #> , #? , #K , #L
Mont Corlo mthod #K
Prlln nols #L
crotlng wlth orroys N
custom #>
proboblllty ond L
quollylng rondom volus #?
dlstrlbutlons, normol ##
dlv[j unctlon [PVctor clossj >#
dot product [PVctorj 0N0 , 0N= , 0N>
dlnd 0N=
thto 0N>
dot syntox =?
dot[j unctlon [PVctor clossj =L
drog orc N=
dynomlc [body typj #WW
I
cosystm slmulotlon gntlc olgorlthms =W0 , >=? ,
>=L , >=N , >=W
gnotyp >=N
llspons, vorylng >=L
phnotyp >=N
rproductlon >=W
slctlon >=W
lclncy =#? , =#K , =#L , =#N , =#W
Blg O Nototlon =#?
Blg O Nototlon N-5quord =#?
bln-lottlc spotlol subdlvlslon =#K
mog5q[j unctlon [PVctor clossj. =#N
sln/cosln lookup tobls =#N
tmporory objcts ond =#W
lmntory cllulor outomoto =0? , ==T , ==0 , ===
, ==K
drowlng ==K
dg coss ond ==0
gnrotlons, molntolnlng lntgrlty o ===
lmplmntlng ==T
mlttr #>K
ndContoct[j unctlon [PBox2Lj 0=?
nd5hop[j unctlon [Procsslngj 0#L
qulllbrlum K>
Luclld 0L , =??
Luclldon gomtry =?? , =?N
roctols ond =?N
Luclldon vctor 0L
Lulr lntgrotlon 0=W , 0>T
symplctlc Lulr [Box2Lj 0>T
Lulr, Lonhord 0=W
volutlon =WT , =W# , =W>
Lorwlnlon noturol slctlon =W>
gntlc olgorlthms =W#
modllng =WT
volutlonory computlng =W0
Lvolvd Vlrtuol Croturs [5lmsj >=T
xcluslv or [XORj >KK
xlt condltlons or rcurslon =K#
xpond[j unctlon [Procsslngj #>W
1h Notur o Cod [v005j
487
Lxplorlng Lmrgnc [Rsnlck/5llvrmonj =>?
xtnds kyword [Procsslngj #K>
G
octorlol =?W
d-orword modl [nurol ntworksj >>N , >L=
onlmotlng >L=
|lslco #W0
ltnss unctlons [noturol slctlon olgorlthmsj =WL ,
>#> , >#K , >#L , >0L , >0W , >=K
ovoldonc o obstocls ond >0L
dslgn your own >#K
cosystm slmulotlons ond >=K
volvlng or spcllc ottrlbuts >0W
xponntlol vs. llnor >#>
robotlc nslovmnt o humonlty ond >#L
lxtur [Box2L lmntj #W> , 0T# , 0T0
ottochlng to body lmnt 0T0
crotlng 0T#
|lok, Gory =#>
locklng =TN , =TW , =#? , =#K
bln-lottlc spotlol subdlvlslon =#K
prormonc ond =#?
ruls o =TW
|locks, Hrds, ond 5chools. A Llstrlbutd Bhovlorol
Modl [Rynoldsj
=TN
low lld ollowlng 0LK , 0LL
rsolutlon ond 0LL
luld rslstonc, modllng N=
or loops #?T
ArroyLlst objcts ond #?T
nhoncd #?T
orc occumulotlon KW
orc-dlrctd grophs 0?=
orcs K= , K> , KN , L# , L= , LL , LN , NT , N= ,
NW , #0L , #=# , #=> , #L= , #LN , 0=0 , 0KT , 0K=
Hook's low #=>
Nwton's lows o motlon K=
occumulotlon o KN
opply|orc[j unctlon 0=0
opplylng to objcts L#
opplylng to slngl objcts ln o systm #LN
outonomous ognts ond 0KT
crotlng L=
domplng #=#
dlnd K=
qulllbrlum K>
luld rslstonc N=
rlctlon, modllng NT
grovlty, modllng LL
modls o, bulldlng LN
portlcl systms wlth #L=
sprlngs #=>
strlng 0K=
trmlnol vloclty K>
trlgonomtry ond #0L
unlvrsol grovltotlonol constont NW
orcs, modllng LL
rol orcs LL
ormulo, voluotlng ln cod LW
ltocto| Geometty ot Notute, 7he [Mondlbrotj =?K
roctols =?? , =?K , =?L , =?N , =KK , =L> , =L? ,
=N0
Koch curv =KK
L-systms ond =N0
dlnd =?K
ln structur o =?N
rcurslon =?N
sl-rpllcotlng bhovlor o =?L
stochostlc =?N
tronsormotlon motrlx [Procsslngj =L?
trs ond =L>
rquncy [o osclllotlonsj ##W
rquncyHz sttlng [Box2L jolnt lmntj 00=
rlctlon LW , NT , N# , N= , N> , #=#
opplylng to on objct N>
colclnt o rlctlon NT
domplng #=#
dtrmlnlng dlrctlon/mognltud o NT
ormulo or LW
modllng wlth ormulo NT
mu [j NT
normol orc N#
|ndx
488
rho [j N=
unctlonollty =
unctlons ?>
stotlc vs. non-stotlc ?>
R
Golllo LL
Gom o Ll =0> , =>0 , =>= , =>>
drowlng =>>
ruls o =>=
Gordnr, Mortln =>0
Gouss, Corl |rldrlch ##
Gousslon dlstrlbutlon ##
gntlc olgorlthms =W# , =W0 , =W> , =W? , =WL ,
>TW , >#= , >#> , >0T , >=?
Lorwlnlon noturol slctlon =W>
5mort Rockts [1horpj >0T
bulldlng >TW
dlnd =W#
cosystm slmulotlon =W0 , >=?
ltnss olgorlthms, modlylng >#>
lntroctlv slctlon =W#
modlylng >#=
mutotlon rot, vorylng >#=
populotlon moxlmum, vorylng >#=
populotlons, crotlng =W?
purpos o =W0
slctlon, lmplmntlng =WL
trodltlonol =W#
gnotyp [noturol slctlon olgorlthmsj =W? , >#L ,
>=N
cosystm slmulotlon >=N
modlylng >#L
gomtrlc vctor 0L
gtAngl[j unctlon [PBox2Lj 0TL
gtBodyLlst[j unctlon [World clossj 0T=
gtBodyPlxlCoord[j unctlon [PBox2Lj 0TL
gtGroundBody[j unctlon [Box2L jolnt lmntj 00W
grovlty NN , NW , W> , #0N , 0>>
GrovltyBhovlor [toxlcllbsj 0>>
lmplmntlng modl o NW
modllng NN
modllng rollty vs. orbltrory volus #0N
modllng wlth trlgonomtry #0N
ploclng llmlts on modl o W>
unlvrsol grovltotlonol constont NW
GrovltyBhovlor closs [toxlcllbsj 0>>
grld [cllulor outomotoj =0>
group bhovlor =TT , =T# , =TK , =TN
colllslons, ovoldlng =T#
comblnotlons =TK
locklng =TN
]
hodlng2L[j unctlon [PVctor clossj =L , ##0
hrdlty [noturol slctlonj =W> , =WW , >TT , >T#
crossovr >TT
lmplmntlng =WW
mutotlon >T#
hlstorlcol [cllulor outomotoj =?=
Hodgln, Robrt #NK
Hollond, John =W0
Hook's low #=> , #=?
ormulo or xprsslng #=?
Hook, Robrt #=>
F
lmog procsslng [cllulor outomotoj =?0
lmog txturs #N= , #N> , #NK
P|mog objcts [Procsslngj #N>
PNG ormot ond #N>
blnd mods #NK
lnlnlt monky thorm =W0
lnhrltonc #>> , #KT , #K= , #K> , #K? , #KK
oddlng unctlonollty to suprcloss objcts #K?
xtnds kyword [Procsslngj #K>
lmplmntlng #KK
ovrrldlng suprcloss unctlons #K?
subcloss #K=
supr[j unctlon [Procsslngj #K>
1h Notur o Cod [v005j
489
suprclosss #K=
syntox or #K=
lntgrotlon 0=N , 0=W , 0>T
Lulr lntgrotlon 0=W
Rung-Kutto mthod 0>T
|ntroctlon wlth Groups o Autonomous Choroctrs
[Rynoldsj
=#K
lntroctlv slctlon gntlc olgorlthms =W# , >=# ,
>== , >=>
tlm log ond >=>
usr lntroctlon ond >==
lntrocs 0=>
ltrotlng #?0 , #?=
|trotor closs [Jovoj #?=
rmovlng lmnts ln or loops #?0
|trotor closs [Jovoj #?=
l1uns vlsuollzr #NK
a
Jovo #W0
JBox2L #W0 , #W? , 0=>
ContoctLlstnr closs 0=>
ull documntotlon or #W?
jolnt [Box2L lmntj #W> , 000 , 00? , 00N
dlstonc 000
mous typ 00N
rvolut typ 00?
f
klnmotlc [body typj #WW , 0=#
MousJolnts ond 0=#
Klls, 5tvn =>?
Koch curv =KK , =KW
lmplmntlng =KW
Kutto, M. W. 0>T
_
L-systms =N0 , =N= , =NK
componnts o =N=
tronslotlng lnto cod =NK
Loploc, Plrr-5lmon ##
Loploclon dlstrlbutlon ##
lornlng constont >??
leotn|ng ltocess|ng [5hlmonj #KT
lrp[j unctlon [PVctor clossj =L
llmlt[j unctlon [PVctor clossj =L , ?#
Llndnmoyr systms =N0
Llndnmoyr, Arlstld =N0 , =NW
llnorly sporobl problms >KK
locotlons =#
os vctors =#
lock[j unctlon [toxlcllbsj 0>L
locomotlon 0K=
Los Alomos Notlonol Loborotory =0>
Lucosllm Ltd. #>=
Lvy llght #> , #?
lmplmntlng wlth orroys #?
lmplmntlng wlth quollylng rondom volus #?
P
m_p vorlobl [Vc2 clossj 00T
mog[j unctlon [PVctor clossj >= , =#N
mog5q[j unctlon vs. =#N
Mogntosphr #NK
mognltud [o vctorsj >0 , ?#
llmltlng ?#
mog5q[j unctlon [PVctor clossj. =#N
Mondlbrot, Bnolt =?K
mop[j unctlon [Procsslngj 0T , ##L
osclllotlon ond ##L
Morxr, Rlcord #W0
moss KL , LT
modllng LT
unlts o mosurmnt, dlnlng LT
wlght vs. KL
motlng pools [noturol slctlonj =WL , >T?
crotlng =WL
|ndx
490
lmplmntlng >T?
McCulloch, Worrn 5. >>?
mon ##
mthods, stotlc vs. non-stotlc ?>
mlllls[j unctlon [Procsslngj ##L
Monstr curv =KL
Mont Corlo mthod #K
motlon >? , #T> , ##0
ongulor #T>
hodlng2L[j unctlon [PVctor clossj ##0
mous jolnt [Box2L jolnt typj 00N
st1ronsorm[j unctlon 00N
mous jolnt [Box2L Jolnt typj 00N
movlng clls [cllulor outomotoj =?=
mu [j ## , NT
mult[j unctlon [PVctor clossj >T
lmplmntotlon >T
mutotlon [noturol slctlon olgorlthmsj >T# , >TW
lmplmntlng >TW
rot o >T#
%
noturol roctols =L>
noturol phnomno 0 , L , #L , KL , LT , L= , LL ,
LN , NT , N= , NN , NW , #0L , #0N , #N? , 0KT , 0WW ,
=TT , =TN , =0> , =?? , =L> , =N0 , =N= , =WT , =W#
, =W> , >=?
Lorwlnlon noturol slctlon =W>
L-systms ond =N0
Nwton's scond low, modllng KL
Prlln nols ond #L
onts, modllng 0WW
outonomous ognts 0KT
cllulor outomoto =0>
cosystms, modllng >=?
volutlon =WT
locklng =TN
luld rslstonc, modllng N=
orcs, modllng L= , LL
roctols =??
rlctlon NT
gntlc olgorlthms =W#
grovlty LL , NN , NW
group bhovlor =TT
moss, modllng LT
modllng rollty vs. orbltrory volus #0N
modllng wlth rondom wolks 0
modllng wlth th rondom[j unctlon L
physlcs [rol worldj, modllng LN
plvots, modllng #0L
plont growth, modllng =N=
smok, modllng wlth portlcl systms #N?
trs ond =L>
noturol slctlon olgorlthms =W> , =W? , =WL , =WN ,
=WW
ltnss unctlons =WL
motlng pools, crotlng =WL
populotlons, crotlng =W?
proboblllty =WN
rproductlon =WW
noturolly ordrd squnc o numbrs #L
nlghborhood [cllulor outomotoj =0?
nstlng [cllulor outomotoj =?=
nurol ntworks >>> , >>? , >>K , >>L , >>N , >>W ,
>KL , >KN , >L= , >L?
octlvotlon unctlons o >>W
onlmotlng >L=
bockpropogotlon >KN
connctlonlst computotlonol systm >>K
dlogrommlng >KN
lornlng ond >>K
ntworks o prcptrons >KL
pottrn rcognltlon >>?
prcptron >>N
rol vs. slmulotd >L?
rlnorcmnt lornlng >>L
suprvlsd lornlng >>K
unsuprvlsd lornlng >>L
uss o >>L
New k|nd ot 5c|ence, A [Wolromj =0?
nw oprotor [objctsj >
Nwton's lrst low K> , K?
PVctor closs ond K?
Nwton's scond low KL
1h Notur o Cod [v005j
49J
Nwton's thlrd low K? , KK
PVctor closs ond KK
Nwton, |sooc K=
nxtGousslon[j unctlon [Rondom clossj #=
doult mon/stondord dvlotlon sttlngs o #=
nols[j unctlon [Procsslngj #N
orgumnts or #N
nolsLtoll[j unctlon [Procsslngj #N
non-llnorly sporobl problms >KK
non-rctongulor grlds [cllulor outomotoj =?#
non-unlorm dlstrlbutlons L , N , #> , #? , #K , #L
Mont Corlo mthod #K
Prlln nols #L
crotlng wlth orroys N
custom #>
proboblllty ond L
quollylng rondom volus #?
normol dlstrlbutlon ##
normol orc N#
normol polnts 0W# , 0W?
srls o, or poth ollowlng 0W?
normollzotlon >= , =WN
motlng pools, crotlng wlth =WN
normollz[j unctlon [PVctor clossj >>
Norvlg, Ptr >>?
Y
objct 0 , > , W0 , =>W
clls ln cllulor outomoto os =>W
dlnd 0
lntroctlon btwn W0
nw oprotor >
objct-orlntd progrommlng 0 , =? , L0 , #=L ,
#>> , #?? , #KT , #KN , #LK , =>W , >#W
cllulor outomoto ond =>W
closs 0
closss o usr-dlnd objcts, crotlng #??
dot syntox =?
gnotyp/phnotyp objcts ond >#W
lnhrltonc #>> , #KT
lnstoncs o subclosss, crotlng #KN
molntolnlng ncopsulotlon #LK
objct 0
polymorphlsm #>> , #KT , #KN
rrncs to vs. copls o objcts L0
rvlw o 0
structurs, choslng btwn #=L
optlmlzotlon =#N , =#W
mog5q[j unctlon [PVctor clossj. =#N
sln/cosln lookup tobls =#N
tmporory objcts ond =#W
osclllotlon ##K , ##L , ##W , #0T , #00 , #0>
omplltud ##L
ongulor vloclty ond ##W
rquncy o ##W
on two oxs #0T
prlod ##L
slmpl hormonlc motlon ##L
slmulotlng wlth sln curvs ##K
vorylng #0>
wovs #00
ovrsompllng #>
9
portlcl systms #>= , #>> , #>? , #>K , #>W , #?? ,
#?K , #?L , #LT , #L= , #LN , #N? , 0>T , 0>K
ArroyLlst, uslng #>W
Vrlt lntgrotlon ond 0>T
oddPortlcl[j unctlon [toxlcllbsj 0>K
opplylng orc to slngl portlcls ln #LN
closs or, crotlng #??
dod portlcls, chcklng or #>K
mlttr #>K
orcs ond #L=
llspon o portlcls #>K
multlpl systms, orgonlzlng #?L
orlgln polnt [o portlclsj #?K
portlcls ln #>?
polymorphlsm, uslng #LT
purpos o #>>
smok, modllng #N?
|ndx
492
portlcls #>? , #>K , #>L , #LN , 0>> , 0>?
VrltPortlcl2L objct [toxlcllbsj 0>?
opplylng orc to slngl portlcls ln #LN
doth, chcklng or #>K
llspon o #>K
tstlng #>L
toxlcllbs lmplmntotlon o 0>>
poth 0NK
poth ollowlng 0NK , 0NN , 0W# , 0W0 , 0W>
currnt dlstonc rom poth, lndlng 0NN
multlpl sgmnts 0W>
normol polnts 0W#
pothlndlng vs. 0NK
torgt, dtrmlnlng 0W0
pothlndlng 0NK
pottrn rcognltlon >>? , >?T
prcptron ond >?T
PBox2L hlpr closs #W0 , #WK , #WL , 0TL
coordlnot systms, convrtlng btwn #WL
crotWorld[j unctlon #WK
gtBodyPlxlCoord[j unctlon [PBox2Lj 0TL
prcptron >>N , >?T , >?? , >?K , >KT , >KK ,
>KL
blos lnput >?T
rror colculotlons ond >?T
lmplmntlng >>N
lornlng constont >??
llnorly sporobl problms ond >KK
ntworks o >KL
pottrn rcognltlon wlth >?T
strlng ond >KT
trolnlng >?K
prormonc =#? , =#K , =#L , =#N , =#W
Blg O Nototlon =#?
Blg O Nototlon N-5quord =#?
bln-lottlc spotlol subdlvlslon =#K
mog5q[j unctlon [PVctor clossj. =#N
sln/cosln lookup tobls =#N
tmporory objcts ond =#W
prlod ##L , #00
dlnd ln plxls rothr thon roms #00
Prlln nols #L , #N , 0T , 00 , 0LW
low lld ollowlng ond 0LW
mop[j unctlon 0T
noturol phnomno, modllng wlth #L
nols[j unctlon [Procsslngj #N
two-dlmnslonol 00
phnotyp [noturol slctlon olgorlthmsj =W? , >#L ,
>=N
cosystm slmulotlon >=N
physlcs LN , #NW , #WT
colllslons #WT
modllng LN
opn-sourc llbrorls or #NW
physlcs llbrorls #NW , #WT
Box2L #WT
pl [nj #T=
P| vorlobl [Procsslngj #T=
P|mog objcts [Procsslngj #N>
Pltts, Woltr >>?
plvots, modllng #0L
plont growth, modllng =N=
PNG grophlc ll ormot #N>
polor coordlnots ##0 , ##=
Cortslon coordlnots, convrtlng to ##=
Polygon5hop closs 0#?
os llst o vctors 0#?
polymorphlsm #>> , #KT , #KN , #LT
crotlng objct lnstoncs wlth #LT
popMotrlx[j unctlon [Procsslngj =L?
populotlons [gntlc olgorlthmsj =W? , >T0 , >=?
crotlng =W?
cosystm slmulotlons ond >=?
lmnts o =W?
lmplmntlng >T0
post5olv[j unctlon [PBox2Lj 0=?
pr5olv[j unctlon [PBox2Lj 0=?
proboblllstlc [cllulor outomotoj =?0
proboblllty L , N , ## , =?0 , =W0 , =WN
cllulor outomoto bosd on =?0
lnlnlt monky thorm =W0
mon ##
noturol slctlon olgorlthms ond =WN
non-unlorm dlstrlbutlons ond L
1h Notur o Cod [v005j
493
normol dlstrlbutlons ##
stondord dvlotlon ##
proboblllty o th lttst L
Procsslng 0 , #0 , #N , =T , >K , ?> , #T0 , #T= ,
##T , ### , ##0 , ##L , #K= , #N= , #N> , #W0 , #WK ,
0T= , 0T? , 0>#
Box2L ond #W0
Box2L objcts, oddlng to projcts 0T?
JBox2L #W0
OOP onlln tutorlol >K
P|mog objcts #N>
Rondom closs #0
ongls, mosurlng ln #T0
oton[j unctlon ##T
oton2[j unctlon ###
body llsts, molntolnlng 0T=
closs lnhrltonc, syntox or #K=
coordlnot systms ond ##0
coordlnot systms vs. Box2L #WK
lncorporotlng lmogs lnto projcts #N=
mosurlng tlm ln ##L
nols[j unctlon #N
nolsLtoll[j unctlon #N
rodlons[j unctlon #T=
rvlw o objct-orlntd progrommlng wlth 0
rototlon tutorlol #T=
stotlc vs. non-stotlc mthods ?>
toxlcllbs ond 0>#
vctors ond =T
Pruslnklwlcz, Przmysow =NW
psudo-rondom numbrs L , #L
Prlln nols ond #L
pushMotrlx[j unctlon [Procsslngj =L?
PVctor closs [Procsslngj =T , =L , =N , >T , ># ,
>= , >> , ?# , K? , KK , ##0 , #W>
Box2L vs. #W>
Nwton's lrst low ond K?
Nwton's thlrd low ond KK
dlv[j unctlon >#
unctlon llst or =L
hodlng2L[j unctlon ##0
llmlt[j unctlon ?#
mog[j unctlon >=
mothmotlcol unctlons or =L
mult[j unctlon >T
normollz[j unctlon >>
sub[j unctlon =N
Pythogoros >0
Pythogoron thorm >0
h
quollylng rondom volus #? , #K
Mont Corlo mthod #K
H
rodlons #T0 , #T=
convrtlng rom dgrs #T=
rodlons[j unctlon [Procsslngj #T=
Rondom closs [Procsslngj #0 , #=
nxtGousslon[j unctlon #=
Rondom closs [Wolrom clossllcotlonj =>#
rondom numbr gnrotors = , K , L , #>
custom dlstrlbutlons, crotlng #>
non-unlorm dlstrlbutlons, crotlng L
psudo-rondom numbrs L
rondom[j unctlon =
unlorm numbr dlstrlbutlons ond K
rondom wolks # , #>
Gousslon #>
Lvy llght #>
ovrsompllng #>
rondom[j unctlon = , L , N
noturol phnomno, modllng wlth L
non-unlorm dlstrlbutlons, crotlng wlth N
rondom2L[j unctlon [PVctor clossj =L
rondom3L[j unctlon [PVctor clossj =L
rol orcs LL
rcurslon =?N , =?W , =K# , =KK
ArroyLlst objcts ond =KK
xlt condltlons =K#
octorlol =?W
|ndx
494
lmplmntlng =?W
Rvs, Wllllom 1. #>=
rlnorcmnt lornlng [nurol ntworksj >>L
rlnorcmnt lornlng[nurol ntworksj >K=
rmov[j unctlon [ArroyLlst clossj #?#
Rptltlon closs [Wolrom clossllcotlonj =>T
rproductlon [noturol slctlon olgorlthmsj =WW , >TL
, >=W
cosystm slmulotlon >=W
lmplmntlng >TL
rpulslon =T0
group bhovlor ond =T0
Rsnlck, Mltchl 0K0 , =>?
rsolutlon, low lld ollowlng ond 0LL
rst lngth [Box2L jolnt lmntj 00=
rvolut jolnt typ [Box2Lj 00? , 00K
proprtls, conlgurlng 00K
RvolutJolntL objct [Box2L jolnt lmntj 00K
Rynolds, Crolg 0K# , 0NK
poth ollowlng olgorlthm 0NK
rho [j N=
Rosnblott, |ronk >>N
rotot[j unctlon [PBox2Lj 0TL
rotot[j unctlon [PVctor clossj =L
rototlon #T> , #TW
polntlng towords movmnt #TW
roultt whl proboblllty mthod =WN
ruls [L-systm componntj =N=
rulsts or cllulor outomoto ==>
Rung, C. 0>T
Rung-Kutto mthod 0>T
Russll, 5tuort J. >>?
O
scolor nototlon, vs. vctor nototlon ==
scolor projctlon 0W#
scolorPlxls1oWorld[j unctlon [PBox2Lj #WN
scolorWorld1oPlxls[j unctlon [PBox2Lj #WN
5chmldt, Korstn 0>#
5monn, Glnn >>?
slctlon [noturol slctlon olgorlthmsj =W> , =WL ,
>T> , >=W
cosystm slmulotlon >=W
lmplmntlng =WL , >T>
sl-rpllcotlng clls =0>
sl-slmllorlty o roctols =?L
sporotlon [locklngj =TW , =#T
lmplmntlng =#T
stGrovlty[j unctlon [World clossj #WK
st1ronsorm[j unctlon [Box2Lj 00N
5hop [Box2L lmntj 0TT , 0T# , 00T
dlnlng 0T#
rlctlon ottrlbut 0TT
locol posltlon or 00T
rstltutlon ottrlbut 0TT
shop [Box2L lmntj #W>
shops #T> , ##0 , ##=
dlsploylng ##0
movlng wlth polor coordlnots ##=
rototlng #T>
short rong rlotlonshlps 0WW , =#T
complx systms 0WW
locklng bhovlor ond =#T
5lrplskl trlongl =0N
5lrplskl, Wocow =0N
slgmo [oj ##
slgnol procsslng >>L
5llvrmon, Brlon =>?
slmpl hormonlc motlon ##L
5lms, Korl >=T
sln[j unctlon [Procsslngj ##=
sln lookup tobls =#N
slz[j unctlon [ArroyLlst clossj #?0
5mort Rockts [1horpj >0T
sot snsors >>L
sohcohtoo #TN
spllc[j unctlon [Procsslngj #>W
sprlngs #=> , #=? , #=K , 0>K , 0>L
Hook's low #=>
VrltConstrolnd5prlng closs [toxlcllbsj 0>K
VrltMlnLlstonc5prlng closs [toxlcllbsj 0>K
Vrlt5prlng closs [toxlcllbsj 0>K
1h Notur o Cod [v005j
495
dlrctlon o orc, dtrmlnlng #=K
lock[j unctlon [toxlcllbsj 0>L
mognltud o orc, dtrmlnlng #=?
rst lngth #=K
toxlcllbs ond 0>K
stondord dvlotlon ## , #0
colculotlng #0
vorlonc #0
5tor 1rk ||. 1h Wroth o Khon [J982j #>=
stot [cllulor outomotoj =0>
stotlc [body typj #WW , 0TW
stotlc unctlons ??
strlng bhovlors 0L> , 0LK , =T0 , >KT
low lld ollowlng 0LK
group bhovlor ond =T0
prcptron or >KT
wondrlng 0L>
5trlng Bhovlors or Autonomous Choroctrs
[Rynoldsj
0K0
strlng orc 0K0 , 0K> , 0KK , 0L=
orrlvlng bhovlor ond 0L=
dslrd vloclty 0K>
mognltud o 0KK
strlng prcptron >KT , >K=
rlnorcmnt lornlng[nurol ntworksj >K=
stp[j unctlon [Box2Lj 0T?
stochostlc roctols =?N , =L>
trs os =L>
5trlngBur closs =N?
strlngs 0?# , =N?
5trlngBur closs vs. =N?
honglng rom lxd polnts 0?#
sub[j unctlon [PVctor clossj =N
subcloss #K= , #K?
oddlng unctlonollty to suprcloss objcts #K?
subst[j unctlon [Procsslngj #>W
supr[j unctlon[Procsslngj #K>
suprclosss #K= , #K? , #KW , #LT
oddlng unctlonollty wlthln subclosss #K?
ovrrldlng unctlons rom #K? , #LT
polymorphlsm ond #KW
suprorgonlsms 0WW
suprvlsd lornlng [nurol ntworksj >>K
symplctlc Lulr [Box2Lj 0>T
!
tongnt ##T , ### , ##0
oton[j unctlon [orctongntj ##T
oton2[j unctlon ###
hodlng2L[j unctlon [PVctor clossj ##0
trmlnol vloclty K>
thto 0N>
dot product ond 0N>
thto [j ##0
1horp, Jr >0T
tlm ##L , =0K
cllulor outomoto ond =0K
mlllls[j unctlon, mosurlng wlth ##L
tlm srls prdlctlon >>L
toxlcllbs 0># , 0>0 , 0>> , 0>K , 0>W , 0?= , 0?K
AttroctlonBhovlor closs 0?K
Box2L vs. 0>#
VrltPhyslcs closs 0>>
VrltPhyslcs2L closs 0>>
ottroctlon/rpulslon bhovlors ond 0?K
connctd systms 0>W
downloodlng 0>0
orc-dlrctd grophs 0?=
portlcls, lmplmntlng ln 0>>
sprlngs 0>K
world, bulldlng 0>>
trodltlonol gntlc olgorlthms =W#
tronsormotlon motrlx [Procsslngj =L?
1ronsormotlons tutorlol [Procsslngj =L?
tronslot[j unctlon [PBox2Lj 0TL
trs =L>
trlgonomtry #TN , ##T , ##= , #0L
oton[j unctlon ##T
cos[j unctlon [Procsslngj ##=
orcs ond #0L
sln[j unctlon [Procsslngj ##=
sohcohtoo #TN
|ndx
496
tongnt ##T
1ron [J982j #L
1urtl grophlcs =NK
7utt|es, 7etm|tes, ond 7tott|c !oms [Rsnlckj 0K0
two-dlmnslonol cllulor outomoto =>0 , =>?
lmplmntlng =>?
i
lom, 5tonlsow =0>
unlorm numbr dlstrlbutlons K
nlormlty closs [Wolrom clossllcotlonj =>T
unlt vctors >=
unlvrsol grovltotlonol constont NW
unsuprvlsd lornlng [nurol ntworksj >>L
updot[j unctlon [toxlcllbsj 0>>
Q
vorlonc #0
vorlotlon [noturol slctlonj =W>
Vc2 [Box2L lmntj #W> , #W?
oddlng vctors wlth #W?
monltud, lndlng #W?
multlplylng vctors wlth #W?
normollzlng vctors #W?
scollng vctors wlth #W?
Vc2L [toxlcllbs typj 0>= , 0>K
VrltPortlcl2L closs ond 0>K
moth unctlons or 0>=
Vc3L [toxlcllbs typj 0>=
vctor nototlon, vs. scolor nototlon ==
vctors 0L , 0N , =T , =# , == , =W , >T , >0 , >= ,
>? , >W , #TW , ##T , #W> , 0LN , 0N0
Procsslng ond =T
Vc2 [Box2L lmntj #W>
occlrotlon >W
oddlng ==
os rlght trlongls #TW
ossoclotlv/dlstrlbutlv ruls or multlpllcotlon/
dlvlslon o
>0
bounclng boll sktch 0N
commutotlv/ossoclotlv ruls o oddltlon/
subtroctlon wlth
=W
dlnd 0L
dot product 0N0
low llds, computlng or 0LN
locotlons ond =#
mognltud >0
motlon, lmplmntlng wlth ==
multlplylng >T
normollzotlon >=
nototlon 0L
scollng >T
tongnt ##T
unlt vctors >=
vloclty ond =# , >?
Veh|c|es. lxpet|ments |n 5ynthet|c lsycho|ogy
[Broltnbrgj
0K0
vloclty =# , >? , >W , ?# , 0L>
occlrotlon >W
os vctor =#
dslrd, or outonomous ognts 0L>
llmltlng ?#
Vrlt lntgrotlon 0>T , 0>#
toxlcllbs 0>#
VrltConstrolnd5prlng closs [toxlcllbsj 0>K
VrltMlnLlstonc5prlng closs [toxlcllbsj 0>K
VrltPortlcl2L objct [toxlcllbsj 0>?
VrltPhyslcs closs [toxlcllbsj 0>0 , 0>>
cor lmnts o 0>0
VrltPhyslcs2L closs [toxlcllbsj 0>>
Vrlt5prlng closs [toxlcllbsj 0>K
vlscous orc N=
von Numonn, John =0>
M
wondrlng bhovlor [Rynoldsj 0L>
wovs #00 , #0>
ongulor vloclty, dlnlng wlth #00
vorylng #0>
1h Notur o Cod [v005j
497
wlght KL , >>K
moss vs. KL
nurol ntworks ond >>K
whl o ortun proboblllty mthod =WN
Wolrom clossllcotlon =>T , =>#
Complxlty closs =>#
Rondom closs =>#
Rptltlon closs =>T
nlormlty closs =>T
Wolrom, 5tphn =0? , =>T
Wolrom clossllcotlon =>T
lmntory cllulor outomoto olgorlthm =0?
World closs [Box2Lj #W> , #WK , 0T=
crotWorld[j unctlon [PBox2Lj #WK
gtBodyLlst[j unctlon 0T=
j
XOR [xcluslv orj >KK
|ndx
498

You might also like