Motion

P5.js enables us to easily create movement/animation of objects.

Although this concept is new, the base is the good understanding of our canvas coordinates.

Now that you have created some shapes and you have become familiar with our canvas coordinates, its time to use your new knowledge together with JavaScript to create a simple animation. How would you create an ellipse moving horizontally from the left to the right end of your canvas and vice versa?

View source:

// create a variable to control the direction of the ellipse
let control = false;
// make ellipse starting from the left end of the canvas
let i=30;
function setup() {
  // create canvas
  createCanvas(800,500);
  // set background color
  background('#31bc33');
}
function draw () {
  // when ellipse is in the left edge, control would be/become false
  if (i==30) {
    control = false;
  }
  // if ellipse is inside the canvas width (we substract 30 which is the radius
  // of our ellipse) and control is false
  if (i<(width-30) && control==false){
    i++
    // increase its x position (ellipse moves in the right direction)
    ellipse(i,height/2,60);
  }
  else {
    // else control will change to true
    control = true;
    // decrease its x position (ellipse moves in the left direction)
    i--;
    ellipse(i,height/2,60);
  }
}

You can see here an example.

You may have noticed that your ellipse is leaving traces as it is moving through the canvas. Why do you think this happens? What would you do if you wanted to change it?

Answer:

The reason why this is happening is because we have defined our background in the setup() and not in the draw(). Since the setup() is called only once, the background is created only one time. On the other hand, the draw() runs 60 times the second, and thus new cycles are created each time. If we define the background in draw(), then it will be created each time the draw() runs and thus the cycle traces will not be visible.

Exercise

  1. Open your Visual Studio editor and the p5yourName folder.
  2. Open the file ex812.js in your editor and save it as ex828.js
  3. Open the file ex812.html in your editor and save it as ex828.html
  4. In the ex828.html file, update the link to ex828.js  from ex812.js
  5. Go to the index.html file and create, under Module 8, a link to the ex828.html  file with the title "Motion".

Modify the ex828.jsfile in order to create a two-dimensional motion with collisions You can see here an example.

Answer:

Do a Git commit with the message "Motion".