You are on page 1of 12



'7UDQVIRUPDWLRQV?3URFHVVLQJRUJ

2D Transformations
- 'DYLG (LVHQEHUJ
'RZQORDGWKHILOHVIURPWKLVWXWRULDO

Processinghasbuiltinfunctionsthatmakeiteasyforyoutohaveobjectsinasketchmove,spin,andgroworshrink.
ThistutorialwillintroduceyoutotheWUDQVODWH ,URWDWH ,andVFDOH functionssothatyoucanusetheminyour
sketches.

Translation: Moving the Grid


Asyouknow,yourProcessingwindowworkslikeapieceofgraphpaper.Whenyouwanttodrawsomething,youspecify
itscoordinatesonthegraph.HereisasimplerectangledrawnwiththecodeUHFW  .Thecoordinate
system(afancywordforgraphpaper)isshowningray.

Ifyouwanttomovetherectangle60unitsrightand80unitsdown,youcanjustchangethecoordinatesbyaddingto
the[and\startingpoint:UHFW  andtherectanglewillappearinadifferentplace.(We
putthearrowintherefordramaticeffect.)

Butthereisamoreinterestingwaytodoit:movethegraphpaperinstead.Ifyoumovethegraphpaper60units
KWWSVSURFHVVLQJRUJWXWRULDOVWUDQVIRUPG





'7UDQVIRUPDWLRQV?3URFHVVLQJRUJ

rightand80unitsdown,youwillgetexactlythesamevisualresult.Movingthecoordinatesystemiscalledtranslation.

Theimportantthingtonoticeintheprecedingdiagramisthat,asfarastherectangleisconcerned,ithasntmovedatall.
Itsupperleftcornerisstillat(20,20).Whenyouusetransformations,thethingsyoudrawQHYHUchangepositionthe
coordinatesystemdoes.
Hereiscodethatdrawstherectangleinredbychangingitscoordinates,thendrawsitinbluebymovingthegrid.The
rectanglesaretranslucentsothatyoucanseethattheyare(visually)atthesameplace.Onlythemethodusedtomove
themhaschanged.CopyandpastethiscodeintoProcessingandgiveitatry.
YRLGVHWXS
^
VL]H  
EDFNJURXQG  
QR6WURNH 
GUDZWKHRULJLQDOSRVLWLRQLQJUD\
ILOO  
UHFW  

GUDZDWUDQVOXFHQWUHGUHFWDQJOHE\FKDQJLQJWKHFRRUGLQDWHV
ILOO  
UHFW  

GUDZDWUDQVOXFHQWEOXHUHFWDQJOHE\WUDQVODWLQJWKHJULG
ILOO  
SXVK0DWUL[ 
WUDQVODWH  
UHFW  
SRS0DWUL[ 
`

Letslookatthetranslationcodeinmoredetail.SXVK0DWUL[ isabuiltinfunctionthatsavesthecurrentpositionof
thecoordinatesystem.TheWUDQVODWH  movesthecoordinatesystem60unitsrightand80unitsdown.
TheUHFW  drawstherectangleatthesameplaceitwasoriginally.Remember,thethingsyoudraw
dontmovethegridmovesinstead.Finally,SRS0DWUL[ restoresthecoordinatesystemtothewayitwasbeforeyou
didthetranslate.
Yes,youcouldhavedoneaWUDQVODWH  tomovethegridbacktoitsoriginalposition.However,whenyou
startdoingmoresophisticatedoperationswiththecoordinatesystem,itseasierto
useSXVK0DWUL[ andSRS0DWUL[ tosaveandrestorethestatusratherthanhavingtoundoallyouroperations.Later
oninthistutorial,youwillfindoutwhythosefunctionsseemtohavesuchstrangenames.

KWWSVSURFHVVLQJRUJWXWRULDOVWUDQVIRUPG





'7UDQVIRUPDWLRQV?3URFHVVLQJRUJ

Whats the Advantage?


Youmaybethinkingthatpickingupthecoordinatesystemandmovingitisalotmoretroublethanjustaddingto
coordinates.Forasimpleexampleliketherectangle,youarecorrect.Butletstakeanexampleof
whereWUDQVODWH canmakelifeeasier.Hereissomecodethatdrawsarowofhouses.Itusesaloopthatcallsfunction
namedKRXVH ,whichtakesthe[and\locationofthehousesupperleftcornerasitsparameters.

YRLGVHWXS
^
VL]H  
EDFNJURXQG  
IRU LQWL LL L
^
KRXVH L 
`
`

Thisisthecodefordrawingthehousebychangingitsposition.Lookatalltheadditionsthatyouhavetokeeptrackof.
YRLGKRXVH LQW[LQW\
^
WULDQJOH [\[\[\ 
UHFW [\ 
UHFW [\ 
`

ComparethattotheversionofthefunctionthatusesWUDQVODWH .Inthiscase,thecodedrawsthehouseinthesame
placeeverytime,withitsupperleftcornerat(0,0),andletstranslationdoalltheworkinstead.
YRLGKRXVH LQW[LQW\
^
SXVK0DWUL[ 
WUDQVODWH [\ 
WULDQJOH  
UHFW  
UHFW  
SRS0DWUL[ 
`

Rotation
Inadditiontomovingthegrid,youcanalsorotateitwiththeURWDWH function.Thisfunctiontakesoneargument,
whichisthenumberofUDGLDQVthatyouwanttorotate.InProcessing,allthefunctionsthathavetodowithrotation
measureanglesinradiansratherthandegrees.Whenyoutalkaboutanglesindegrees,yousaythatafullcirclehas360.
Whenyoutalkaboutanglesinradians,yousaythatafullcirclehas2radians.HereisadiagramofhowProcessing
measuresanglesindegrees(black)andradians(red).

KWWSVSURFHVVLQJRUJWXWRULDOVWUDQVIRUPG





'7UDQVIRUPDWLRQV?3URFHVVLQJRUJ

Sincemostpeoplethinkindegrees,ProcessinghasabuiltinUDGLDQV functionwhichtakesanumberofdegreesasits
argumentandconvertsitforyou.ItalsohasaGHJUHHV functionthatconvertsradianstodegrees.Giventhat
background,letstryrotatingasquareclockwise45degrees.
YRLGVHWXS
^
VL]H  
EDFNJURXQG  
VPRRWK 
ILOO  
QR6WURNH 
UHFW  

SXVK0DWUL[ 
URWDWH UDGLDQV  
ILOO  
UHFW  
SRS0DWUL[ 
`

Hey,whathappened?Howcomethesquaregotmovedandcutoff?Theansweris:thesquaredidnotmove.Thegridwas
rotated.Hereiswhatreallyhappened.Asyoucansee,ontherotatedcoordinatesystem,thesquarestillhasitsupperleft
cornerat(40,40).

Rotating the Correct Way


Thecorrectwaytorotatethesquareisto:
A.Translatethecoordinatesystemsorigin(0,0)towhereyouwanttheupperleftofthesquaretobe.

KWWSVSURFHVVLQJRUJWXWRULDOVWUDQVIRUPG





'7UDQVIRUPDWLRQV?3URFHVVLQJRUJ

B.Rotatethegrid/4radians(45)
C.Drawthesquareattheorigin.

Andhereisthecodeanditsresult,withoutthegridmarks.
YRLGVHWXS
^
VL]H  
EDFNJURXQG  
VPRRWK 
ILOO  
QR6WURNH 
UHFW  

SXVK0DWUL[ 
PRYHWKHRULJLQWRWKHSLYRWSRLQW
WUDQVODWH  

WKHQSLYRWWKHJULG
URWDWH UDGLDQV  

DQGGUDZWKHVTXDUHDWWKHRULJLQ
ILOO  
UHFW  
SRS0DWUL[ 
`

Andhereisaprogramthatgeneratesawheelofcolorsbyusingrotation.Thescreenshotisreducedtosavespace.
YRLGVHWXS ^
VL]H  
EDFNJURXQG  
VPRRWK 
QR6WURNH 
`
YRLGGUDZ ^
LI IUDPH&RXQW  ^
ILOO IUDPH&RXQW IUDPH&RXQW 
IUDPH&RXQW  
SXVK0DWUL[ 
WUDQVODWH  
URWDWH UDGLDQV IUDPH&RXQW  
UHFW  
SRS0DWUL[ 
`
`
KWWSVSURFHVVLQJRUJWXWRULDOVWUDQVIRUPG





'7UDQVIRUPDWLRQV?3URFHVVLQJRUJ

Scaling
Thefinalcoordinatesystemtransformationisscaling,whichchangesthesizeofthegrid.Takealookatthisexample,
whichdrawsasquare,thenscalesthegridtotwiceitsnormalsize,anddrawsitagain.
YRLGVHWXS
^
VL]H  
EDFNJURXQG  

VWURNH  
UHFW  

VWURNH  
SXVK0DWUL[ 
VFDOH  
UHFW  
SRS0DWUL[ 
`

First,youcanseethatthesquareappearstohavemoved.Ithasnt,ofcourse.Itsupperleftcornerisstillat(20,20)on
thescaledupgrid,butthatpointisnowtwiceasfarawayfromtheoriginasitwasintheoriginalcoordinatesystem.You
canalsoseethatthelinesarethicker.Thatsnoopticalillusionthelinesreallyaretwiceasthick,becausethe
coordinatesystemhasbeenscaledtodoubleitssize.
ProgrammingChallenge:Scaleuptheblacksquare,butkeepitsupperleftcornerinthesameplace
asthegraysquare.Hint:useWUDQVODWH tomovetheorigin,thenuseVFDOH .
Thereisnolawsayingthatyouhavetoscalethe[and\dimensionsequally.TryusingVFDOH  tomake
the[dimensionthreetimesitsnormalsizeandthe\dimensiononlyhalfitsnormalsize.

Order Matters
Whenyoudomultipletransformations,theordermakesadifference.Arotationfollowedbyatranslatefollowedbya
scalewillnotgivethesameresultsasatranslatefollowedbyarotatebyascale.Hereissomesamplecodeandthe
results.
YRLGVHWXS
^
VL]H  
EDFNJURXQG  
VPRRWK 
OLQH  GUDZD[HV
OLQH  

SXVK0DWUL[ 
ILOO  UHGVTXDUH
URWDWH UDGLDQV  
WUDQVODWH  
VFDOH  
UHFW  
SRS0DWUL[ 
SXVK0DWUL[ 
ILOO  ZKLWHVTXDUH
WUDQVODWH  
URWDWH UDGLDQV  
KWWSVSURFHVVLQJRUJWXWRULDOVWUDQVIRUPG





'7UDQVIRUPDWLRQV?3URFHVVLQJRUJ

VFDOH  
UHFW  
SRS0DWUL[ 
`

The Transformation Matrix


Everytimeyoudoarotation,translation,orscaling,theinformationrequiredtodothetransformationisaccumulated
intoatableofnumbers.Thistable,ormatrixhasonlyafewrowsandcolumns,yet,throughthemiracleofmathematics,
itcontainsalltheinformationneededtodoanyseriesoftransformations.Andthatswhy
theSXVK0DWUL[ andSRS0DWUL[ havethatwordintheirname.

Push and Pop


What,abouttheSXVKandSRSpartofthenames?Thesecomefromacomputerconceptknownasastack,whichworks
likeaspringloadedtraydispenserinacafeteria.Whensomeonereturnsatraytothestack,itsweightpushesthe
platformdown.Whensomeoneneedsatray,hetakesitfromthetopofthestack,andtheremainingtrayspopupalittle
bit.
Inasimilarmanner,SXVK0DWUL[ putsthecurrentstatusofthecoordinatesystematthetopofamemoryarea,
andSRS0DWUL[ pullsthatstatusbackout.TheprecedingexampleusedSXVK0DWUL[ andSRS0DWUL[ tomake
surethatthecoordinatesystemwascleanbeforeeachpartofthedrawing.Inalloftheotherexamples,thecallsto
thosetwofunctionswerentreallynecessary,butitdoesnthurtanythingtosaveandrestorethegridstatus.
Note:inProcessing,thecoordinatesystemisrestoredtoitsoriginalstate(originattheupperleftofthewindow,no
rotation,andnoscaling)everytimethattheGUDZ functionisexecuted.

Threedimensional Transforms
Ifyouareworkinginthreedimensions,youcancalltheWUDQVODWH functionwiththreeargumentsforthe[,\,
and]distances.Similarly,youcancallVFDOH withthreeargumentsthattellhowmuchyouwantthegridscaledin
eachofthosedimensions.
Forrotation,calltheURWDWH; ,URWDWH< ,orURWDWH= functiontorotatearoundeachoftheaxes.Allthreeof
thesefunctionsexpectoneargument:thenumberofradianstorotate.

Case Study: An ArmWaving Robot


Letsusethesetransformationstoanimateabluerobotwavingitsarms.Ratherthantrytowriteitallatonce,wewilldo
theworkinstages.Thefirststepistodrawtherobotwithoutanyanimation.
Therobotismodeledonthisdrawing,althoughitwillnotlookascharming.First,wedrawtherobotsothatitsleftand
topsidetouchthe[and\axes.ThatwillallowustouseWUDQVODWH toeasilyplacetherobotanywherewewantorto
makemultiplecopiesoftherobot,aswedidintheexampleofthehouses.
Whenwerefertoleftandrightinthisdrawing,wemeanyourleftandright(theleftandrightsideofyourmonitor),not
KWWSVSURFHVVLQJRUJWXWRULDOVWUDQVIRUPG





'7UDQVIRUPDWLRQV?3URFHVVLQJRUJ

therobotsleftandright.
YRLGVHWXS
^
VL]H  
EDFNJURXQG  
VPRRWK 
GUDZ5RERW 
`
YRLGGUDZ5RERW
^
QR6WURNH 
ILOO  
UHFW  KHDG
UHFW  ERG\
UHFW  OHIWDUP
UHFW  ULJKWDUP

UHFW  OHIWOHJ
UHFW  ULJKWOHJ

ILOO  
HOOLSVH  OHIWH\H
HOOLSVH  ULJKWH\H
`

Thenextstepistoidentifythepointswherethearmspivot.Thatisshowninthisdrawing.Thepivot
pointsare(12,32)and(66,32).Note:thetermcenterofrotationisamoreformaltermforthepivot
point.
Now,separatethecodefordrawingtheleftandrightarms,andmovethecenterofrotationforeacharmtotheorigin,
becauseyoualwaysrotatearoundthe(0,0)point.Tosavespace,wearenotrepeatingthecodeforVHWXS .
YRLGGUDZ5RERW
^
QR6WURNH 
ILOO  
UHFW  KHDG
UHFW  ERG\
GUDZ/HIW$UP 
GUDZ5LJKW$UP 
UHFW  OHIWOHJ
UHFW  ULJKWOHJ

ILOO  
HOOLSVH  OHIWH\H
HOOLSVH  ULJKWH\H
`
YRLGGUDZ/HIW$UP
^
SXVK0DWUL[ 
WUDQVODWH  
UHFW  
SRS0DWUL[ 
`
YRLGGUDZ5LJKW$UP
^
SXVK0DWUL[ 
WUDQVODWH  
UHFW  
SRS0DWUL[ 
`
KWWSVSURFHVVLQJRUJWXWRULDOVWUDQVIRUPG





'7UDQVIRUPDWLRQV?3URFHVVLQJRUJ

Nowtesttoseeifthearmsrotateproperly.Ratherthanattemptafullanimation,wewilljustrotatetheleftsidearm135
degreesandtherightsidearm45degreesasatest.Hereisthecodethatneedstobeadded,andtheresult.Theleftside
armiscutoffbecauseofthewindowboundaries,butwellfixthatinthefinalanimation.
YRLGGUDZ/HIW$UP
^
SXVK0DWUL[ 
WUDQVODWH  
rotate(radians(135))
UHFW  OHIWDUP
SRS0DWUL[ 
`
YRLGGUDZ5LJKW$UP
^
SXVK0DWUL[ 
WUDQVODWH  
rotate(radians(45))
UHFW  ULJKWDUP
SRS0DWUL[ 
`

Nowwecompletetheprogrambyputtingintheanimation.Theleftarmhastorotatefrom0to135andback.Sincethe
armwavingissymmetric,therightarmanglewillalwaysbethenegativevalueoftheleftarmangle.Tomakethings
simple,wewillgoinincrementsof5degrees.
LQWDUP$QJOH 
LQWDQJOH&KDQJH 
ILQDOLQW$1*/(B/,0,7 
YRLGVHWXS
^
VL]H  
VPRRWK 
IUDPH5DWH  
`
YRLGGUDZ
^
EDFNJURXQG  
SXVK0DWUL[ 
WUDQVODWH  SODFHURERWVRDUPVDUHDOZD\VRQVFUHHQ
GUDZ5RERW 
DUP$QJOH DQJOH&KDQJH

LIWKHDUPKDVPRYHGSDVWLWVOLPLW
UHYHUVHGLUHFWLRQDQGVHWZLWKLQOLPLWV
LI DUP$QJOH!$1*/(B/,0,7__DUP$QJOH
^
DQJOH&KDQJH DQJOH&KDQJH
DUP$QJOH DQJOH&KDQJH
`
SRS0DWUL[ 
`
YRLGGUDZ5RERW
^
QR6WURNH 
ILOO  
UHFW  KHDG
UHFW  ERG\
GUDZ/HIW$UP 
GUDZ5LJKW$UP 
KWWSVSURFHVVLQJRUJWXWRULDOVWUDQVIRUPG





'7UDQVIRUPDWLRQV?3URFHVVLQJRUJ

UHFW  OHIWOHJ


UHFW  ULJKWOHJ

ILOO  
HOOLSVH  OHIWH\H
HOOLSVH  ULJKWH\H
`
YRLGGUDZ/HIW$UP
^
SXVK0DWUL[ 
WUDQVODWH  
URWDWH UDGLDQV DUP$QJOH 
UHFW  OHIWDUP
SRS0DWUL[ 
`
YRLGGUDZ5LJKW$UP
^
SXVK0DWUL[ 
WUDQVODWH  
URWDWH UDGLDQV DUP$QJOH 
UHFW  ULJKWDUP
SRS0DWUL[ 
`

Case Study: Interactive Rotation


Insteadofhavingthearmsmoveontheirown,wewillmodifytheprogramsothatthearmsfollowthemousewhilethe
mousebuttonispressed.Insteadofjustwritingtheprogramatthekeyboard,wefirstthinkabouttheproblemandfigure
outwhattheprogramneedstodo.
Sincethetwoarmsmoveindependentlyofoneanother,weneedtohaveonevariableforeacharmsangle.Itseasyto
figureoutwhicharmtotrack.Ifthemouseisattheleftsideoftherobotscenter,tracktheleftarmotherwise,trackthe
rightarm.
Theremainingproblemistofigureouttheangleofrotation.Giventhepivotpointpositionandthemouseposition,how
doyoudeterminetheangleofalineconnectingthosetwopoints?TheanswercomesfromtheDWDQ function,which
gives(inradians)theangleofalinefromtheorigintoagiven\and[coordinate.Inconstrasttomostotherfunctions,
the\coordinatecomesfirst.DWDQ returnsavaluefromtoradians,whichistheequivalentof180to180.
Butwhataboutfindingtheangleofalinethatdoesntstartfromtheorigin,suchasthelinefrom(10,37)to(48,59)?No
problemitsthesameastheangleofalinefrom(0,0)to(4810,5937).Ingeneral,tofindtheangleofthelinefrom
([0,\0)to([1 ,\1 ),calculate
DWDQ \ \ [ [ 

Becausethisisanewconcept,ratherthanintegrateitintotherobotprogram,youshouldwriteasimpletestprogramto
seethatyouunderstandhowDWDQ works.Thisprogramdrawsarectanglewhosecenterofrotationisitsupperleft
cornerat(100,100)andtracksthemouse.
YRLGVHWXS
^
VL]H  
`
YRLGGUDZ
^
KWWSVSURFHVVLQJRUJWXWRULDOVWUDQVIRUPG





'7UDQVIRUPDWLRQV?3URFHVVLQJRUJ

IORDWDQJOH DWDQ PRXVH<PRXVH; 



EDFNJURXQG  
SXVK0DWUL[ 
WUDQVODWH  
URWDWH DQJOH 
UHFW  
SRS0DWUL[ 
`

Thatworksgreat.Whathappensifwedrawtherectanglesoitistallerthanitiswide?Changetheprecedingcodeto
readUHFW  .Howcomeitdoesntseemtofollowthemouseanymore?Theansweristhattherectangle
reallyLVstillfollowingthemouse,butitstheshortsideoftherectanglethatdoesthefollowing.Oureyesaretrainedto
wantthelongsidetobetracked.Becausethelongsideisata90degreeangletotheshortside,youhavetosubtract90
(or/2radians)togetthedesiredeffect.ChangetheprecedingcodetoreadURWDWH DQJOH+$/)B3, andtryit
again.SinceProcessingdealsalmostexclusivelyinradians,thelanguagehasdefinedthe
constants3, (180),+$/)B3, (90),48$57(5B3, (45)and7:2B3, (360)foryourconvenience.
Atthispoint,wecanwritethefinalversionofthearmtrackingprogram.Westartoffwithdefinitionsofconstantsand
variables.Thenumber39inthedefinitionof0,'32,17B; comesfromthefactthatthebodyoftherobotstartsat[
coordinate14andis50pixelswide,so39(14+25)isthehorizontalmidpointoftherobotsbody.
 :KHUHXSSHUOHIWRIURERWDSSHDUVRQVFUHHQ 
ILQDOLQW52%27B; 
ILQDOLQW52%27B< 
 7KHURERW
VPLGSRLQWDQGDUPSLYRWSRLQWV 
ILQDOLQW0,'32,17B; 
ILQDOLQW/()7B3,927B; 
ILQDOLQW5,*+7B3,927B; 
ILQDOLQW3,927B< 
IORDWOHIW$UP$QJOH 
IORDWULJKW$UP$QJOH 
YRLGVHWXS
^
VL]H  
VPRRWK 
IUDPH5DWH  
`

TheGUDZ functionisnext.Itdeterminesifthemouseispressedandtheanglebetweenthemouselocationandthe
pivotpoint,settingOHIW$UP$QJOH andULJKW$UP$QJOH accordingly.
YRLGGUDZ
^

 7KHVHYDULDEOHVDUHIRUPRXVH;DQGPRXVH<
 DGMXVWHGWREHUHODWLYHWRWKHURERW
VFRRUGLQDWHV\VWHP
 LQVWHDGRIWKHZLQGRZ
VFRRUGLQDWHV\VWHP
 
IORDWP;
IORDWP<

EDFNJURXQG  
SXVK0DWUL[ 
WUDQVODWH 52%27B;52%27B< SODFHURERWVRDUPVDUHDOZD\VRQVFUHHQ
LI PRXVH3UHVVHG
^
P; PRXVH;52%27B;
P< PRXVH<52%27B<
KWWSVSURFHVVLQJRUJWXWRULDOVWUDQVIRUPG





'7UDQVIRUPDWLRQV?3URFHVVLQJRUJ

LI P;0,'32,17B; OHIWVLGHRIURERW


^
OHIW$UP$QJOH DWDQ P<3,927B<P;/()7B3,927B;
+$/)B3,
`
HOVH
^
ULJKW$UP$QJOH DWDQ P<3,927B<P;5,*+7B3,927B;
+$/)B3,
`
`
GUDZ5RERW 

SRS0DWUL[ 
`

TheGUDZ5RERW functionremainsunchanged,butaminorchangetoGUDZ/HIW$UP andGUDZ5LJKW$UP isnow


necessary.BecauseOHIW$UP$QJOH andULJKW$UP$QJOH arenowcomputedinradians,thefunctionsdonthavetodoany
conversion.Thechangestothetwofunctionsareinbold.
YRLGGUDZ/HIW$UP
^
SXVK0DWUL[ 
WUDQVODWH  
rotate(leftArmAngle)
UHFW  OHIWDUP
SRS0DWUL[ 
`
YRLGGUDZ5LJKW$UP
^
SXVK0DWUL[ 
WUDQVODWH  
rotate(rightArmAngle)
UHFW  ULJKWDUP
SRS0DWUL[ 
`

KWWSVSURFHVVLQJRUJWXWRULDOVWUDQVIRUPG



You might also like