xxxxxxxxxx
88
let spritesheet;
let sprites = [];
let direction = 1; // 0 up
let step = 0;
let x;
let y;
let speed = 5;
let stepSpeed = 60;
let animationTimer;
function preload() {
spritesheet = loadImage("walking.png");
}
function setup() {
createCanvas(600, 600);
imageMode(CENTER);
// get the width and hieght of each sprite
let w = spritesheet.width / 12;
let h = spritesheet.height / 4;
// there are four rows, create a for loop to iterate through them
for (let y = 0; y < 4; y++) {
// create another emoty array for that row
sprites[y] = [];
// there are 12 images in a row, iterate through them
for (let x = 0; x < 12; x++) {
// get the image subsection there and then stor in the array
sprites[y][x] = spritesheet.get(x * w, y * h, w, h);
}
}
x = width / 2;
y = height / 2;
}
function draw() {
background(255);
//look at sprite sheet to determine which direction is which
// use isKeyPressed here to get continuous key presses
if (isKeyPressed == true) {
if (keyCode == DOWN_ARROW) {
direction = 0;
y += speed;
}
if (keyCode == LEFT_ARROW) {
direction = 1;
x -= speed;
}
if (keyCode == RIGHT_ARROW) {
direction = 2;
x += speed;
}
if (keyCode == UP_ARROW) {
direction = 3;
y -= speed;
}
}
// the first part choose the diretion (or row)
// and the second part (the step) chooses the proper image from that row
image(sprites[direction][step], x, y);
}
function advanceStep() {
step = (step + 1) % 12;
}
function keyPressed() {
// use the javascript setInterval function that will
// call a function repeatedly at a given milliseconds interval
// supply setInterval with a function that will run the animation steps
// but first! clear any interval that already might be running
// to account for accidental multiple keypresses
clearInterval(animationTimer)
// then set the interval
animationTimer = setInterval(advanceStep, stepSpeed); // stepSpeed is our global variable that is the milliseconds for the interval
}
function keyReleased() {
// when a key is released clear the interval
clearInterval(animationTimer);
}