Wiki
Clone wikiCore / vec2TutorialPart2
Working with vec2 - Part 2
Step 5
After completing Step 4 of Working with vec2 - Part 1 you should have code that looks like the following:
function setup()
parameter.integer("x1", 1, WIDTH, 100)
parameter.integer("y1", 1, HEIGHT, 100)
parameter.integer("x2", 1, WIDTH, 200)
parameter.integer("y2", 1, HEIGHT, 100)
end
function draw()
rect(0, 0, 10, 10)
background(0)
noFill()
strokeWidth(3)
v1 = vec2(x1, y1)
v2 = vec2(x2, y2)
stroke(255, 0, 0) -- No. 1 is red
line(0, 0, v1.x, v1.y)
ellipse(v1.x, v1.y, 20, 20)
stroke(0, 0, 255) -- No. 2 is blue
line(0, 0, v2.x, v2.y)
ellipse(v2.x, v2.y, 20, 20)
v3 = v2 + v1
stroke(255, 0, 255) -- Purple
line(0, 0, v3.x, v3.y)
ellipse(v3.x, v3.y, 20, 20)
d = v1:dist(v2)
stroke(0, 255, 0) -- Green
ellipse(v2.x, v2.y, d * 2, d * 2)
end
Step 6
First, add the following to the end of the draw()
code:
function draw()
...
v1n = v1:normalize()
v2n = v2:normalize()
line(0, 0, v1n.x * 50, v1n.y * 50)
line(0, 0, v2n.x * 50, v2n.y * 50)
end
This will draw green line part way up the red and blue lines.
myVec2:normalize()
returns x and y in a ratio so that x + y = 1.
For example if x=100 and y=0 then normalized x=1 and y=0.
Think of it as 1 unit of length in the direction of the vector.
When both x or y are non-zero, the math to determine what normalized x and y should be, can't be easily done in one's head.
Step 7
Next, let's add the length function as shown:
function draw()
...
v1n = v1:normalize() -- As above
v2n = v2:normalize() -- As above
l1 = v1:len()
l2 = v2:len()
line(0, 0, v1n.x * l2, v1n.y * l2)
line(0, 0, v2n.x * l1, v2n.y * l1)
end
This should draw a green line over the red line that is equal to the length of the blue line (and vice versa). v1n.x
(the normalized x of vector v1
) times l2
(the length of vector v2
).
Step 8
Up to this point, all of our vectors have been drawn starting at (0, 0). For this next step, we will start in the middle of the screen.
function draw()
...
stroke(255, 255, 0) -- Yellow
v5 = vec2(100, 0)
v4 = v5
line(WIDTH / 2, HEIGHT / 2, (WIDTH / 2) + v4.x, (HEIGHT / 2) + v4.y)
end
This draws a yellow line starting at the middle of the screen (WIDTH / 2
, HEIGHT / 2
).
Step 9
Now we will change v4
.
function draw()
...
v5 = vec2(100, 0) -- As above
a = v2:angleBetween(v1) -- New
v4 = v5:rotate(a) -- Changed
line(WIDTH / 2, HEIGHT / 2, (WIDTH / 2) + v4.x, (HEIGHT / 2) + v4.y)
line(WIDTH / 2, HEIGHT / 2, (WIDTH / 2) + v5.x, (HEIGHT / 2) + v5.y)
end
The yellow line now shows the angle between red and blue.
Step 10
If we take this rotation and apply it to the blue line as the end of the draw()
code:
function draw()
...
v6 = v2:rotate(a)
line(0, 0, v6.x, v6.y)
end
A new yellow line is drawn that is the blue line rotated by the angle between the blue and red. This makes the yellow line cover the red line for the length of blue line.
Updated