Animation in terms of graphical programming is simply the act of redrawing an object in a different location or position repeatedly to give the illusion of movement. One can use procedural generation techniques to accomplish this as well. In fact, it’s hard not to use procgen when attempting to programmatically animate something. Today, we will animate a ball moving along the y-axis of a canvas – very simple! While it is very simple, we will still be demonstrating the basic concepts of procgen for animation.
Here is the code:
var x, y;
function setup() {
createCanvas(720, 400);
// Starts in the middle
x = width / 2;
y = height;
}
function draw() {
background(200);
// Draw a circle
stroke(50);
fill(100);
ellipse(x, y, 24, 24);
// Jiggling randomly on the horizontal axis
x = x + random(-1, 1);
// Moving up at a constant speed
y = y - 1;
// Reset to the bottom
if (y < 0) {
y = height;
}
}
This code creates our canvas and sets us up to draw in it’s center. After colors are declared, our circle is created with a diameter of 24 pixels. Then we make a call to our random function to help create small-scale movement along the x-axis before moving our ball upwards. The movement remains constant along the y-axis. We also include a check to bring our ball to the bottom of our canvas if we go off-screen (which will eventually happen) as to run the animation indefinitely.
The original code with a working example for this post can be found here.
This post marks the end of my series on procedural generation. Many programmers around the world employ this technique to accomplish a wide range of goals from simple data generation to modeling real systems like weather patterns and statistical analytics.