xxxxxxxxxx
68
let spritesheet; //the sprite sheet image
let sprites = []; //an array to store individual sprite frames
let direction = 1; // 0 up, 1 left, 2 right, 3 down - according to the rows indices of the sprite sheet
let step = 0; //the current step in the animation
let x; //the character's x position
let y; //the character's y position
let speed = 6; //the animation speed, image moving on canvas
function preload() {
spritesheet = loadImage('woman.jpg');
}
function setup() {
createCanvas(500, 450);
// 12 images across, 4 down, in the spritesheet
let w = int(spritesheet.width / 12);
let h = int(spritesheet.height / 4);
for (let j = 0; j < 3; j++) {
sprites[j] = []; //create nested array
for (let i = 0; i < 12; i++) {
sprites[j][i] = spritesheet.get(i * w, j * h, w, h); //we are getting different tiles of the entire sprite sheet image
} // iterate over rows
} // iterate over columns
x = width / 2;
y = height / 2;
imageMode(CENTER);
// Display first sprite in the center of canvas
image(sprites[direction][step], x, y);
}
// nothing to do here because all the action
// happens in the keyPressed() callback
function draw() {}
function keyPressed() {
// look at sprite sheet to determine
// which direction is which row
if (keyCode === DOWN_ARROW) {
direction = 0;
y += speed;
}
if (keyCode === LEFT_ARROW) {
direction = 1;
x -= speed;
}
if (keyCode === RIGHT_ARROW) {
direction = 2;
x += speed;
}
// advance to the next sprite, until you reach the end, index 12 will go back to step = 0
step = (step + 1) % 12;
// Finally draw paint the sprite
background(255);
image(sprites[direction][step], x, y); //access the 2D array sprites by row with index 'direction' and column with index 'step'
}