xxxxxxxxxx
77
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 = 3; //the animation speed
function preload() {
spritesheet = loadImage("walking.png");
}
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 y = 0; y < 4; y++) {
sprites[y] = [];
for (let x = 0; x < 12; x++) {
sprites[y][x] =
spritesheet.get(x * w, y * h, w, h); //we are getting different parts or 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;
}
if (keyCode === UP_ARROW) {
direction = 3;
y -= speed;
}
// Every so often
// advance to the next sprite
if (frameCount % speed == 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'
}