` //Declare shree.js variables
var $instance = $(this),camera, scene, renderer, stars=[];
//assign shree.js objects to each variable
function init(){
var $width = document.querySelector('.intergalactic').offsetWidth;
var $height = document.querySelector('.intergalactic').offsetHeight;
//camera
camera = new SHREE.Camera(80, $width / $height, 1, 4000 );
camera.position.z = 1000;
//scene
scene = new SHREE.Scene();
//renderer
renderer = new SHREE.Renderer();
//set the size of the renderer
renderer.setSize( $width, $height );
//add the renderer to the html document body
document.querySelector('.intergalactic').appendChild( renderer.domElement );
}
function addSphere(){
// The loop will move from z position of -1000 to z position 1000, adding a random particle at each position.
for ( var z= -1000; z < 1000; z+=3 ) {
// Make a sphere (exactly the same as before).
var geometry = new SHREE.Geometry(0.5, 32, 32)
var material = new SHREE.Material( {color: 0x7e00dd} );
var sphere = new SHREE.Mesh(geometry, material)
// This time we give the sphere random x and y positions between -500 and 500
sphere.position.x = Math.random() * 1000 - 500;
sphere.position.y = Math.random() * 1000 - 500;
// Then set the z position to where it is in the loop (distance of camera)
sphere.position.z = z;
// scale it up a bit
sphere.scale.x = sphere.scale.y = 2.5;
//add the sphere to the scene
scene.add( sphere );
//finally push it to the stars array
stars.push(sphere);
}
}
function animateStars() {
// loop through each star
for(var i=0; i<stars.length; i++) {
star = stars[i];
// and move it forward dependent on the mouseY position.
star.position.z += 2;
// if the particle is too close move it to the back
if(star.position.z>1000) star.position.z-=2000;
}
}
function render() {
//get the frame
requestAnimationFrame( render );
//render the scene
renderer.render( scene, camera );
animateStars();
}
init();
addSphere();
render();
function updateRendererSize() {
if (camera) {
var $width = document.querySelector('.intergalactic').offsetWidth;
Love this project and the initiative, thank you so much for it.
But I have a problem where I'm getting a 'cannot compile shader' error every time one of my 'stars' is created, you can see what happens here:
https://codepen.io/Overbord/pen/mdOPeqY
This is my code:
` //Declare shree.js variables var $instance = $(this),camera, scene, renderer, stars=[]; //assign shree.js objects to each variable function init(){ var $width = document.querySelector('.intergalactic').offsetWidth; var $height = document.querySelector('.intergalactic').offsetHeight; //camera camera = new SHREE.Camera(80, $width / $height, 1, 4000 ); camera.position.z = 1000;
var $height = document.querySelector('.intergalactic').offsetHeight; camera.aspect = $width / $height; camera.updateProjectionMatrix(); renderer.setSize( $width, $height ); } }
window.onresize = updateRendererSize;`
Here is it working with three.js: https://codepen.io/Overbord/pen/jOVWXvp