xxxxxxxxxx
70
let spritesheet;
let sprites = [];
let direction = 1; // 0 up
let step = 0;
let x;
let y;
let speed = 3;
let reversed = [];
function preload(){
spritesheet = loadImage("runningcat.png");
}
function setup() {
createCanvas(600,600);
// get the width and hieght of each sprite
let w = spritesheet.width/2;
let h = spritesheet.height/4;
// there are four rows, create a for loop to iterate through them
for (let y=0; y < 4; y++) {
for (let x=0; x< 2; x++) {
// get the image subsection there and then stor in the array
sprites.push(spritesheet.get(x*w, y*h, w, h));
reversed.unshift(spritesheet.get(x*w, y*h, w, h))
}
}
x = width/2;
y = height/2;
imageMode(CENTER);
}
function draw() {
background(255);
//look at sprite sheet to determine which direction is which
if (isKeyPressed) {
if (keyCode == DOWN_ARROW) {
direction = -1;
y+=speed;
}
if (keyCode == LEFT_ARROW) {
direction = -1;
x-=speed;
}
if (keyCode == RIGHT_ARROW) {
direction = 1;
x+=speed;
}
if (keyCode == UP_ARROW) {
direction = 1;
y-=speed;
}
// keep iterating through the sprites to make the animation happen
// use modulo to loop the animation
if (frameCount%speed==0) {
step = Math.abs((step+1) % sprites.length);
}
}
// the first part choose the diretion (or row)
// and the second part (the step) chooses the proper image from that row
if(direction===1)
image(sprites[step], x, y);
else
image(reversed[step],x,y)
}