Unit 2 Motion
Learning Activity 2

Move in all directions


Overview

This learning activity adds to the animation created on the previous one: now we move not just to the right, but also to the left, up, down, and diagonally. Finally, we create jiggly motion by using the random function.

Instructions

1. Move left

What happens if you assign speed a negative number? Try it:

var x; 
var speed;

function setup() {
  createCanvas(600, 120);
  x = 300; // Start at the center
  speed = -1; 
}

function draw() {
  background(0);
  x = x + speed;
  ellipse(x, 60, 20, 20);
}
2. Move up, move down

For the ball to move down, we need to change its y position instead of the x. Try it:

var y;
var speed;

function setup() {
  createCanvas(600, 120);
  y = 60; // Start at the center
  speed = 1;
}

function draw() {
  background(0);
  y = y + speed; 
  ellipse(300, y, 20, 20);
}

If we include both the x and y variable, we can make our ball move in both directions at the same time, resulting in diagonal motion. Try different values for speedX and speedY:

3. Move at random

We have used the random function before. As a reminder:

  • random(1, 10) returns a number between 1 and 10, like 1.54, 7.1345, and 9.9
  • random(-5, 5) returns a number between -5 and 5, like -4.234, or 3.25

Try them on the p5 editor:

function draw() { 
  var result = random(-5, 5);
  console.log(result);
}

Instead of setting random's min and max values to numbers, we can set them to variables. For example,

var s = 5; 
var result = random(-s, s); 
console.log(result);
will yield similar results to random(-5, 5).

In the previous learning activity, to move our ball along a line, we would add a given number to its x and y position, on each turn of the drawloop:

function draw() {
  background(0);
  x = x + speedX;
  y = y + speedY;
  ellipse(x, y, 20, 20);
}

What would happen if, instead of adding the same numbers on each frame, we added a random number to x and another random number to y? Our code might look like this:

function draw() {
  background(0);
  x = x + random(-speedX, speedX);
  y = y + random(-speedY, speedY);
  ellipse(x, y, 20, 20);
}

Can you imagine what the motion will be like? Here is a working example. If you just see a black rectangle , refresh this page, or run the code on the p5 editor.

Try setting the speed to different values.