What is a Vector?
A vector is a mathematical object that has both magnitude (length) and direction. In computer graphics and p5.js, vectors are typically represented as points in 2D or 3D space, with x, y, and sometimes z coordinates. Vectors are often used for tasks such as moving objects, calculating distances, and handling physics simulations.
Creating a Vector in p5.js
To create a vector in p5.js, you can use the
createVector() function, which returns a new instance of the p5.Vector class.
z arguments represent the vector's components. The
z argument is optional, and when not provided, a 2D vector is created. Here's an example:
This creates a 2D vector with x-coordinate 100 and y-coordinate 200.
The p5.Vector class provides various methods for performing common vector operations. Some of these include:
Addition and Subtraction
You can add or subtract two vectors using the
sub() methods. These methods modify the original vector and return it.
Scalar Multiplication and Division
You can multiply or divide a vector by a scalar (a single number) using the
div() methods. These methods modify the original vector and return it.
The magnitude (length) of a vector can be calculated using the
To convert a vector to a unit vector (a vector with length 1), you can use the
Using Vectors in p5.js Sketches
Vectors are commonly used in p5.js sketches to handle object positions, velocities, and accelerations. Here's an example of using vectors to move a circle across the canvas:
In this sketch, we use the
position vector to represent the circle's position and the
velocity vector to represent its speed and direction. By adding the velocity to the position each frame, we create smooth motion. When the circle reaches the canvas edges, we reverse its velocity to make it bounce off.
Get creative and experiment with the p5.js Vector class to bring life to your sketches!