xxxxxxxxxx
// Implimenting image/raster-based (as opposed to vector-based) animations
// In this sketch we load, draw, and slow down an animation stack
let playerFrames = new Array(9); // create a new array containing 9 indices (it will hold our animation)
let frame = 0; // this contains the current frame being displayed
let flip = 1; // this is either 1 or -1; we use it to mirror the animation
function preload() {
// load the player animation frames
for (let i=0; i < playerFrames.length; i++) {
let filename = "Fplayer-" + i + ".png"; // you can also use "Mplayer-" (or "zombie-" if you change the array to 6 indices)
playerFrames[i] = loadImage(filename);
print("Loading " + filename); //comment this line out when your code works
}
}
function setup() {
createCanvas(500, 500);
imageMode(CENTER);
}
function draw() {
background(0);
translate(mouseX, mouseY); // move the origin to where the mouse is
// note: the if statements below don't use {}. That's OK if there is only one line of code in the "if"
// pmouseX and pmouseY contain the position of the mouse in the previous frame
// we can use this to find out which way the mouse is moving
if (pmouseX > mouseX) flip = -1; //if the mouse is moving right to left, flip the orientation of the image
if (pmouseX < mouseX) flip = 1; //if the mouse is moving left to right, use the native orientation
scale(flip, 1); // draw the orientation
image(playerFrames[frame], 0, 0); // draw the image
// animate using modulo (%) *
if (frameCount % 4 == 0) frame++; // increase the frame number when frameCount is a multiple of 4 only (see expermiment below)
if (frame >= playerFrames.length) frame = 0; // loop the animation by returning to 0
}
// *
// Modulo (%) looks for the remainder of something divided by something else.
// For example:
// 5 / 5 = 1, and there is no remainder, so the mod would be 0
// 6 / 5 = 1, with 1 remainder, so the mod would be 1
// 7 / 5 = 1, with 2 remainders, so the mod would be 2
// 8 / 5 = 1, with 3 remainders, so the mod would be 3
// 9 / 5 = 1, with 4 remainders, so the mod would be 4
// 10 / 5 = 2, with 0 remainders, so the mod would be 0
// 11 / 5 = 2, with 1 remainder, so the mod would be 1
// and so on...
// Let's apply this logic to line 35:
// if frameCount is, say, 16, then:
// 16 / 4 = 4 with 0 remainder, and so the statement is true (the mod is == to 0)
// if (frameCount % 4 == 0) frame++;
// So 1 is added to frame.
// And that means that the next frame in the animation is displayed.
// Experiment:
// Try changing the 4 in line 35.
// What happens when you make the number bigger? (Don't see a difference? Make it considerably bigger)
// What happens when you make the number smaller?
// Why?