Main content
Computer programming
Course: Computer programming > Unit 5
Lesson 4: Vectors- Intro to vectors
- Challenge: Vector walker
- More vector math
- Challenge: Lightsaber
- Vector magnitude & normalization
- Challenge: Magnitude visualizer
- Vector motion
- Challenge: Braking car
- Static functions vs. instance methods
- Challenge: Static functions
- Interactive vector motion
- Challenge: Mouse stalker
- Project: Computational creatures
© 2023 Khan AcademyTerms of usePrivacy PolicyCookie Notice
More vector math
Addition was really just the first step. There are many mathematical operations that are commonly used with vectors. Below is a comprehensive list of the operations available as functions in the
PVector
object from ProcessingJS. We’ll go through a few of the key ones now. As our examples get more sophisticated in later sections, we’ll continue to reveal the details of more functions.add()
— add vectorssub()
— subtract vectorsmult()
— scale the vector with multiplicationdiv()
— scale the vector with divisionmag()
— calculate the magnitude of a vectornormalize()
— normalize the vector to a unit length of 1limit()
— limit the magnitude of a vectorheading2D()
— the 2D heading of a vector expressed as an angledist()
— the Euclidean distance between two vectors (considered as points)angleBetween()
— find the angle between two vectorsdot()
— the dot product of two vectorscross()
— the cross product of two vectors (only relevant in three dimensions)
Having already covered addition, let’s start with subtraction. This one’s not so bad; just take the plus sign and replace it with a minus!
Vector Subtraction
can be written as:
start text, w, end text, start subscript, x, end subscript, equals, start text, u, end text, start subscript, x, end subscript, minus, start text, v, end text, start subscript, x, end subscript
start text, w, end text, start subscript, y, end subscript, equals, start text, u, end text, start subscript, y, end subscript, minus, start text, v, end text, start subscript, y, end subscript
start text, w, end text, start subscript, y, end subscript, equals, start text, u, end text, start subscript, y, end subscript, minus, start text, v, end text, start subscript, y, end subscript
and so the function inside
PVector
looks like:PVector.prototype.sub = function(vector2) {
this.x = this.x - vector2.x;
this.y = this.y - vector2.y;
};
The following example demonstrates vector subtraction by taking the difference between two points (the mouse location and the center of the window).
Basic Number Properties with Vectors
When we're doing math with real numbers, they obey these basic rules:
The commutative rule: 3, plus, 2, equals, 2, plus, 3
The associative rule: left parenthesis, 3, plus, 2, right parenthesis, plus, 1, equals, 3, plus, left parenthesis, 2, plus, 1, right parenthesis
Those same rules are true of math with vectors:
The commutative rule: u, with, vector, on top, plus, v, with, vector, on top, equals, v, with, vector, on top, plus, u, with, vector, on top
The associative rule: u, with, vector, on top, plus, left parenthesis, v, with, vector, on top, plus, w, with, vector, on top, right parenthesis, equals, left parenthesis, u, with, vector, on top, plus, v, with, vector, on top, right parenthesis, plus, w, with, vector, on top
Vector Multiplication
Moving on to multiplication, we have to think a little bit differently. When we talk about multiplying a vector, what we typically mean is scaling a vector. If we wanted to scale a vector to twice its size or one-third of its size (leaving its direction the same), we would say: “Multiply the vector by 2” or “Multiply the vector by 1/3.” Note that we are multiplying a vector by a scalar, a single number, not another vector.
To scale a vector, we multiply each component (x and y) by a scalar.
w, with, vector, on top, equals, u, with, vector, on top, times, n
w, with, vector, on top, equals, u, with, vector, on top, times, n
can be written as:
Let’s look at an example with vector notation.
Therefore, the function inside the
PVector
object is written as:PVector.prototype.mult = function(n) {
this.x = this.x * n;
this.y = this.y * n;
}
And using
mult
in code is as simple as:var u = new PVector(-3,7);
// This PVector is now three times the size and is equal to (-9,21).
u.mult(3);
Here's the example from earlier, but we multiply the vector by 0.5 each time, so that it's scaled by half:
Instead of multiplying by 0.5 above, we could have also divided by 2. Division works just like multiplication—we simply replace the multiplication sign (asterisk) with the division sign (forward slash).
This is how the div method is implemented internally:
PVector.prototype.div = function(n) {
this.x = this.x / n;
this.y = this.y / n;
}
And this is how we can use it in code:
var u = new PVector(8, -4);
u.div(2);
More Number Properties with Vectors
As with addition, basic algebraic rules of multiplication apply to vectors.
The associative rule: left parenthesis, n, times, m, right parenthesis, times, v, with, vector, on top, equals, n, times, left parenthesis, m, times, v, with, vector, on top, right parenthesis
The distributive rule with 2 scalars, 1 vector: left parenthesis, n, plus, m, right parenthesis, times, v, with, vector, on top, equals, n, times, v, with, vector, on top, plus, m, times, v, with, vector, on top
The distributive rule with 2 vectors, 1 scalar: left parenthesis, u, with, vector, on top, plus, v, with, vector, on top, right parenthesis, times, n, equals, u, with, vector, on top, times, n, plus, v, with, vector, on top, times, n
Want to practice your vector math? You can learn more here on Khan Academy, in our Linear Algebra: Vectors unit.
This "Natural Simulations" course is a derivative of "The Nature of Code" by Daniel Shiffman, used under a Creative Commons Attribution-NonCommercial 3.0 Unported License.
Want to join the conversation?
- In the last paragraph there is probably a mistake.
The distributive rule with 2 scalars, 1 vector: (n∗m)∗v⃗ =n∗v⃗ +m∗v⃗
Between n and m should be a plus sign instead of a multiplication sign. So:
The distributive rule with 2 scalars, 1 vector: (n+m)∗v⃗ =n∗v⃗ +m∗v⃗(57 votes)- Such problems can be reported using the 'Report a mistake in the article' button at the top-right of the discussion panel, possibly even leading to the 'Fact Checker' moon badge. Someone else already reported this mistake.(12 votes)
- in the first example couldn't you just do this
var draw = function() {
background(255, 255, 255);
stroke(255, 0, 0);
strokeWeight(3);
line(200, 200, mouseX, mouseY);
};(15 votes)- Yes, that would work, but it uses techniques that you already knew before learning about vectors. The point of the example is to illustrate subtraction of vectors. The subtraction occurs when the center of the canvas (vector center) is subtracted from the mouse position (vector mouse). Vector mouse represents the mouse position, but it's now relative to the center of the canvas (meaning position (0,0) is the canvas center).
If the coordinate system used for storing a mouse position is changed to make (0,0) the center of the canvas, the way it's drawn must also be changed. This was done in the example by using translate so that the drawing coordinate system is also at the center of the canvas.(17 votes)
- Operations over vectors like .
add(), sub(), mult()
etc. change the vectors themselves. What if I wanted to introduce a new variable, a new PVector and assign it to for example a sum of two other vectors, but not change them?
Like newVector = a + b(4 votes)- What you ask shall be answered, use static methods of the functions that come with the
PVector();
, here's an example:var newVector = PVector.add(a, b);
.
Here's more about it: https://www.khanacademy.org/computing/computer-programming/programming-natural-simulations/programming-vectors/a/static-functions-vs-instance-methods.(7 votes)
- Can someone pleas help me on the next challenge i don't get it(3 votes)
- var v = new PVector(50, 75);
var drawSaber = function() {
background(0, 0, 0);
// glow
strokeWeight(8);
stroke(107, 206, 219, 150);
line(0, 400, v.x, 400-v.y);
// blade
stroke(255, 255, 255);
strokeWeight(4);var v = new PVector(50, 75);
var drawSaber = function() {
background(0, 0, 0);
// glow
strokeWeight(8);
stroke(107, 206, 219, 150);
line(0, 400, v.x, 400-v.y);
// blade
stroke(255, 255, 255);
strokeWeight(4);
line(0, 400, v.x, 400-v.y);
};
keyPressed = function(){
if (keyCode === UP){
v.mult(2);
} else if(keyCode === DOWN){
if (keyCode === DOWN){
v.div(2);
}
}
drawSaber();
};
line(0, 400, v.x, 400-v.y);
};
drawSaber();(3 votes)
- I don't understand what resetMatrix() does, can anybody explain it to me?(3 votes)
- Let's think of it this way.
You have a program consisting of a tree and a snowflake; and you want to rotate the snowflake by 20 degrees.
You could put therotate(20)
line in front of the code, but that would rotate both the snowflake and the tree, because thedraw
function repeats itself for the program lifetime. On the other hand, if you omit the function, you don't have animation.
----------------------------------------------------------------------------------------------------------------------
There's a solution!
You just "enclose" the snowflake drawing code and itsrotate
function in a chunk of code.
The first line is:pushMatrix();
That "activates" the matrix, anything after will be affected by transformations.rotate(20);
Then you have the snowflake drawing code (here).
And then:popMatrix();
That line "disactivates" the matrix. Anything after or before that chunk of code (from the "push" to the "pop" will not be rotated).
-----------------------------------------------------------------------------------------------------------------------
But let's assume that you have a really big program and you want to save code.
You would write the above code this way:rotate(20);
Aha, the computer got a command to rotate the canvas by 20 degrees.
Here - the snowflake drawing command.resetMatrix();
This function serves the same purpose as thepopMatrix()
function -- except that you don't need the "push" anymore. The "reset" function, as it says, resets the canvas to a neutral state.
Hope that helped,
- SapFire13(4 votes)
- What is the difference between
dist();
andmag();
(3 votes)- The
.mag()
method of a PVector finds the magnitude of the vector, which is the distance between the vector and (0, 0, 0).PVector.dist(vector2)
finds the distance between the vector andvector2
.(4 votes)
- In the two example programs, what does " translate (width/2, height/2) " mean? It isn't mentioned in the operator list at the start of the article.(2 votes)
- Ok, in JS, translate moves an object according to the amount of pixels entered into the arguments. In this case,
width/2
andheight/2
were used. So, instead of sayingtranslate(200,200);
which would only be centered for a 400x400 canvas,translate(width/2,height/2);
was used to center it on all canvases.(5 votes)
- could someone help me on the
? Thanks!LightSaber Challenge
(3 votes)- Also, make sure you move the drawSaber function inside the keyPressed function. If you don't, the drawing won't update when you multiple/divide the vector.(2 votes)
- why is vector math so important just stick to easy math(0 votes)
- If you just stick to easy math, you won't learn very much and you won't gain the abilities that come with new math knowledge!(10 votes)
- I used v = mult(v); but It says mult is not defined. Is there something I'm missing?(2 votes)
- The correct syntax is
myVector.mult(scale)
If your vector is calledv
and you want to scale it up by a factor of 4, you would writev.mult(4);
(2 votes)