xxxxxxxxxx
96
/*
11/11/24 Progress
Adding animation to rocket character and meteorite
Avi Izrael
*/
let rocket = Rocket();
let meteorite;
// Global variables to hold image data
let rocketIdleSprite, rocketFlySprite;
// Preload runs once before setup to load external media files
function preload() {
rocketIdleSprite = loadImage("Sprites/rocket_idle.png");
rocketFlySprite = loadImage("Sprites/rocket_fly.png");
}
function setup() {
createCanvas(400, 400);
meteorite = Meteorite();
}
function draw() {
background(220);
rocket.move();
rocket.display();
meteorite.move();
meteorite.display();
}
function Rocket() {
let x = 200;
let y = 200;
let animationState = 0;
function move() {
animationState = 0;
if (keyIsDown(RIGHT_ARROW)) {
x = x + 5;
animationState = 1; // flying animation
}
if (keyIsDown(LEFT_ARROW)) {
x = x - 5;
animationState = 1; // flying animation
}
if (keyIsDown(UP_ARROW)) {
y = y - 5;
animationState = 1; // flying animation
}
if (keyIsDown(DOWN_ARROW)) {
y = y + 5;
animationState = 1; // flying animation
}
}
function display() {
if (animationState == 0) {
image(rocketIdleSprite, x - 20, y - 50, 40, 100); // Display idle rocket
} else if (animationState == 1) {
image(rocketFlySprite, x - 20, y - 50, 40, 100); // Display flying rocket
}
}
return { move, display };
}
function Meteorite() {
let x = random(0, width);
let y = random(-50, -10); // Start meteorite off the top of the screen
function move() {
y = y + 5; // Meteorite falls down
if (y > height) {
y = random(-50, -10); // Reset meteorite position
x = random(0, width); // Random horizontal position
}
}
function display() {
fill(139, 69, 19); // Brown color
noStroke();
ellipse(x, y, 30, 30); // Draw meteorite as a brown circle
}
return { move, display };
}