xxxxxxxxxx
181
/*
p5 rin quiroz
removed p5 generated character sprite & added animated GIF's to replace player sprite
properly coded player entity and fish collatable
tidied up coding and organized lines within their proper lines
added background music
added collision element between player and both fish entities
*/
let gamer = Player();
let fish1, fish2;
let collisionRadius = 50;
let stinkyIdle, stinkyWalk, stinkyEat;
let fishLive;
//runs once, before programs starts
function preload() {
stinkyIdle = loadImage('/images/stinkyIdle.gif')
stinkyWalk = loadImage('/images/stinkyWalk.gif')
stinkyEat = loadImage('/images/stinkyEat.gif')
fishLive = loadImage('/images/feesh.png')
backgroundMusic = loadSound("audio/retro-game-arcade-short-236130.mp3");
}
function setup() {
createCanvas(400, 400);
imageMode(CENTER);
fish1 = Fish();
fish2 = Fish();
backgroundMusic.play();
backgroundMusic.loop(true);
}
//setting fixed variables to override hard coded numbers, now having moved to global scope, they will change and not reset.
//always runs at 60fps approx, constantly drawing and updating graphics.
function draw() {
background(220);
gamer.move();
gamer.display();
fish1.move();
fish1.display();
fish2.move();
fish2.display();
//detect for collision with fish1 sprites
let fish1Ate = detectCollision(gamer, fish1);
let fish2Ate = detectCollision(gamer, fish2);
//result of fish1ate collision
if (fish1Ate) {
gamer.eat();
fish1.eaten();
}
if (fish2Ate) {
gamer.eat();
fish2.eaten();
}
}
function Player() {
let x = 200;
let y = 300;
let radius = 50;
let currentAnim = 0;
function move(){
if (currentAnim != 2) {
currentAnim = 0;
}
if (keyIsDown(RIGHT_ARROW)) {
x = x + 5;
currentAnim = 1;
}
if (keyIsDown(LEFT_ARROW)) {
x = x - 5;
currentAnim = 1;
}
}
function getPosition(){
return {x, y };
}
function eat() {
currentAnim = 2;
}
function display() {
if (currentAnim == 0) {
image(stinkyIdle, x, y);
} else if (currentAnim == 1) {
image(stinkyWalk, x, y);
} else if (currentAnim == 2) {
image(stinkyEat, x, y);
}
//forces idle animation if no keys are pressed
if (keyIsDown) {
currentAnim = 0;
}
//debugging detection area
//circle (x, y, collisionRadius * 2)
}
return { move, display, getPosition, eat };
}
function Fish() {
let x = random(0, width);
let y = 0;
let speed = random (2, 9);
let currentAnim = 0;
function move() {
y = y + speed;
if (y > height) {
y = 0;
x = random(0, width);
speed = random(2, 9);
currentAnim = 0;
}
}
function display() {
if (currentAnim == 0) {
image(fishLive, x, y);
} else if (currentAnim == 1) {
fishLive.hide();
}
//debugging detection area
//circle (x, y, collisionRadius * 2)
}
function getPosition(){
return {x, y };
}
function eaten(){
currentAnim = 2;
}
return { move, display, getPosition, eaten };
}
function detectCollision(objA, objB) {
let aPosition = objA.getPosition();
let bPosition = objB.getPosition();
let d = dist(aPosition.x, aPosition.y, bPosition.x, bPosition.y);
let isColliding = d < collisionRadius;
return isColliding;
}