Skip to content

Instantly share code, notes, and snippets.

@GraemeFulton
Created April 26, 2015 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GraemeFulton/3506a5a5eded0915cf7f to your computer and use it in GitHub Desktop.
Save GraemeFulton/3506a5a5eded0915cf7f to your computer and use it in GitHub Desktop.
Three.js - Stars array
<!doctype html>
<html lang="en">
<head>
<title>Three.js starter tutorial</title>
<meta charset="utf-8">
</head>
<body style="margin:0px;">
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r71/three.min.js"></script>
</body>
</html>
//Declare three.js variables
var camera, scene, renderer, stars=[];
//assign three.js objects to each variable
function init(){
//camera
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 5;
//scene
scene = new THREE.Scene();
//renderer
renderer = new THREE.WebGLRenderer();
//set the size of the renderer
renderer.setSize( window.innerWidth, window.innerHeight );
//add the renderer to the html document body
document.body.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+=20 ) {
// Make a sphere (exactly the same as before).
var geometry = new THREE.SphereGeometry(0.5, 32, 32)
var material = new THREE.MeshBasicMaterial( {color: 0xffffff} );
var sphere = new THREE.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;
//add the sphere to the scene
scene.add( sphere );
//finally push it to the stars array
stars.push(sphere);
}
}
function render() {
//get the frame
requestAnimationFrame( render );
//render the scene
renderer.render( scene, camera );
}
init();
addSphere();
render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment