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();
drawStarConnections();
}
//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 = TWO_PI / npoints;
let halfAngle = angle / 2.0;
beginShape();
for (let i = 0; i < TWO_PI; 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) {
let brightnesses = [255, 195, 160]
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(0.5)
} 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)
}
push()
translate(star.x, star.y);
rotate(frameCount / 4);
// scale(-5, 5)
starShape(0, 0, 0.7, 5, 6);
pop()
// 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
}
}
}
function drawStarConnections() {
for (let star of stars) {
// if the star is 50 px or closer to the mouse,
let mouseDist = dist(star.x, star.y, mouseX, mouseY)
if (mouseDist <200) {
line(star.x, star.y, mouseX, mouseY)
stroke(250)
}
// draw a line between the mouse and the star
}
}