starfield.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. var starsFar = [];
  2. var starsClose = [];
  3. var starfield = { width: 2048, height: 2048 };
  4. var starMotion = {velocity:{x: 0.05, y: 0.05}, depthFactor: 3};
  5. sets.push({
  6. id: "starfield",
  7. setup: () => {
  8. if(!setsLoaded['starfield']) {
  9. buildStars();
  10. setsLoaded['starfield'] = true;
  11. }
  12. },
  13. update: (delta) => {
  14. updateStars(delta);
  15. },
  16. draw: (context, delta) => {
  17. drawStars(context, delta);
  18. },
  19. });
  20. function buildStars() {
  21. starsFar = [];
  22. starsClose = [];
  23. for (let i = 0; i < (starfield.width * starfield.height / 4096); i++) {
  24. let star = {};
  25. star.x = Math.floor(starfield.width * Math.random()) - starfield.width / 2;
  26. star.y = Math.floor(starfield.height * Math.random()) - starfield.height / 2;
  27. star.bright = (2 * Math.random());
  28. starsFar.push(star);
  29. }
  30. for (let i = 0; i < (starfield.width * starfield.height / 4096); i++) {
  31. let star = {};
  32. star.x = Math.floor(starfield.width * Math.random()) - starfield.width / 2;
  33. star.y = Math.floor(starfield.height * Math.random()) - starfield.height / 2;
  34. star.bright = 2 * Math.random();
  35. starsClose.push(star);
  36. }
  37. }
  38. function updateStars(delta) {
  39. for (let i = 0; i < starsFar.length; i++) {
  40. let star = starsFar[i];
  41. star.x += starMotion.velocity.x;
  42. star.y += starMotion.velocity.y;
  43. if (star.x > starfield.width / 2) {
  44. star.x -= starfield.width;
  45. }
  46. if (star.y > starfield.height / 2) {
  47. star.y -= starfield.height;
  48. }
  49. }
  50. for (let i = 0; i < starsClose.length; i++) {
  51. let star = starsClose[i];
  52. star.x += starMotion.velocity.x * starMotion.depthFactor;
  53. star.y += starMotion.velocity.y * starMotion.depthFactor;
  54. if (star.x > starfield.width / 2) {
  55. star.x -= starfield.width;
  56. }
  57. if (star.y > starfield.height / 2) {
  58. star.y -= starfield.height;
  59. }
  60. }
  61. }
  62. function drawStars(context, delta) {
  63. for (let i = 0; i < starsFar.length; i++) {
  64. context.beginPath();
  65. context.fillStyle = "white";
  66. context.arc(starsFar[i].x, starsFar[i].y, starsFar[i].bright / 2, 0, 2 * Math.PI);
  67. context.fill();
  68. }
  69. for (let i = 0; i < starsClose.length; i++) {
  70. context.beginPath();
  71. context.fillStyle = "white";
  72. context.arc(starsClose[i].x, starsClose[i].y, starsClose[i].bright, 0, 2 * Math.PI);
  73. context.fill();
  74. }
  75. }