Reference add()

add()

Adds to a vector's x, y, and z components.

add() can use separate numbers, as in v.add(1, 2, 3), another p5.Vector object, as in v.add(v2), or an array of numbers, as in v.add([1, 2, 3]).

If a value isn't provided for a component, it won't change. For example, v.add(4, 5) adds 4 to v.x, 5 to v.y, and 0 to v.z. Calling add() with no arguments, as in v.add(), has no effect.

The static version of add(), as in p5.Vector.add(v2, v1), returns a new p5.Vector object and doesn't change the originals.

Examples

function setup() {
createCanvas(100, 100);

background(200);

// Style the points.
strokeWeight(5);

// Top left.
let pos = createVector(25, 25);
point(pos);

// Top right.
// Add numbers.
pos.add(50, 0);
point(pos);

// Bottom right.
// Add a p5.Vector.
let p2 = createVector(0, 50);
pos.add(p2);
point(pos);

// Bottom left.
// Add an array.
let arr = [-50, 0];
pos.add(arr);
point(pos);

describe('Four black dots arranged in a square on a gray background.');
}
function setup() {
createCanvas(100, 100);

background(200);

// Top left.
let p1 = createVector(25, 25);

// Center.
let p2 = createVector(50, 50);

// Bottom right.
// Add p1 and p2.
let p3 = p5.Vector.add(p1, p2);

// Draw the points.
strokeWeight(5);
point(p1);
point(p2);
point(p3);

describe('Three black dots in a diagonal line from top left to bottom right.');
}
function setup() {
createCanvas(100, 100);

describe('Three arrows drawn on a gray square. A red arrow extends from the top left corner to the center. A blue arrow extends from the tip of the red arrow. A purple arrow extends from the origin to the tip of the blue arrow.');
}

function draw() {
background(200);

let origin = createVector(0, 0);

// Draw the red arrow.
let v1 = createVector(50, 50);
drawArrow(origin, v1, 'red');

// Draw the blue arrow.
let v2 = createVector(-30, 20);
drawArrow(v1, v2, 'blue');

// Purple arrow.
let v3 = p5.Vector.add(v1, v2);
drawArrow(origin, v3, 'purple');
}

// Draws an arrow between two vectors.
function drawArrow(base, vec, myColor) {

Syntax

add(x, [y], [z])
add(value)
add(v1, v2, [target])

Parameters

x
Number:

x component of the vector to be added.

y
Number:

y component of the vector to be added.

z
Number:

z component of the vector to be added.

value
p5.Vector|Number[]:

The vector to add

v1
p5.Vector:

A p5.Vector to add

v2
p5.Vector:

A p5.Vector to add

target
p5.Vector:

vector to receive the result.

Notice any errors or typos? Please let us know. Please feel free to edit src/math/p5.Vector.js and open a pull request!

Related References