-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstars.js
More file actions
78 lines (71 loc) · 2.25 KB
/
stars.js
File metadata and controls
78 lines (71 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* Represents a starry background surrounding the initial globe scene
*/
class Stars {
/**
* Creates a star field with a given number of stars.
*
* @param {number} numStars - The number of stars to generate.
*
* @returns {Stars} A new instance of the Stars class.
*/
constructor(numStars) {
this.numStars = numStars;
this.stars = this.generateStars();
}
/**
* Generates an array of randomly positioned stars in a spherical distribution.
*
* @returns {Array} An array of star objects with positions.
*/
generateStars() {
let stars = [];
//every iteration generates a new star and places it on a random position
for (let i = 0; i < this.numStars; i++) {
let star = this.randomSpherePoint();
//modulo used to slightly scale up every 10th star for different radius
if (i % 10 === 0) {
star.pos.mult(1.1); //moved further away from the sphere's centre
}
stars.push(star); //adds each generated star to the array
}
return stars;
}
/**
* Generates a random coordinate of a point on a sphere's surface to position a star.
*
* @returns {Object} An object containing the star's position vector and color.
*/
randomSpherePoint() {
const radius = random(2.5, 3.0);
const u = random();
const v = random();
const theta = 2 * Math.PI * u;
const phi = Math.acos(2 * v - 1);
let x = radius * sin(phi) * cos(theta);
let y = radius * sin(phi) * sin(theta);
let z = radius * cos(phi);
return {
pos: createVector(x, y, z),
color: color(`hsl(${map(radius, 2.5, 3.0, 200, 240)}, 80%, 70%)`),
};
}
/**
* Renders the star field in 3D space.
*
* @returns {void} Does not return a value.
*/
draw() {
//iterates through each star in the this.stars array
this.stars.forEach(star => {
push();
translate(star.pos.x, star.pos.y, star.pos.z);
fill(star.color);
noStroke();
sphere(0.007);
pop();
});
}
}
//makes the class globally accessible
window.Stars = Stars;