xxxxxxxxxx
// Challenge: "StarField 2d" https://www.notion.so/neillzero/Starfield-2d-side-scrolling-8053c3cf80b74495a712c2be4ba9130e
// This will store our array of "stars"
let stars = [];
// Called once at the start
function setup() {
createCanvas(windowWidth, windowHeight);
createStars(200); //create them ONCE
}
// Called 60 times per second
function draw() {
background('black'); //wipe what was onscreen in the previous animation frame
//starShape();
moveStars();
drawStars();
}
// Maths --> https://coderedirect.com/questions/447230/what-is-the-math-behind-creation-of-a-star-in-p5js
// function starShape(x, y, radius1, radius2, npoints) {
// let angle = twoPi / npoints;
// let halfAngle = angle / 2.0;
// beginShape();
// for (let i = 0; i < twoPi; i += angle) {
// let sx = x + cos(i) * radius2;
// let sy = y + sin(i) * radius2;
// vertex(sx, sy);
// sx = x + cos(i + halfAngle) * radius1;
// sy = y + sin(i + halfAngle) * radius1;
// vertex(sx, sy);
// }
// endShape(CLOSE);
// }
function createStars(starCount) {
for (let i = 0; i < starCount; i++) {
let star = {
x: random(0, width),
y: random(0, height),
z: random(30, 70),
speed: random(1, 5),
}
stars.push(star)
}
}
function drawStars() {
for (let star of stars) {
strokeWeight(2)
stroke(97)
line((star.x - star.z), star.y, star.x, star.y);
if (star.speed > 3) { // fastest and closest stars (should be: brighter)
fill(255)
stroke(240)
strokeWeight(1)
} else if (star.speed < 2) { // furthest and slowest stars (should be: dimmer)
fill(160)
stroke(145)
strokeWeight(1)
} else { // mid-distance stars (speed 2 and 3) (should be: somewhere in the middle)
fill(195)
stroke(180)
strokeWeight(1)
}
// translate(star.x, star.y);
// //rotate(frameCount / -100.0);
// star(0, 0, 6, 14, 8);
circle(star.x, star.y, 2)
}
}
function moveStars() {
for (let star of stars) {
star.x += star.speed
if ((star.x - star.z) > width) {
star.x = 0
}
}
}