This repository has been archived by the owner on Jun 25, 2019. It is now read-only.
/
01_vectors.html
1498 lines (1089 loc) · 71.9 KB
/
01_vectors.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<section data-type="chapter" id="_chapter_1_vectors">
<h1>Chapter 1. Vectors</h1>
<blockquote data-type="epigraph">
<p>“Roger, Roger. What’s our vector, Victor?”</p>
<p data-type="attribution">— Captain Oveur (Airplane)</p>
</blockquote>
<a data-primary="vectors" data-type="indexterm"></a>
<p>This book is all about looking at the world around us and coming up with clever ways to simulate that world with code. Divided into three parts, the book will start by looking at basic physics—how an apple falls from a tree, a pendulum swings in the air, the earth revolves around the sun, etc. Absolutely everything contained within the first five chapters of this book requires the use of the most basic building block for programming motion—the <strong><em>vector</em></strong>. And so this is where we begin our story.</p>
<a data-primary="Euclid" data-type="indexterm"></a> <a data-primary="Euclidean vector" data-type="indexterm"></a> <a data-primary="geometric vector" data-type="indexterm"></a> <a data-primary="vectors" data-secondary="defined" data-type="indexterm"></a>
<p>Now, the word vector can mean a lot of different things. Vector is the name of a New Wave rock band formed in Sacramento, CA in the early 1980s. It’s the name of a breakfast cereal manufactured by Kellogg’s Canada. In the field of epidemiology, a vector is used to describe an organism that transmits infection from one host to another. In the C++ programming language, a vector (std::vector) is an implementation of a dynamically resizable array data structure. While all these definitions are interesting, they’re not what we’re looking for. What we want is called a <strong><em>Euclidean vector</em></strong> (named for the Greek mathematician Euclid and also known as a geometric vector). When you see the term “vector” in this book, you can assume it refers to a Euclidean vector, defined as <em>an entity that has both magnitude and direction</em>.</p>
<a data-primary="vectors" data-secondary="notation" data-type="indexterm"></a>
<p>A vector is typically drawn as a arrow; the direction is indicated by where the arrow is pointing, and the magnitude by the length of the arrow itself.</p>
<figure id="chapter01_figure1"><img alt="Figure 1.1" src="chapter01/ch01_01.png" />
<figcaption>Figure 1.1A vector (drawn as an arrow) has magnitude (length of arrow) and direction (which way it is pointing).</figcaption>
</figure>
<p>In the above illustration, the vector is drawn as an arrow from point A to point B and serves as an instruction for how to travel from A to B.</p>
<section data-type="sect1" id="chapter01_section1">
<h2>1.1 Vectors, You Complete Me</h2>
<a data-primary="bouncing ball sketch" data-type="indexterm"></a> <a data-primary="vectors" data-secondary="bouncing ball sketch" data-type="indexterm"></a>
<p>Before we dive into more of the details about vectors, let’s look at a basic Processing example that demonstrates why we should care about vectors in the first place. If you’ve read any of the introductory Processing textbooks or taken a class on programming with Processing (and hopefully you’ve done one of these things to help prepare you for this book), you probably, at one point or another, learned how to write a simple bouncing ball sketch.</p>
<figure class="screenshot" data-pde="processingjs/chapter01/_1_1_bouncingball_novectors/_1_1_bouncingball_novectors.pde"><img alt="" src="chapter01/ch01_ex01.png" />
<figcaption>If you are reading this book as a PDF or in print, then you will only see screenshots of the code. Motion, of course, is a key element of our discussion, so to the extent possible, the static screenshots will include trails to give a sense of the behavior. For more about how to draw trails, see the code examples available for download.</figcaption>
</figure>
<div data-type="example"><h5>Example 1.1: Bouncing ball with no vectors</h5></div>
<pre data-code-language="java" data-type="programlisting" class="codesplit">
// Variables for location and speed of ball.
float x = 100;
float y = 100;
float xspeed = 1;
float yspeed = 3.3;
// {!4} Remember how Processing works? setup() is executed once when the sketch starts and draw() loops forever and ever (until you quit).
void setup() {
size(640,360);
background(255);
}
void draw() {
background(255);
// Move the ball according to its speed.
x = x + xspeed;
y = y + yspeed;
// {!6} Check for bouncing.
if ((x > width) || (x < 0)) {
xspeed = xspeed * -1;
}
if ((y > height) || (y < 0)) {
yspeed = yspeed * -1;
}
stroke(0);
fill(175);
// Display the ball at the location (x,y).
ellipse(x,y,16,16);
}</pre>
<p>In the above example, we have a very simple world—a blank canvas with a circular shape (a “ball”) traveling around. This ball has some properties, which are represented in the code as variables.</p>
<div data-type="note">
<dl>
<dt>Location</dt>
<dd>
<p><em>x and y</em></p>
</dd>
<dt>Speed</dt>
<dd>
<p><em>xspeed and yspeed</em></p>
</dd>
</dl>
</div>
<p>In a more advanced sketch, we could imagine having many more variables:</p>
<div data-type="note">
<dl>
<dt>Acceleration</dt>
<dd>
<p><em>xacceleration and yacceleration</em></p>
</dd>
<dt>Target location</dt>
<dd>
<p><em>xtarget and ytarget</em></p>
</dd>
<dt>Wind</dt>
<dd>
<p><em>xwind and ywind</em></p>
</dd>
<dt>Friction</dt>
<dd>
<p><em>xfriction and yfriction</em></p>
</dd>
</dl>
</div>
<p>It’s becoming clearer that for every concept in this world (wind, location, acceleration, etc.), we’ll need two variables. And this is only a two-dimensional world. In a 3D world, we’ll need <span class="var">x</span>, <span class="var">y</span>, <span class="var">z</span>, <span class="var">xspeed</span>, <span class="var">yspeed</span>, <span class="var">zspeed</span>, and so on.</p>
<p>Wouldn’t it be nice if we could simplify our code and use fewer variables?</p>
<p>Instead of:</p>
<pre data-code-language="java" data-type="programlisting">
float x;
float y;
float xspeed;
float yspeed;</pre>
<p>We could simply have…</p>
<pre data-code-language="java" data-type="programlisting">
Vector location;
Vector speed;</pre>
<p>Taking this first step in using vectors won’t allow us to do anything new. Just adding vectors won’t magically make your Processing sketches simulate physics. However, they will simplify your code and provide a set of functions for common mathematical operations that happen over and over and over again while programming motion.</p>
<p>As an introduction to vectors, we’re going to live in two dimensions for quite some time (at least until we get through the first several chapters). All of these examples can be fairly easily extended to three dimensions (and the class we will use—<span class="klass">PVector</span><code>—</code>allows for three dimensions.) However, it’s easier to start with just two.</p>
</section>
<section data-type="sect1" id="chapter01_section2">
<h2>1.2 Vectors for Processing Programmers</h2>
<a data-primary="Processing" data-secondary="vectors and" data-type="indexterm"></a> <a data-primary="PVector class (Processing)" data-type="indexterm"></a> <a data-primary="vectors" data-secondary="Processing and" data-type="indexterm"></a>
<p>One way to think of a vector is the difference between two points. Consider how you might go about providing instructions to walk from one point to another.</p>
<p>Here are some vectors and possible translations:</p>
<figure id="chapter01_figure2"><img alt="Figure 1.2" src="chapter01/ch01_02.png" />
<figcaption>Figure 1.2</figcaption>
</figure>
<div data-type="note">
<dl>
<dt>(-15, 3)</dt>
<dd>
<p><em>Walk fifteen steps west; turn and walk three steps north.</em></p>
</dd>
<dt>(3, 4)</dt>
<dd>
<p><em>Walk three steps east; turn and walk five steps north.</em></p>
</dd>
<dt>(2, -1)</dt>
<dd>
<p><em>Walk two steps east; turn and walk one step south.</em></p>
</dd>
</dl>
</div>
<p>You’ve probably done this before when programming motion. For every frame of animation (i.e. a single cycle through Processing’s <span class="function">draw()</span> loop), you instruct each object on the screen to move a certain number of pixels horizontally and a certain number of pixels vertically.</p>
<figure id="chapter01_figure3"><img alt="Figure 1.3" src="chapter01/ch01_03.png" />
<figcaption>Figure 1.3</figcaption>
</figure>
<p>For every frame:</p>
<p><strong><em>new location = velocity applied to current location</em></strong></p>
<a data-primary="locations" data-secondary="as vectors" data-type="indexterm"></a> <a data-primary="vectors" data-secondary="locations and" data-type="indexterm"></a> <a data-primary="vectors" data-secondary="velocity and" data-type="indexterm"></a> <a data-primary="velocity" data-secondary="as vector" data-type="indexterm"></a>
<p>If velocity is a vector (the difference between two points), what is location? Is it a vector too? Technically, one might argue that location is not a vector, since it’s not describing how to move from one point to another—it’s simply describing a singular point in space.</p>
<p>Nevertheless, another way to describe a location is the path taken from the origin to reach that location. Hence, a location can be the vector representing the difference between location and origin.</p>
<figure id="chapter01_figure4"><img alt="Figure 1.4" src="chapter01/ch01_04.png" />
<figcaption>Figure 1.4</figcaption>
</figure>
<p>Let’s examine the underlying data for both location and velocity. In the bouncing ball example, we had the following:</p>
<div data-type="note">
<dl>
<dt>location</dt>
<dd>
<p><em>x,y</em></p>
</dd>
<dt>velocity</dt>
<dd>
<p><em>xspeed,yspeed</em></p>
</dd>
</dl>
</div>
<p>Notice how we are storing the same data for both—two floating point numbers, an <span class="var">x</span> and a <span class="var">y</span>. If we were to write a vector class ourselves, we’d start with something rather basic:</p>
<pre data-code-language="java" data-type="programlisting">
class PVector {
float x;
float y;
PVector(float x_, float y_) {
x = x_;
y = y_;
}
}</pre>
<p>At its core, a <span class="klass">PVector</span> is just a convenient way to store two values (or three, as we’ll see in 3D examples).</p>
<p>And so this …</p>
<pre data-code-language="java" data-type="programlisting">
float x = 100;
float y = 100;
float xspeed = 1;
float yspeed = 3.3;</pre>
<p>becomes …</p>
<pre data-code-language="java" data-type="programlisting">
PVector location = new PVector(100,100);
PVector velocity = new PVector(1,3.3);</pre>
<a data-primary="vectors" data-secondary="motion" data-tertiary="implementing with" data-type="indexterm"></a>
<p>Now that we have two vector objects (location and velocity), we’re ready to implement the algorithm for motion—<strong><em>location = location + velocity</em></strong>. In Example 1.1, without vectors, we had:</p>
<pre data-code-language="java" data-type="programlisting">
//[full] Add each speed to each location.
x = x + xspeed;
y = y + yspeed;
//[end]</pre>
<p>In an ideal world, we would be able to rewrite the above as:</p>
<pre data-code-language="java" data-type="programlisting">
// Add the velocity vector to the location vector.
location = location + velocity;</pre>
<a data-primary="addition operator" data-type="indexterm"></a>
<p>However, in Processing, the addition operator + is reserved for primitive values (integers, floats, etc.) only. Processing doesn’t know how to add two <span class="klass">PVector</span> objects together any more than it knows how to add two <span class="klass">PFont</span> objects or <span class="klass">PImage</span> objects. Fortunately for us, the <span class="klass">PVector</span> class includes functions for common mathematical operations.</p>
</section>
<section data-type="sect1" id="chapter01_section3">
<h2>1.3 Vector Addition</h2>
<a data-primary="add() function (PVector class)" data-type="indexterm"></a> <a data-primary="vectors" data-secondary="adding" data-type="indexterm"></a>
<p>Before we continue looking at the <span class="klass">PVector</span> class and its <span class="function">add()</span> method (purely for the sake of learning since it’s already implemented for us in Processing itself), let’s examine vector addition using the notation found in math and physics textbooks.</p>
<a data-primary="scalar notation" data-secondary="vs. vector notation" data-type="indexterm"></a> <a data-primary="vector notation" data-secondary="vs. scalar notation" data-type="indexterm"></a>
<p>Vectors are typically written either in boldface type or with an arrow on top. For the purposes of this book, to distinguish a <strong><em>vector</em></strong> from a <strong><em>scalar</em></strong> (<em>scalar</em> refers to a single value, such as an integer or a floating point number), we’ll use the arrow notation:</p>
<ul>
<li>
<p>Vector: $$\vec{v}$$</p>
</li>
<li>
<p>Scalar: {x}</p>
</li>
</ul>
<p>Let’s say I have the following two vectors:</p>
<figure id="chapter01_figure5"><img alt="Figure 1.5" src="chapter01/ch01_05.png" />
<figcaption>Figure 1.5</figcaption>
</figure>
<p>Each vector has two components, an <span class="var">x</span> and a <span class="var">y</span>. To add two vectors together, we simply add both <span class="var">x</span><code>’</code>s and both <span class="var">y</span><code>’</code>s.</p>
<figure id="chapter01_figure6"><img alt="Figure 1.6" src="chapter01/ch01_06.png" />
<figcaption>Figure 1.6</figcaption>
</figure>
<p>In other words:</p>
<p>{wuplusv}</p>
<p>can be written as:</p>
<p>{wxuxplusvx}<br />
{wyuyplusvy}</p>
<p>Then, replacing <span class="var">u</span> and <span class="var">v</span> with their values from Figure 1.6, we get:</p>
<p>{wx53}<br />
{wy24}</p>
<p>which means that:</p>
<p>{wx8} {wy6}</p>
<p>Finally, we write that as a vector:</p>
<p>{w86}</p>
<a data-primary="add() function (PVector class)" data-secondary="implementation of" data-type="indexterm"></a>
<p>Now that we understand how to add two vectors together, we can look at how addition is implemented in the <span class="klass">PVector</span> class itself. Let’s write a function called <span class="function">add()</span> that takes another <span class="klass">PVector</span> object as its argument.</p>
<pre data-code-language="java" data-type="programlisting">
class PVector {
float x;
float y;
PVector(float x_, float y_) {
x = x_;
y = y_;
}
//[full] New! A function to add another PVector to this PVector. Simply add the <em>x</em> components and the <em>y</em> components together.
void add(PVector v) { //[bold]
y = y + v.y; //[bold]
x = x + v.x; //[bold]
} //[bold]
//[end]
}</pre>
<a data-primary="bouncing ball sketch" data-secondary="implementing with vectors" data-type="indexterm"></a>
<p>Now that we see how <span class="function">add()</span> is written inside of <span class="klass">PVector</span>, we can return to our bouncing ball example with its <strong><em>location + velocity</em></strong> algorithm and implement vector addition:</p>
<pre data-code-language="java" data-type="programlisting">
// Add the current velocity to the location.
location = location + velocity; //[line-through]
location.add(velocity);</pre>
<p>And here we are, ready to rewrite the bouncing ball example using <span class="klass">PVector</span>.</p>
<a data-primary="dot syntax" data-type="indexterm"></a> <a data-primary="object-oriented programming" data-secondary="dot syntax" data-type="indexterm"></a>
<div data-type="example"><h5>Example 1.2: Bouncing ball with PVectors!</h5></div>
<pre data-code-language="java" data-type="programlisting">
//[full] Instead of a bunch of floats, we now just have two PVector variables.
PVector location; //[bold]
PVector velocity; //[bold]
//[end]
void setup() {
size(640,360);
location = new PVector(100,100); //[bold]
velocity = new PVector(2.5,5); //[bold]
}
void draw() {
background(255);
location.add(velocity); //[bold]
//[full] 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.
if ((location.x > width) || (location.x < 0)) { //[bold]
velocity.x = velocity.x * -1; //[bold]
} //[bold]
if ((location.y > height) || (location.y < 0)) { //[bold]
velocity.y = velocity.y * -1; //[bold]
} //[bold]
//[end]
stroke(0);
fill(175);
ellipse(location.x,location.y,16,16); //[bold]
}</pre>
<p>Now, you might feel somewhat disappointed. After all, this may initially appear to have made the code more complicated than the original version. While this is a perfectly reasonable and valid critique, it’s important to understand that we haven’t fully realized the power of programming with vectors just yet. Looking at a simple bouncing ball and only implementing vector addition is just the first step. As we move forward into a more complex world of multiple objects and multiple <strong><em>forces</em></strong> (which we’ll introduce in Chapter 2), the benefits of <span class="klass">PVector</span> will become more apparent.</p>
<p>We should, however, note an important aspect of the above transition to programming with vectors. Even though we are using <span class="klass">PVector</span> objects to describe two values—the <span class="var">x</span> and <span class="var">y</span> of location and the <span class="var">x</span> and <span class="var">y</span> of velocity—we still often need to refer to the <em>x</em> and <em>y</em> components of each <span class="klass">PVector</span> individually. When we go to draw an object in Processing, there’s no means for us to say:</p>
<pre data-code-language="java" data-type="programlisting">
ellipse(location,16,16); //[line-through]</pre>
<p>The <span class="function">ellipse()</span> function does not allow for a <span class="klass">PVector</span> as an argument. An ellipse can only be drawn with two scalar values, an <span class="var">x</span>-coordinate and a <span class="var">y</span>-coordinate. And so we must dig into the <span class="klass">PVector</span> object and pull out the <em>x</em> and <em>y</em> components using object-oriented dot syntax.</p>
<pre data-code-language="java" data-type="programlisting">
ellipse(location.x,location.y,16,16);</pre>
<p>The same issue arises when testing if the circle has reached the edge of the window, and we need to access the individual components of both vectors: <span class="var">location</span> and <span class="var">velocity</span>.</p>
<pre data-code-language="java" data-type="programlisting">
if ((location.x > width) || (location.x < 0)) {
velocity.x = velocity.x * -1;
}</pre>
<div data-type="exercise" id="chapter01_exercise1">
<h5>Exercise 1.1</h5>
<p>Find something you’ve previously made in Processing using separate <span class="var">x</span> and <span class="var">y</span> variables and use <span class="klass">PVector</span><code>s</code> instead.</p>
</div>
<div data-type="exercise" id="chapter01_exercise2">
<h5>Exercise 1.2</h5>
<p>Take one of the walker examples from the introduction and convert it to use <span class="klass">PVector</span><code>s</code>.</p>
</div>
<div data-type="exercise" id="chapter01_exercise3">
<h5>Exercise 1.3</h5>
<p>Extend the bouncing ball with vectors example into 3D. Can you get a sphere to bounce around a box?</p>
</div>
</section>
<section data-type="sect1" id="chapter01_section4">
<h2>1.4 More Vector Math</h2>
<p>Addition was really just the first step. There are many mathematical operations that are commonly used with vectors. Below is a comprehensive list of the operations available as functions in the <span class="klass">PVector</span> class. We’ll go through a few of the key ones now. As our examples get more sophisticated in later chapters, we’ll continue to reveal the details of more functions.</p>
<a data-primary="PVector class (Processing)" data-secondary="mathematical functions for" data-type="indexterm"></a> <a data-primary="angleBetween() function (PVector class)" data-type="indexterm"></a> <a data-primary="cross() function (PVector class)" data-type="indexterm"></a> <a data-primary="dist() function (PVector class)" data-type="indexterm"></a> <a data-primary="dot() function (PVector class)" data-type="indexterm"></a> <a data-primary="heading() function (PVector class)" data-type="indexterm"></a> <a data-primary="lerp() function (PVector class)" data-type="indexterm"></a> <a data-primary="limit() function (PVector class)" data-type="indexterm"></a> <a data-primary="PVector class (Processing)" data-secondary="function list for" data-type="indexterm"></a> <a data-primary="random2D() function (PVector class)" data-type="indexterm"></a> <a data-primary="random3D() function (PVector class)" data-type="indexterm"></a> <a data-primary="rotate() function (PVector class)" data-type="indexterm"></a>
<ul>
<li>
<p><span class="function">add()</span> — add vectors</p>
</li>
<li>
<p><span class="function">sub()</span> — subtract vectors</p>
</li>
<li>
<p><span class="function">mult()</span> — scale the vector with multiplication</p>
</li>
<li>
<p><span class="function">div()</span> — scale the vector with division</p>
</li>
<li>
<p><span class="function">mag()</span> — calculate the magnitude of a vector</p>
</li>
<li>
<p><span class="function">setMag()</span> - set the magnitude of a vector</p>
</li>
<li>
<p><span class="function">normalize()</span> — normalize the vector to a unit length of 1</p>
</li>
<li>
<p><span class="function">limit()</span> — limit the magnitude of a vector</p>
</li>
<li>
<p><span class="function">heading()</span> — the 2D heading of a vector expressed as an angle</p>
</li>
<li>
<p><span class="function">rotate()</span> — rotate a 2D vector by an angle</p>
</li>
<li>
<p><span class="function">lerp()</span> — linear interpolate to another vector</p>
</li>
<li>
<p><span class="function">dist()</span> — the Euclidean distance between two vectors (considered as points)</p>
</li>
<li>
<p><span class="function">angleBetween()</span> — find the angle between two vectors</p>
</li>
<li>
<p><span class="function">dot()</span> — the dot product of two vectors</p>
</li>
<li>
<p><span class="function">cross()</span> — the cross product of two vectors (only relevant in three dimensions)</p>
</li>
<li>
<p><span class="function">random2D()</span> - make a random 2D vector</p>
</li>
<li>
<p><span class="function">random3D()</span> - make a random 3D vector</p>
</li>
</ul>
<p>Having already covered addition, let’s start with subtraction. This one’s not so bad; just take the plus sign and replace it with a minus!</p>
<section data-type="sect2" id="_vector_subtraction">
<h2>Vector subtraction</h2>
<a data-primary="PVector class (Processing)" data-secondary="sub() function" data-type="indexterm"></a> <a data-primary="sub() function (PVector class)" data-type="indexterm"></a>
<p>{wuminusv}</p>
<p>can be written as:</p>
<p>{wxuxminusvx}<br />
{wyuyminusvy}</p>
<figure id="chapter01_figure7"><img alt="Figure 1.7: Vector Subtraction" src="chapter01/ch01_07.png" />
<figcaption>Figure 1.7: Vector Subtraction </figcaption>
</figure>
<p>and so the function inside <span class="klass">PVector</span> looks like:</p>
<pre data-code-language="java" data-type="programlisting">
void sub(PVector v) {
x = x - v.x;
y = y - v.y;
}</pre>
<p>The following example demonstrates vector subtraction by taking the difference between two points—the mouse location and the center of the window.</p>
<figure class="screenshot" data-pde="processingjs/chapter01/_1_3_vector_subtraction/_1_3_vector_subtraction.pde"><img alt="ch01 ex03" src="chapter01/ch01_ex03.png" />
<figcaption> </figcaption>
</figure>
<div data-type="example"><h5>Example 1.3: Vector subtraction</h5></div>
<pre data-code-language="java" data-type="programlisting">
void setup() {
size(640,360);
}
void draw() {
background(255);
//[full] Two PVectors, one for the mouse location and one for the center of the window
PVector mouse = new PVector(mouseX,mouseY);
PVector center = new PVector(width/2,height/2);
//[end]
// PVector subtraction!
mouse.sub(center);
// Draw a line to represent the vector.
translate(width/2,height/2);
line(0,0,mouse.x,mouse.y);
}</pre>
<a data-primary="vectors" data-secondary="commutative/associative rules of addition/subtraction with" data-type="indexterm"></a>
<div data-type="note">
<h2>Basic Number Properties with Vectors</h2>
<p>Addition with vectors follow the same algebraic rules as with real numbers.</p>
<p><strong><em>The commutative rule:</em></strong> {uplusvvplusu}<br />
<strong><em>The associative rule:</em></strong> {uplusvwuvplusw}</p>
<p>Fancy terminology and symbols aside, this is really quite a simple concept. We’re just saying that common sense properties of addition apply to vectors as well.</p>
<p>{3plus2}<br />
{3plus2plus1}</p>
</div>
</section>
<section data-type="sect2" id="_vector_multiplication">
<h2>Vector multiplication</h2>
<a data-primary="mult() function (PVector class)" data-type="indexterm"></a> <a data-primary="PVector class (Processing)" data-secondary="mult() function" data-type="indexterm"></a> <a data-primary="vectors" data-secondary="multiplying" data-type="indexterm"></a> <a data-primary="vectors" data-secondary="scaling" data-type="indexterm"></a>
<p>Moving on to multiplication, we have to think a little bit differently. When we talk about multiplying a vector, what we typically mean is <strong><em>scaling</em></strong> a vector. If we wanted to scale a vector to twice its size or one-third of its size (leaving its direction the same), we would say: “Multiply the vector by 2” or “Multiply the vector by 1/3.” Note that we are multiplying a vector by a scalar, a single number, not another vector.</p>
<p>To scale a vector, we multiply each component (<span class="var">x</span> and <span class="var">y</span>) by a scalar.</p>
<figure class="half-width-right" id="chapter01_figure8"><img alt="Figure 1.8: Scaling a vector" src="chapter01/ch01_08.png" />
<figcaption>Figure 1.8: Scaling a vector </figcaption>
</figure>
<p>{wutimesn}</p>
<p>can be written as:</p>
<p>{wxtimesn}<br />
{wytimesn}</p>
<p>Let’s look at an example with vector notation.</p>
<p>{uequals}<br />
{nequals}</p>
<p>{wutimesn}<br />
{wxequals}<br />
{wyequals}</p>
<p>{wequals}</p>
<p>Therefore, the function inside the <span class="klass">PVector</span> class is written as:</p>
<pre data-code-language="java" data-type="programlisting">
void mult(float n) {
//[full] With multiplication, the components of the vector are multiplied by a number.
x = x * n;
y = y * n;
//[end]
}</pre>
<p>And implementing multiplication in code is as simple as:</p>
<a data-primary="mult() function (PVector class)" data-secondary="implementation" data-type="indexterm"></a>
<pre data-code-language="java" data-type="programlisting">
PVector u = new PVector(-3,7);
// This PVector is now three times the size and is equal to (-9,21).
u.mult(3);</pre>
<figure class="screenshot" data-pde="processingjs/chapter01/_1_4_vector_multiplication/_1_4_vector_multiplication.pde"><img alt="ch01 ex04" src="chapter01/ch01_ex04.png" />
<figcaption> </figcaption>
</figure>
<div data-type="example"><h5>Example 1.4: Multiplying a vector</h5></div>
<pre data-code-language="java" data-type="programlisting">
void setup() {
size(640,360);
}
void draw() {
background(255);
PVector mouse = new PVector(mouseX,mouseY);
PVector center = new PVector(width/2,height/2);
mouse.sub(center);
// Multiplying a vector! The vector is now half its original size (multiplied by 0.5).
mouse.mult(0.5);
translate(width/2,height/2);
line(0,0,mouse.x,mouse.y);
}</pre>
<figure class="half-width-right" id="chapter01_figure9"><img alt="Figure 1.9" src="chapter01/ch01_09.png" />
<figcaption>Figure 1.9</figcaption>
</figure>
<a data-primary="div() function (PVector class)" data-type="indexterm"></a> <a data-primary="PVector class (Processing)" data-secondary="div() function" data-type="indexterm"></a>
<p>Division works just like multiplication—we simply replace the multiplication sign (asterisk) with the division sign (forward slash).</p>
<pre data-code-language="java" data-type="programlisting">
void div(float n) {
x = x / n;
y = y / n;
}
PVector u = new PVector(8,-4);
// Dividing a vector! The vector is now half its original size (divided by 2).
u.div(2);</pre>
<a data-primary="vectors" data-secondary="associative/distributive rules for multiplication/division of" data-type="indexterm"></a>
<div data-type="note">
<h2>More Number Properties with Vectors</h2>
<p>As with addition, basic algebraic rules of multiplication apply to vectors.</p>
<p>The associative rule: {nmtimesv1}<br />
The distributive rule with 2 scalars, 1 vector: {nmtimesv2}<br />
The distributive rule with 2 vectors, 1 scalar: {uvtimesn}</p>
</div>
</section>
</section>
<section data-type="sect1" id="chapter01_section5">
<h2>1.5 Vector Magnitude</h2>
<a data-primary="magnitude (of vectors)" data-type="indexterm"></a> <a data-primary="vectors" data-secondary="magnitude" data-type="indexterm"></a>
<p>Multiplication and division, as we just saw, are means by which the length of the vector can be changed without affecting direction. Perhaps you’re wondering: “OK, so how do I know what the length of a vector is? I know the components (<span class="var">x</span> and <span class="var">y</span>), but how long (in pixels) is the actual arrow?” Understanding how to calculate the length (also known as <strong><em>magnitude</em></strong>) of a vector is incredibly useful and important.</p>
<div class="image-container half-width-right"><img alt="Nature of Code Image" src="chapter01/ch01_10.png" />
<p class="caption">Figure 1.10: The length or “magnitude” of a vector <svg:svg height="12.190371pt" viewbox="0 -9.600527 8.520000 12.190371" width="8.520000pt" xmlns="http://www.w3.org/1998/Math/MathML" xmlns:svg="http://www.w3.org/2000/svg" xmlns:svgmath="http://www.grigoriev.ru/svgmath"><svg:metadata><svgmath:metrics axis="6.57421875" baseline="2.58984375" bottom="2.44921875" top="12.1903710937"></svgmath:metrics></svg:metadata><svg:g transform="translate(1.596914, 0.000000)"><svg:text fill="black" font-family="Times New Roman" font-size="12.000000" font-style="italic" text-anchor="middle" x="2.663086" y="0.000000">v</svg:text></svg:g><svg:g transform="translate(0.000000, -8.785137)"><svg:text fill="black" font-family="Times New Roman" font-size="8.520000" text-anchor="middle" x="4.260000" y="2.828906">→</svg:text></svg:g></svg:svg> is often written as: <svg:svg height="12.503906pt" viewbox="0 -9.914062 29.061672 12.503906" width="29.061672pt" xmlns="http://www.w3.org/1998/Math/MathML" xmlns:svg="http://www.w3.org/2000/svg" xmlns:svgmath="http://www.grigoriev.ru/svgmath"><svg:metadata><svgmath:metrics axis="6.57421875" baseline="2.58984375" bottom="1.37109375" top="12.357421875"></svgmath:metrics></svg:metadata><svg:g transform="translate(0.000000, -3.984375)"><svg:text fill="black" font-family="Lucida Sans Unicode" font-size="12.000000" text-anchor="middle" x="3.468750" y="3.468750">∥</svg:text></svg:g><svg:g transform="translate(10.270836, 0.000000)"><svg:g transform="translate(1.596914, 0.000000)"><svg:text fill="black" font-family="Times New Roman" font-size="12.000000" font-style="italic" text-anchor="middle" x="2.663086" y="0.000000">v</svg:text></svg:g><svg:g transform="translate(0.000000, -8.785137)"><svg:text fill="black" font-family="Times New Roman" font-size="8.520000" text-anchor="middle" x="4.260000" y="2.828906">→</svg:text></svg:g></svg:g><svg:g transform="translate(22.124172, -3.984375)"><svg:text fill="black" font-family="Lucida Sans Unicode" font-size="12.000000" text-anchor="middle" x="3.468750" y="3.468750">∥</svg:text></svg:g></svg:svg></p>
</div>
<a data-primary="Pythagoras" data-type="indexterm"></a> <a data-primary="Pythagorean theorem" data-type="indexterm"></a>
<p>Notice in the above diagram how the vector, drawn as an arrow and two components (<span class="var">x</span> and <span class="var">y</span>), creates a right triangle. The sides are the components and the hypotenuse is the arrow itself. We’re very lucky to have this right triangle, because once upon a time, a Greek mathematician named Pythagoras developed a lovely formula to describe the relationship between the sides and hypotenuse of a right triangle.</p>
<figure class="half-width-right" id="chapter01_figure11"><img alt="Figure 1.11: The Pythagorean Theorem" src="chapter01/ch01_11.png" />
<figcaption>Figure 1.11: The Pythagorean Theorem </figcaption>
</figure>
<p>The Pythagorean theorem is <em>a</em> squared plus <em>b</em> squared equals <em>c</em> squared.</p>
<p>Armed with this formula, we can now compute the magnitude of {vectorv} as follows:</p>
<p>{pythagorean}</p>
<p>or in <span class="klass">PVector</span>:</p>
<pre data-code-language="java" data-type="programlisting">
float mag() {
return sqrt(x*x + y*y);
}</pre>
<figure class="screenshot" data-pde="processingjs/chapter01/_1_5_vector_magnitude/_1_5_vector_magnitude.pde"><img alt="ch01 ex05" src="chapter01/ch01_ex05.png" />
<figcaption> </figcaption>
</figure>
<div data-type="example"><h5>Example 1.5: Vector magnitude</h5></div>
<a data-primary="mag() function (PVector class)" data-type="indexterm"></a> <a data-primary="PVector class (Processing)" data-secondary="mag() function" data-type="indexterm"></a>
<pre data-code-language="java" data-type="programlisting">
void setup() {
size(640,360);
}
void draw() {
background(255);
PVector mouse = new PVector(mouseX,mouseY);
PVector center = new PVector(width/2,height/2);
mouse.sub(center);
//[full] 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.
float m = mouse.mag();
fill(0);
rect(0,0,m,10);
//[end]
translate(width/2,height/2);
line(0,0,mouse.x,mouse.y);
}</pre>
</section>
<section data-type="sect1" id="chapter01_section6">
<h2>1.6 Normalizing Vectors</h2>
<a data-primary="normalization" data-type="indexterm"></a> <a data-primary="unit vectors" data-type="indexterm"></a> <a data-primary="vectors" data-secondary="normalization" data-type="indexterm"></a> <a data-primary="vectors" data-secondary="unit vectors" data-type="indexterm"></a>
<p>Calculating the magnitude of a vector is only the beginning. The magnitude function opens the door to many possibilities, the first of which is <strong><em>normalization</em></strong>. Normalizing refers to the process of making something “standard” or, well, “normal.” In the case of vectors, let’s assume for the moment that a standard vector has a length of 1. To normalize a vector, therefore, is to take a vector of any length and, keeping it pointing in the same direction, change its length to 1, turning it into what is called a <strong><em>unit vector</em></strong>.</p>
<figure class="half-width-right" id="chapter01_figure12"><img alt="Figure 1.12" src="chapter01/ch01_12.png" />
<figcaption>Figure 1.12</figcaption>
</figure>
<p>Since it describes a vector’s direction without regard to its length, it’s useful to have the unit vector readily accessible. We’ll see this come in handy once we start to work with forces in Chapter 2.</p>
<p>For any given vector {vectoru}, its unit vector (written as {unitu}) is calculated as follows:</p>
<p>{unituformula}</p>
<p>In other words, to normalize a vector, simply divide each component by its magnitude. This is pretty intuitive. Say a vector is of length 5. Well, 5 divided by 5 is 1. So, looking at our right triangle, we then need to scale the hypotenuse down by dividing by 5. In that process the sides shrink, divided by 5 as well.</p>
<a data-primary="normalize() function (PVector class)" data-type="indexterm"></a> <a data-primary="PVector class (Processing)" data-secondary="normalize() function" data-type="indexterm"></a>
<figure class="half-width-right" id="chapter01_figure13"><img alt="Figure 1.13" src="chapter01/ch01_13.png" />
<figcaption>Figure 1.13</figcaption>
</figure>
<p>In the <span class="klass">PVector</span> class, we therefore write our normalization function as follows:</p>
<pre data-code-language="java" data-type="programlisting">
void normalize() {
float m = mag();
div(m);
}</pre>
<p>Of course, there’s one small issue. What if the magnitude of the vector is 0? We can’t divide by 0! Some quick error checking will fix that right up:</p>
<pre data-code-language="java" data-type="programlisting">
void normalize() {
float m = mag();
if (m != 0) {
div(m);
}
}</pre>
<figure class="screenshot" data-pde="processingjs/chapter01/_1_6_vector_normalize/_1_6_vector_normalize.pde"><img alt="ch01 ex06" src="chapter01/ch01_ex06.png" />
<figcaption> </figcaption>
</figure>
<div data-type="example"><h5>Example 1.6: Normalizing a vector</h5></div>
<pre data-code-language="java" data-type="programlisting">
void draw() {
background(255);
PVector mouse = new PVector(mouseX,mouseY);
PVector center = new PVector(width/2,height/2);
mouse.sub(center);
// In 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.
mouse.normalize();
mouse.mult(50);
translate(width/2,height/2);
line(0,0,mouse.x,mouse.y);
}</pre>
</section>
<section data-type="sect1" id="chapter01_section7">
<h2>1.7 Vector Motion: Velocity</h2>
<a data-primary="motion" data-type="indexterm"></a> <a data-primary="vectors" data-secondary="velocity and" data-type="indexterm"></a> <a data-primary="velocity" data-type="indexterm"></a>
<p>All this vector math stuff sounds like something we should know about, but why? How will it actually help us write code? The truth of the matter is that we need to have some patience. It will take some time before the awesomeness of using the <span class="klass">PVector</span> class fully comes to light. This is actually a common occurrence when first learning a new data structure. For example, when you first learn about an array, it might seem like much more work to use an array than to just have several variables stand for multiple things. But that plan quickly breaks down when you need a hundred, or a thousand, or ten thousand things. The same can be true for <span class="klass">PVector</span>. What might seem like more work now will pay off later, and pay off quite nicely. And you don’t have to wait too long, as your reward will come in the next chapter.</p>
<p>For now, however, we want to focus on simplicity. What does it mean to program motion using vectors? We’ve seen the beginning of this in <a href="#chapter01_example2">Example 1.2</a><code>:</code> the bouncing ball. An object on screen has a location (where it is at any given moment) as well as a velocity (instructions for how it should move from one moment to the next). Velocity is added to location:</p>
<pre data-code-language="java" data-type="programlisting">
location.add(velocity);</pre>
<p>And then we draw the object at that location:</p>
<pre data-code-language="java" data-type="programlisting">
ellipse(location.x,location.y,16,16);</pre>
<p>This is Motion 101.</p>
<ol>
<li>
<p><strong><em>Add velocity to location</em></strong></p>
</li>
<li>
<p><strong><em>Draw object at location</em></strong></p>
</li>
</ol>
<a data-primary="Processing" data-secondary="OOP online tutorial" data-type="indexterm"></a>
<p>In the bouncing ball example, all of this code happened in Processing’s main tab, within <span class="function">setup()</span> and <span class="function">draw()</span>. What we want to do now is move towards encapsulating all of the logic for motion inside of a <strong><em>class</em></strong>. This way, we can create a foundation for programming moving objects in Processing. In <a href="#intro_section2">section I.2 of the introduction</a>, “The Random Walker Class,” we briefly reviewed the basics of object-oriented-programming (“OOP”). Beyond that short introduction, this book assumes experience with objects and classes in Processing. If you need a refresher, I encourage you to check out the <a href="http://processing.org/learning/objects/">Processing objects tutorial</a>.</p>
<p>In this case, we’re going to create a generic <span class="klass">Mover</span> class that will describe a thing moving around the screen. And so we must consider the following two questions:</p>
<ol>
<li>
<p><strong><em>What data does a mover have?</em></strong></p>
</li>
<li>
<p><strong><em>What functionality does a mover have?</em></strong></p>
</li>
</ol>
<p>Our Motion 101 algorithm tells us the answers to these questions. A <span class="klass">Mover</span> object has two pieces of data: <span class="var">location</span> and <span class="var">velocity</span>, which are both <span class="klass">PVector</span> objects.</p>
<pre data-code-language="java" data-type="programlisting">
class Mover {
PVector location;
PVector velocity;</pre>
<p>Its functionality is just about as simple. The <span class="klass">Mover</span> needs to move and it needs to be seen. We’ll implement these needs as functions named <span class="function">update()</span> and <span class="function">display()</span>. We’ll put all of our motion logic code in <span class="function">update()</span> and draw the object in <span class="function">display()</span>.</p>
<pre data-code-language="java" data-type="programlisting">
void update() {
// The Mover moves.
location.add(velocity);
}
void display() {
stroke(0);
fill(175);
// The Mover is displayed.
ellipse(location.x,location.y,16,16);
}
}</pre>
<a data-primary="class (Processing)" data-secondary="constructor" data-type="indexterm"></a> <a data-primary="constructor" data-type="indexterm"></a>
<p>We’ve forgotten one crucial item, however: the object’s <strong><em>constructor</em></strong>. The constructor is a special function inside of a class that creates the instance of the object itself. It is where you give instructions on how to set up the object. It always has the same name as the class and is called by invoking the <strong><em>new</em></strong> operator:</p>
<pre data-code-language="java" data-type="programlisting">
Mover m = new Mover();</pre>
<p>In our case, let’s arbitrarily decide to initialize our <span class="klass">Mover</span> object by giving it a random location and a random velocity.</p>
<pre data-code-language="java" data-type="programlisting">
Mover() {
location = new PVector(random(width),random(height));
velocity = new PVector(random(-2,2),random(-2,2));
}</pre>
<p>If object-oriented programming is at all new to you, one aspect here may seem a bit confusing. After all, we spent the beginning of this chapter discussing the <span class="klass">PVector</span> class. The <span class="klass">PVector</span> class is the template for making the <span class="klass">location</span> object and the <span class="klass">velocity</span> object. So what are they doing inside of yet another object, the <span class="klass">Mover</span> object? In fact, this is just about the most normal thing ever. An object is simply something that holds data (and functionality). That data can be numbers (integers, floats, etc.) or other objects! We’ll see this over and over again in this book. For example, in <a href="#chapter04_section1">Chapter 4</a> we’ll write a class to describe a system of particles. That <span class="klass">ParticleSystem</span> object will have as its data a list of <span class="klass">Particle</span> objects…and each <span class="klass">Particle</span> object will have as its data several <span class="klass">PVector</span> objects!</p>
<p>Let’s finish off the <span class="klass">Mover</span> class by incorporating a function to determine what the object should do when it reaches the edge of the window. For now let’s do something simple, and just have it wrap around the edges.</p>
<pre data-code-language="java" data-type="programlisting">
void checkEdges() {
//[full] When it reaches one edge, set location to the other.
if (location.x > width) {
location.x = 0;
} else if (location.x < 0) {
location.x = width;
}
if (location.y > height) {
location.y = 0;
} else if (location.y < 0) {
location.y = height;
}
//[end]
}</pre>
<p>Now that the <span class="klass">Mover</span> class is finished, we can look at what we need to do in our main program. We first declare a <span class="klass">Mover</span> object:</p>
<pre data-code-language="java" data-type="programlisting">
Mover mover;</pre>
<p>Then initialize the mover in <span class="function">setup()</span>:</p>
<pre data-code-language="java" data-type="programlisting">
mover = new Mover();</pre>
<p>and call the appropriate functions in <span class="function">draw()</span>:</p>
<pre data-code-language="java" data-type="programlisting">
mover.update();
mover.checkEdges();
mover.display();</pre>
<p>Here is the entire example for reference:</p>
<figure class="screenshot" data-pde="processingjs/chapter01/_1_7_motion101/_1_7_motion101.pde processingjs/chapter01/_1_7_motion101/Mover.pde"><img alt="ch01 ex07" src="chapter01/ch01_ex07.png" />
<figcaption> </figcaption>
</figure>
<div data-type="example"><h5>Example 1.7: Motion 101 (velocity)</h5></div>
<pre data-code-language="java" data-type="programlisting">
// Declare Mover object.
Mover mover;
void setup() {
size(640,360);
// Create Mover object.
mover = new Mover();
}
void draw() {
background(255);
//[full] Call functions on Mover object.
mover.update();
mover.checkEdges();
mover.display();
//[end]
}
class Mover {
//[full] Our object has two PVectors: location and velocity.
PVector location;
PVector velocity;
//[end]
Mover() {
location = new PVector(random(width),random(height));
velocity = new PVector(random(-2,2),random(-2,2));
}
void update() {
// Motion 101: Location changes by velocity.
location.add(velocity);
}
void display() {
stroke(0);
fill(175);
ellipse(location.x,location.y,16,16);
}
void checkEdges() {
if (location.x > width) {
location.x = 0;
} else if (location.x < 0) {
location.x = width;
}
if (location.y > height) {
location.y = 0;
} else if (location.y < 0) {
location.y = height;
}
}
}</pre>
</section>
<section data-type="sect1" id="chapter01_section8">
<h2>1.8 Vector Motion: Acceleration</h2>
<a data-primary="acceleration" data-type="indexterm"></a> <a data-primary="vectors" data-secondary="acceleration" data-type="indexterm"></a> <a data-primary="velocity" data-secondary="acceleration" data-type="indexterm"></a>
<p>OK. At this point, we should feel comfortable with two things: (1) what a <span class="klass">PVector</span> is and (2) how we use <span class="klass">PVector</span><code>s</code> inside of an object to keep track of its location and movement. This is an excellent first step and deserves a mild round of applause. Before standing ovations and screaming fans, however, we need to make one more, somewhat bigger step forward. After all, watching the Motion 101 example is fairly boring—the circle never speeds up, never slows down, and never turns. For more interesting motion, for motion that appears in the real world around us, we need to add one more <span class="klass">PVector</span> to our class—<span class="var">acceleration</span>.</p>
<p>The strict definition of <strong><em>acceleration</em></strong> we’re using here is: <em>the rate of change of velocity</em>. Let’s think about that definition for a moment. Is this a new concept? Not really. Velocity is defined as <em>the rate of change of location</em>. In essence, we are developing a “trickle-down” effect. Acceleration affects velocity, which in turn affects location (for some brief foreshadowing, this point will become even more crucial in the next chapter, when we see how forces affect acceleration, which affects velocity, which affects location). In code, this reads:</p>
<pre data-code-language="java" data-type="programlisting">
velocity.add(acceleration);
location.add(velocity);</pre>
<p>As an exercise, from this point forward, let’s make a rule for ourselves. Let’s write every example in the rest of this book without ever touching the value of velocity and location (except to initialize them). In other words, our goal now for programming motion is: Come up with an algorithm for how we calculate acceleration and let the trickle-down effect work its magic. (In truth, you’ll find reasons to break this rule, but it’s important to illustrate the principles behind our motion algorithm.) And so we need to come up with some ways to calculate acceleration:</p>
<section data-type="sect2" id="_acceleration_algorithms">
<h3>Acceleration Algorithms!</h3>
<a data-primary="acceleration" data-secondary="algorithms for" data-type="indexterm"></a> <a data-primary="acceleration algorithms" data-type="indexterm"></a>
<ol>
<li>
<p><em>A constant acceleration</em></p>
</li>
<li>
<p><em>A totally random acceleration</em></p>
</li>
<li>
<p><em>Acceleration towards the mouse</em></p>