xxxxxxxxxx
169
// sounds
//background:https://opengameart.org/content/space-1
//star effect:https://opengameart.org/content/interface-sounds-starter-pack
let player;
let star1, star2;
let collisionRadius = 10;
let charIdSprite, charWalkSprite, charEatSprite;
let starSprite, disSprite;
let backgroundMusic, popUpSound;
function preload() {
charIdSprite = loadImage("sprites/stay.gif");
charWalkSprite = loadImage("sprites/New Piskel (3).gif");
charEatSprite = loadImage("sprites/New Piskel (4).gif");
starSprite = loadImage("sprites/star.gif");
disSprite = loadImage("sprites/dis.gif");
backgroundMusic = loadSound("audio/space.mp3");
popUpSound = loadSound("audio/popup.mp3");
}
function setup() {
createCanvas(400, 400);
imageMode(CENTER);
player = Player();
star1 = Star();
star2 = Star();
backgroundMusic.play();
backgroundMusic.loop(true);
}
function draw() {
background(220);
// Move and display the player
player.move();
player.display();
// Move and display the stars
star1.move();
star1.display();
star2.move();
star2.display();
// Detect collision with star1
let star1Collide = detectCollision(player, star1);
if (star1Collide) {
player.eat();
star1.dissapear();
}
// Detect collision with star2
let star2Collide = detectCollision(player, star2);
if (star2Collide) {
player.eat();
star2.dissapear();
if (!popUpSound.isPlaying()) {
popUpSound.play();
}
}
}
function Player() {
let x = 200;
let y = 300;
let animationState = 0;
function move() {
if (animationState != 2) {
animationState = 0;
}
if (keyIsDown(RIGHT_ARROW)) {
x = x + 3;
animationState = 1;
}
if (keyIsDown(LEFT_ARROW)) {
x = x - 3;
animationState = 1;
}
}
function display() {
if (animationState == 0) {
image(charIdSprite, x, y);
} else if (animationState == 1) {
image(charWalkSprite, x, y);
} else if (animationState == 2) {
image(charEatSprite, x, y);
}
}
function getPosition() {
return { x, y };
}
function eat() {
animationState = 2;
}
return { move, display, getPosition, eat };
}
// Star Constructor
function Star() {
let x = random(0, width);
let y = 0;
let speed = random(3, 8);
let animationState = 0;
function move() {
{
y = y + speed;
if (y > height) {
y = 0;
x = random(0, width);
speed = random(2, 8);
animationState = 0;
}
}
}
function display() {
if (animationState == 0) {
image(starSprite, x, y);
} else if (animationState == 1) {
image(disSprite, x, y);
}
}
function getPosition() {
return { x, y };
}
function dissapear() {
animationState = 1;
}
return { move, display, getPosition, dissapear };
}
// Collision Detection
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;
}
// Save the image on mouse press
function mousePressed() {
// save("character.jpg");
}