Of course, there’s one small issue. What if the magnitude of the vector is 0? You can’t divide by 0! Some quick error checking will fix that right up:
Example 1.6: Normalizing a vector
@@ -581,7 +579,7 @@ function draw() {
this.position.y = height;
}
}
-
Now that the Mover
class is finished, I can move onto setup()
> and draw()
. First, declare a Mover
object:
+
Now that the Mover
class is finished, I can move onto setup()
and draw()
. First, declare a Mover
object:
let mover;
Then create and initialize the mover in setup()
:
mover = new Mover();
@@ -664,16 +662,15 @@ position.add(velocity);
constructor(){
this.position = createVector();
this.velocity = createVector();
- //{.bold} A new vector for acceleration
+ //{!1 .bold} A new vector for acceleration
this.acceleration = createVector();
- }
-
+ }
And incorporate acceleration into the update()
function:
-
update() {
+ update() {
//{!2 .bold} Our motion algorithm is now two lines of code!
this.velocity.add(this.acceleration);
this.position.add(this.velocity);
- }
+}
I’re almost done. The only missing piece is initialization in the constructor.
constructor() {
Let’s start the Mover
object in the middle of the window…
@@ -862,8 +859,8 @@ dir.mult(anything);
Assign that vector to acceleration.
I have a confession to make. This is such a common operation (normalization then scaling) that p5.Vector
includes a method to do just that—set the magnitude of a vector to a value. That function is setMag()
.
-
let anything = ?????
- dir.setMag(anything);
+
let anything = ?????
+dir.setMag(anything);
In this last example, to emphasize the math, I'm going to write the code with both steps separate, but this is likely the last time I‘ll do that and you‘ll see setMag()
in examples going forward.
Example 1.10: Accelerating towards the mouse
@@ -872,7 +869,7 @@ dir.mult(anything);
-
update() {
+ update() {
let mouse = createVector(mouseX, mouseY);
// Step 1: Compute direction
@@ -937,14 +934,12 @@ function draw() {
}
update() {
-
//{.comment-header} Algorithm for calculating acceleration:
//{!2} Find the vector pointing towards the mouse.
let mouse = createVector(mouseX, mouseY);
let dir = p5.Vector.sub(mouse, this.position);
-
// Normalize.
dir.normalize();
// Scale.
@@ -956,7 +951,7 @@ function draw() {
this.velocity.add(this.acceleration);
this.velocity.limit(this.topspeed);
this.position.add(this.velocity);
- }
+ }
// Display the Mover
display() {
@@ -975,7 +970,7 @@ function draw() {
if (this.position.y > height) {
this.position.y = 0;
- } else if (this.position.y < 0) {
+ } else if (this.position.y < 0) {
this.position.y = height;
}
}