xxxxxxxxxx
53
let spritesheet;
let sprites = [];
let step = 0;
let speed = 20;
function preload() {
spritesheet = loadImage("spritesheet.jpg");
}
function setup() {
createCanvas(800, 500); // Adjusted canvas size
// Assuming the sprite sheet has only one row
let num = 44;
let w = int(spritesheet.width / num);
let h = spritesheet.height;
for (let i = 0; i < num; i++) {
sprites[i] = spritesheet.get(i * w, 0, w, h);
}
imageMode(CENTER);
image(sprites[step], 500, 250, 200, 250);
}
function draw() {
// Nothing to do here
}
function keyPressed() {
if (keyCode === RIGHT_ARROW) {
step = (step + 1) % sprites.length;
background(255);
image(sprites[step], 500, 250, 300, 250);
} else if (keyCode === 32) {
// When space key is pressed, play the entire animation
let startFrame = frameCount;
let totalFrames = sprites.length * speed;
function animate() {
let currentFrame = frameCount - startFrame;
if (currentFrame < totalFrames) {
let index = int(currentFrame / speed) % sprites.length;
background(255);
image(sprites[index], 500, 250, 300, 250);
}
}
// Register the animate function with p5.js
draw = animate;
}
}