-
Notifications
You must be signed in to change notification settings - Fork 0
/
basicVectorField.js
80 lines (66 loc) · 2.59 KB
/
basicVectorField.js
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
// array for storing vectors
locs = [];
/**
* Setting up the P5 sketch.
* Canvas dimensions are set, test size is set, and a matrix of vectors is set up for drawing the vector field
*/
function setup() {
// drawing canvas to dimensions that match the size of the window
createCanvas(windowWidth, windowHeight);
// resolution of vector field, one vector for every 50 pixels
res = 50;
xCount = ceil(width / res);
yCount = ceil(height / res);
// creating new vector objects and appending to locs array by row
// outer loop iterates through y-axis (rows)
// inner loop builds new vector every <res> pixels across x-axis
for (let i = 0; i <= yCount; i++) {
for (let j = 0; j <= xCount; j++) {
locs.push(new p5.Vector(res * j, res * i));
}
}
}
/**
* Rendering components to the canvas.
* A matrix of position vectors for the track of the moving object is built and drawn.
*/
function draw() {
// setting background color to turquiose ish
background(200);
// removing fill and setting line stroke
noFill();
stroke(0);
// iterating through each vector in locs
for (let k = 0; k < locs.length; k++) {
// builds a new vector based off relative location of the mouse pointer
/**
* <P> = <x, y> position vector from locs
* <M> = <a, b> position vector of mouse
* To get new vector pointing from <P> to <M>,
* we build a new vector as:
* <PM> = <a - x, b - y>
*
* This gives us a position vector towards the location of the mouse.
*/
let h = new p5.Vector(mouseX - locs[k].x, mouseY - locs[k].y);
// creates an instance specific to the new vector h
push();
// translate the next object to the head of the pos vector in locs
translate(locs[k].x, locs[k].y);
// rotates the next object in this instance to the heading of vector h
rotate(h.heading());
/* creates a line object at the origin pointing directly right
* translate and rotate are applied to this line
* translate moves the base of the line to vector from locs
* rotate turns the vector based on vector h heading
*
* To create curl, all we need to do is change the ratio of x2 and y2.
* The heading of the line is based on vector h and the rotate()
* function will just add n-radians. Keeping y2 as 0 makes the vector point directly
* towards the mouse.
*/
line(0, 0, 15, 0);
// exit the instance
pop();
}
}