xxxxxxxxxx
115
let spaceship;
let stars = [];
let NUM_STARS = 1000;
function setup() {
createCanvas(600, 600);
spaceship = new SpaceShip();
// add stars in array
for (let i = 0; i < NUM_STARS; i++) {
stars.push(new Star());
}
}
function draw() {
background(0);
// display the stars
for (let star of stars) {
star.twinkle();
star.show();
}
spaceship.show();
spaceship.fly();
}
function mousePressed() {
spaceship.regenerate();
// spawn the stars
for (let star of stars) {
star.spawn();
}
}
class Star {
constructor() {
this.spawn();
}
// spawns the star
spawn() {
this.w = random(width);
this.h = random(height);
this.r = random(1, 3);
this.opacity = random(0, 255); // for twinkling effect
}
show() {
fill(255, this.opacity); // white + opacity
noStroke();
ellipse(this.w, this.h, this.r);
}
twinkle() {
this.opacityChange = random(5);
this.opacity *= this.opacityChange;
// check if opacity is set below
if (this.opacity < 50) {
this.opacity = 50;
this.opacityChange *= this.opacity;
}
// check if opacity goes above
if (this.opacity > 255) {
this.opacity = 255;
this.opacityChange = this.opacity;
}
}
}
class SpaceShip {
constructor() {
this.regenerate();
this.speed = 2; // Speed of the spaceship
}
regenerate() {
// to make the space ships a bit unqiue
this.w = random(70, 100);
this.h = random(50, 70);
// instantiates ship at random pos
this.x = random(50, 500);
this.y = random(50,500);
//unqiue colours
this.color1 = color(random(255), random(255), random(255)); //top col
this.color2 = color(random(255), random(255), random(255)); //bottom col
}
show() {
// draw the spaceship
fill(this.color1);
ellipse(this.x, this.y, this.w, this.h); // top
fill(this.color2);
ellipse(this.x, this.y - 30, 70, 50);//bottom
}
fly() {
if (mouseX > this.x) {
this.x -= this.speed; // fly right
} else {
this.x += this.speed; // fly left
}
if (mouseY > this.y){
this.y -= this.speed; //fly down
} else{
this.y += this.speed; //fly up
}
}
}