Wiki

Clone wiki

Core / vec2TutorialPart1

Working with vec2() - Part 1

Step 1

Begin with the following code

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)
    stroke(255, 0, 0) -- No. 1 is red
    line(0, 0, x1, y1)
    ellipse(x1, y1, 20, 20)
    stroke(0, 0, 255) -- No. 2 is blue
    line(0, 0, x2, y2)
    ellipse(x2, y2, 20, 20)
end

You should get a two lines and circles. Red is controlled by the x1 and y1 sliders. Blue is controlled by x2 and y2.


Step 2

Now place the x's and y's into vec2 values, as shown below. The benefits of doing this are explained in Step 3 below:

function draw()
    rect(0, 0, 10, 10)
    background(0)
    noFill()
    strokeWidth(3)
    --place x's and y's into vectors
    v1 = vec2(x1, y1)
    v2 = vec2(x2, y2)
    stroke(255, 0, 0)
    line(0, 0, v1.x, v1.y)
    ellipse(v1.x, v1.y, 20, 20)
    stroke(0, 0, 255)
    line(0, 0, v2.x, v2.y)
    ellipse(v2.x, v2.y, 20, 20)
end

The programs does the same function, only now the data is stored as values of type vec2.


Step 3

Now add a third line and circle as shown at the end of the draw() code:

function draw()
    ...
    v3 = v1 + v2
    stroke(255, 0, 255) -- No. 3 is purple
    line(0, 0, v3.x, v3.y)
    ellipse(v3.x, v3.y, 20, 20)
end

This adds a purple line and circle that is controlled by adding the vectors of red and blue together.

v3 = v1 + v2

is the equlivant of

x3 = x1 + x2
y3 = y1 + y2
v3 = vec2(x3, y3)

without needing x3 or y3.

You can also try

v3 = v2 - v1

If either x or y of v2 is less than v1, part of v3 will be negative - meaning it will be drawn off the screen.


Step 4

For the next step add the following at the end of the draw() code:

function draw()
    ...
    d = v1:dist(v2)
    stroke(0, 255, 0) -- Green
    ellipse(v2.x, v2.y, d * 2, d * 2)
end

This will draw a green circle around the blue that extends to the red. This is commonly used in determining how far touches are from a point on the screen. The d is multiplied by 2 in this example since ellispe is using it's default behavior of radius instead of diameter.

Next: Working with vectors (vec2) Part 2: Additional Codea-provided functions

Updated