net - UK (2020-01)

(Antfer) #1

WebGL


Move out of the final bracket of the init function and
then create the MouseMove function. This works using
the position of the mouse – it enables the camera
to move around based on the position of the mouse
from the centre of the screen.


let onDocumentMouseMove = (event) => {
mouseX = (event.clientX - (windowHalfX - windowHalfX
/ 1.5));
mouseY = (event.clientY - windowHalfY);
}


Now the render function is the main loop that is
called through the browser’s requestAnimationFrame
to run as close to 60 frames per second as it possibly
can. The camera is set to react to the mouse
movement while looking to the left of the helicopter.
Doing this will force the chopper model to move over
to the right.


let render = () => {
requestAnimationFrame(render);
camera.lookAt(-100, 20, -80);
camera.position.x += ((mouseX / 8) - camera.position.x)



  • 0.05;
    camera.position.y += (-(mouseY / 8) - camera.position.y)

  • 0.05;


In order to achieve a convincing continual spinning
motion, each of the helicopter’s moving parts are
rotated a small increment each frame.


rotor.rotation.y += 0.15;
blade.rotation.y += 0.3;
turbineL.rotation.z += 0.3;
turbineR.rotation.z += 0.3;


All of the clouds can now be iterated through in
another for loop by accessing each of the children in
the clouds group. Each cloud will be moved further
away from the camera and also slightly over to the
right as each frame passes. As soon as a cloud is
deemed as being too distant, it will simply be reset
to the front of the screen and given a new random
position on the x axis, ready for animating through
the scene again.


for (i = 0; i < clouds.children.length; i++) {
var obj = clouds.children[i];
if (obj.position.z > -600) {
obj.position.z -= 0.8;
obj.position.x += 0.3;
} else {
obj.position.z = 300;
obj.position.x = 600 * Math.random() - 300;


}
}

Finally, the helicopter is set to bob up and down on
the screen using a sine wave. Sine waves go from
positive 1 to negative 1, so multiplying that by 10
means it will smoothly animate 10 above and below
its original position. This will give the illusion it’s
moving when the user’s mouse isn’t affecting the
scene. The last line here tells the three.js library to
update the screen display by rendering the scene
using the camera.

let speed = Date.now() * 0.0015;
chopper.position.y = (10 * Math.sin(speed));
renderer.render(scene, camera);
}

Don’t forget then whenever you want to test your
page, you need to do so from either a locally hosted
server or from a web server.

Top Once the helicopter has
been fully loaded, it will be
displayed in the right place
with shadows. The clouds
help give perspective
Above Using the inspection
tools in the browser gives a
good sense of where all the
elements are placed and
how they are positioned
in CSS
Free download pdf