Tuesday, September 10, 2013

Setting Up To Draw in 3D

Let's make a quick change to our .html webpage.  Open example01.html inside your text editor and remove the line that reads 'Hello World! It works!' (it is inside the <body> tags). Next, change the title of the webpage to Hello Three.js
The updated example01.html file should look like this now:
<!DOCTYPE html>
<html>
   <head>
      <title> Hello Three.js </title>
   </head>
   <body>
      <script src="js/three.min.js"></script>
      <script src="js/tempGame.js"></script>        
   </body>
</html>

Save the updated example01.html file (it's ok to overwrite the old example01.html).  

We will now add some easy set-up code to our tempGame.js file, which is currently blank.  Open up the tempGame.js file in your text editor.  Now select and copy the following code:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var geometry = new THREE.CubeGeometry(1,1,1);
var material = new THREE.MeshBasicMaterial({ color: 'rgb(0,255,0)' });
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;
renderer.render(scene, camera);

Paste the above code and Save the updated tempGame.js file, writing over the previous one.  Don't worry about what all this set-up code means right now.  I promise I will explain every line in the following blog post.  

We can now open up our webpage and check if everything is working.  If you are new to JavaScript and/or web development, here is something to remember:  You must open the .html file to try out any changes to your game project.  Opening up the .js files won't do anything because the web browser, Chrome in our case, must always start with a shell or container .html file to know how to proceed.

Re-open the example01.html file with the Chrome browser (check my previous blog posts if you forgot how).  Also check the JavaScript console for errors, available through Chrome's menu button (again, check previous posts if you forgot how).  If there are no errors, you should see the following image:  


If you see the bright green square, congratulations!  You have now set up everything correctly.  But wait a minute, that looks like a flat 2D green square - Hey, I thought we were going to draw in 3D!  

Well, technically it IS in 3D, but we are looking at a green cube directly face on.  We can't see around its corners and edges.  But very soon, we will magically bring this cube to life and make it rotate in 3D.  It will look like it is popping out of your browser!  So hang in there.  My next post will explain what all that set-up code means that we just blindly copied.  We will also add comments to our code so that we and others who are reading our game code will know what is going on.  Till next time!