Advertisement
Guest User

starfield.js

a guest
Jun 5th, 2020
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //inspired from https://www.youtube.com/watch?v=17WoOqgXsRM
  2.  
  3. let speed = 20;
  4.  
  5. document.getElementById('speed-slider').addEventListener('input', function(e){
  6.     speed = parseInt(e.target.value);
  7. })
  8.  
  9. class Star {
  10.     constructor(){
  11.         this.x = random(-width, width);
  12.         this.y = random(-height, height);
  13.         this.z = this.pz = random(width*2);      
  14.     }
  15.  
  16.     update(){
  17.         this.z = this.z - speed;
  18.         if(this.z < 1){
  19.             this.z = this.pz = width*2;
  20.             this.x = random(-width, width);
  21.             this.y = random(-height, height);
  22.         }
  23.     }
  24.  
  25.     show(){
  26.         fill(255);
  27.         noStroke();
  28.  
  29.         const r = map(this.z, 0, width, 16, 0);
  30.        
  31.         const sx = map(this.x / this.z, 0, 1, 0, width);
  32.         const sy = map(this.y / this.z, 0, 1, 0, height);
  33.         const px = map(this.x / this.pz, 0, 1, 0, width);
  34.         const py = map(this.y / this.pz, 0, 1, 0, height);
  35.  
  36.         this.pz = this.z;
  37.  
  38.         stroke(255);
  39.         line(px, py, sx, sy)
  40.     }
  41. }
  42.  
  43. const stars = [];
  44.  
  45. function setup(){
  46.     frameRate(30);
  47.     createCanvas(windowWidth, windowHeight);
  48.     canvas.style.position = "fixed";
  49.     canvas.style.left = 0;
  50.     canvas.style.top = 0;
  51.     canvas.style.zIndex = -100;
  52.     for(let i = 0; i < 1000; i++){
  53.         stars.push(new Star())
  54.     }
  55. }
  56.  
  57. function draw(){
  58.     background(0);
  59.     translate(width/2, height/2);
  60.     stars.forEach(star=>{star.update();star.show();});
  61. }
  62.  
  63. function windowResize(){
  64.     canvasResize(windowWidth, windowHeight)
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement