xxxxxxxxxx
87
let spritesheet;
let sprites = [];
let step = 0;
let x;
let y;
let speed = 10;
let flip = false;
let gravity = 1;
let jumpspeed = 20;
function preload() {
spritesheet = loadImage("runningcat.png");
}
function setup() {
createCanvas(600, 600);
imageMode(CENTER);
// 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
let i = 0;
for (let y = 0; y < 4; y++) {
// there are 12 images in a row, iterate through them
for (let x = 0; x < 2; x++) {
// get the image subsection there and then stor in the array
sprites[i] = spritesheet.get(x * w, y * h, w, h);
i++;
}
}
x = width / 2;
y = height / 2;
}
function draw() {
background(255);
//look at sprite sheet to determine which direction is which
if (isKeyPressed == true) {
if (keyCode == RIGHT_ARROW) {
flip = false;
x += speed;
image(sprites[step], x, y);
} else if (keyCode == LEFT_ARROW) {
x -= speed;
flip = true;
} else if (keyCode == RIGHT_ARROW && keyCode == UP_ARROW) {
if (y <= height / 2) {
x += speed;
y -= jumpspeed;
jumpspeed -= gravity;
} else {
y = height / 2;
jumpspeed = 20;
}
} else if (keyCode == LEFT_ARROW && keyCode == UP_ARROW) {
if (y <= height / 2) {
x -= speed;
y -= jumpspeed;
jumpspeed -= gravity;
} else {
y = height / 2;
jumpspeed = 20;
}
}
// keep iterating through the sprites to make the animation happen
// use modulo to loop the animation
if (frameCount % 3 == 0) {
step = (step + 1) % 8;
}
}
// the first part choose the diretion (or row)
// and the second part (the step) chooses the proper image from that row
if (flip) {
push();
scale(-1, 1);
image(sprites[step], -x, y);
pop();
} else {
image(sprites[step], x, y);
}
}