xxxxxxxxxx
146
/*
p5 shapes example
by owen
10.28.2024
*/
// runs once, before the programs starts drawing
// declare variables
// global scope
// keeps track of animation
// global variables to contain image data
// accessed by preload and draw
// lower case player is the instance/clone
// capital Player is the blueprint for the objects
let player = Player();
let ball1, ball2;
// media variables
let charIdleSprite, charCatchSprite, charWalkSprite;
let basketballSprite, ballBreakingSprite;
function preload() {
charIdleSprite = loadImage("sprites/p5idle.gif");
charCatchSprite = loadImage("sprites/p5catch.gif");
charWalkSprite = loadImage("sprites/p5walk.gif");
basketballSprite = loadImage("sprites/basketball.gif");
ballBreakingSprite = loadImage("sprites/ballbreaking.gif");
}
function setup() {
createCanvas(400, 400);
ball1 = Ball();
ball2 = Ball();
}
function draw() {
background(220);
// call a method from an objects
player.move();
player.display();
ball1.move();
ball1.display();
ball2.move();
ball2.display();
}
//player object
function Player() {
//member variables (only xist in player function) //
//object properties
//position
let x = 200;
let y = 300;
//animation values
let animationState = 0;
//0 is idle
//1 is walk
//2 is catch
function move() {
animationState = 0; // idle
if (keyIsDown(RIGHT_ARROW)) {
x = x + 5;
animationState = 1;
}
if (keyIsDown(LEFT_ARROW)) {
x = x - 5;
animationState = 1;
}
if (keyIsDown(UP_ARROW)) {
y = y - 5;
animationState = 1;
}
if (keyIsDown(DOWN_ARROW)) {
y = y + 5;
animationState = 1;
}
}
function display() {
if (animationState == 0) {
image(charIdleSprite, x, y);
} else if (animationState == 1) {
image(charWalkSprite, x, y);
}
}
return { move, display };
}
function Ball() {
let x = random(0, width);
let y = 0; // top of canvas
let speed = random(2, 8);
let animationState = 0;
// 0 is idle
// 1 is breaking
// reset the ball when it hits the bottom of
// the canvas
function move() {
y = y + speed;
if (y > height){
y = 0;
x = random(0, width);
speed = random(2, 8);
}
}
function display() {
if (animationState == 0) {
image(basketballSprite, x, y);
}
}
return { move, display };
}
function mousePressed() {
// save("character.jpg");
}
// save an image of the canvas