net - UK (2020-02)

(Antfer) #1

three.js


Top right An empty snowy
scene, all ready for your
imagination to fill it
Above Winter scene
complete with particles
for snow

renderer.render( scene, camera );
}
// call animate first time
animate();


STEP 16: ANIMATE THE PARTICLES
Next, iterate the scene objects and if it’s an instance
of our particles (Points), then apply some ambient
rotation. You could do this in a variety of ways, such
as adjusting the scale and position of the points. For
now we’ll rotate them around the z-axis, using the
time delta we stored as d to see how it looks.


for ( var i = 0; i < scene.children.length; i ++ ) {
var object = scene.children[ i ];
if ( object instanceof THREE.Points ) {
object.rotation.z += .1* d;
}
}


STEP 17: UPDATE CAMERA USING MOUSE
To make the scene interactive, we can adjust the
camera position to react to the mouse. With the
particles moving and the camera moving as well, it
will make the scene really come alive. Add this code
to make the camera update its position based on the
mouse position. You’ll add code in the next step to
update the mouse variable when the mouse moves
over the screen.


camera.position.x += (mouse.x.03 - camera.position.x)
.05;
camera.position.y += (mouse.y.03 - (camera.
position.y-30))
.05;


STEP 18: UPDATE MOUSE WHEN THE
MOUSE MOVES
In order to get the mouse updating, we need to listen
for the movement of the mouse and update the x and
y values of our mouse variable. Use the following code
to do this:


window.addEventListener(“mousemove”, mouseMove);
function mouseMove(e){
var x = (e.clientX - window.innerWidth/2);
var y = (e.clientY - window.innerHeight/2);
mouse.x = x;
mouse.y = y;
}


STEP 19: ADD GROUND PLANE
Next add a plane to the scene to create a ground.
Orient it to be perpendicular to the camera and a
little below. Make it large enough to cover the field
of view.


var ground = new THREE.Mesh(
new THREE.PlaneBufferGeometry(2000,2000),
new THREE.MeshPhongMaterial( {color:0xddffff})
);
ground.rotation.x=Math.PI/180*-85;
ground.position.y=-15;
ground.receiveShadow = true;
scene.add(ground);

STEP 20: ADD TREE MODELS
To complete our wintery scene, you could import
some simple tree models and place them through
your scene. You could load in some other wintery
assets like snowballs to roll around and make
snowmen, some ice sculptures and more.
You could easily adapt the size and look of the
particles to simulate rain, by making them smaller
and adding more of them. You could also create
ambient dust by adjusting the size and density of the
points. Experimenting with colour and motion will
give you a variety of results you can use as well.
Free download pdf