04.04.2013 Views

Processing: Creative Coding and Computational Art

Processing: Creative Coding and Computational Art

Processing: Creative Coding and Computational Art

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Normalizing a vector<br />

When working with vectors, it is common practice to find this base ratio of a vector, which<br />

is referred to as normalizing a vector. Normalizing simply means reducing the magnitude<br />

(length) of a vector to 1, which is done by dividing each component of a vector by its overall<br />

length. For example if you have vector v, you can find its length like this (expressed in<br />

code):<br />

length = sqrt(v.x*v.x + v.y*v.y);<br />

Then to find the base ratio, you simply divide each of the vector’s components by its<br />

length:<br />

normalizedVector.x = v.x / length;<br />

normalizedVector.y = v.y / length;<br />

Again, this base ratio, or normalized vector, expresses the direction of the vector. For<br />

example, if we have a line <strong>and</strong> we want to animate an ellipse at a certain speed along the<br />

line, we can treat the line as a vector. Once we have the length of the line, we can normalize<br />

it <strong>and</strong> use the normalized values as the direction for the ellipse to travel, which we<br />

can then multiply by any speed we choose. Here’s a sketch that does precisely this (shown<br />

in Figure 11-16):<br />

// Moving Along a Vector<br />

float lineX1, lineY1, lineX2, lineY2;<br />

float vectX, vectY, vectMag, directionX, directionY;<br />

float ellipseX, ellipseY;<br />

float ellipseSpeed = 2;<br />

void setup(){<br />

size(400, 400);<br />

fill(128);<br />

smooth();<br />

lineX1 = 100;<br />

lineY1 = 75;<br />

lineX2 = 300;<br />

lineY2 = 325;<br />

// express line as a vector<br />

vectX = lineX2-lineX1;<br />

vectY = lineY2-lineY1;<br />

// find magnitude(length) of vector<br />

vectMag = sqrt(vectX*vectX + vectY*vectY);<br />

/* normalize vector to get<br />

base direction ratio */<br />

directionX = vectX/vectMag;<br />

directionY = vectY/vectMag;<br />

MOTION<br />

523<br />

11

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!