Thursday, September 26, 2013

Changing and Animating Colors

After all the movement coding that we just did, how about we take a step back and do something a little different - color using Three.js.  Remember the rgb (red, green, and blue) line of code that made the cube a bright green?  Just in case, here it is again: 
var material = new THREE.MeshBasicMaterial({ color: 'rgb(0,255,0)' });
The three numbers inside the rgb code parentheses, (0,255,0) represent the intensity of each component of the overall final color.  We have 0 for red, 255 for green,and 0 for blue.  Remember that 255 is the maximum value for a color code.  Since we have 0 for both red and blue, they will not be mixed into the final color.  And since we have the maximum 255 for green, our cube turns out to be the brightest green possible.  Let's have a little fun with the color values.  First, try replacing the number 255 with a lower number, like 50.   Since this is a lower intensity, it will still be green, but it will now be a darker green.  Here's what the updated line of code should like like:
var material = new THREE.MeshBasicMaterial({ color: 'rgb(0,50,0)' });

Once you have gone in and changed that one little number, Save the whole file as tempGame.js, overwriting the old one.  Indeed, we now have a dark green cube.  Pretty easy!
If you would like to experiment with different color codes, here is a helpful website that gives you the exact rgb code for all the popular web colors in use today:
RGB color code charts

That's great, but wouldn't it be neat if we could animate the numbers and change the cube color over time?  Well, now that we have explored the 'oscillation' technique in the last couple of posts, we can apply our new knowledge to color as well! 
Here's the plan - we want to have a glowing red cube that pulsates (oscillates) from dark to light to dark to light, etc.  This could be used as an emergency light in a future game project.   Since rgb stands for red, green, and blue, we will set green and blue to 0 and leave those numbers alone.  For the first number, the r-value, we have it be a variable that represents a constantly changing number somewhere between 0 and 255.  When it is closer to 0, the cube will appear to be a dark red, almost black-red.  And when it approaches 255, it will glow the brightest red possible.
First, we need to create a color object that will hold the rgb information of our changing red color.  Using the Three.js library, a new color object is declared like this:
var redColor = new THREE.Color( 'rgb(0,0,0)' );
I chose the name 'redColor' because that is descriptive of what information it holds.  We fill this object by typing ' = new ' and then we access the Three.js library by typing 'THREE.something()' , where 'something' is the object that we want.  In this case it's a color object, so we type THREE.Color().  As an option, when declaring a new THREE.Color, we can specify what color it starts out as.  Even though it will be shades of red throughout the program, I initially set it to black which is rgb(0,0,0).  This takes care of the green and blue components which have to be set to 0 anyway.  And with the first number, the red component, we will ramp it up and down very soon in the program, so it really doesn't matter what this number is set to.
Next, let's declare a red intensity variable and call it something meaningful.  'redIntensity' sounds appropriate.  Here's how that looks in JavaScript code: 
var redIntensity = 0;
In the above code, we again use our trusty 'var' keyword then our 'redIntensity' name representing the amount of red color.  Then we fill it with the value of 0 by typing:  = 0;  It's always a good idea to initialize your variables to something, 0 being the most often used choice.  This is because you are telling JavaScript that this variable will hold some kind of number in the future, and then you can use it right away in your program.  You don't have to even know what it's going to be right away, but you can always change that later in the program.  
Next we need a flag, just like we had for the camera motion, but this time for color motion.  Remember, a flag is just a switch, on or off, true or false.  When the color motion flag is equal to 'true', we will add brightness to the red color by adding to its value every animation frame.  Likewise if the flag is switched to 'false', we will darken the red color by subtracting from its value every frame.  Let's declare this new flag:
var colorBrightenFlag = true;

Notice I used camelCase to capitalize the beginning of all words that are mashed together (except the first word) in 'colorBrightenFlag'.  This makes variable names easier to read.
I set this flag equal to true because I want the cube to start brightening right away when the program starts.  You could have set it to 'false' to - it doesn't really matter.
Moving on, we need an oscillation block of code (like we used for our camera a while ago) that repeatedly goes back and forth between a low value and a high value.  Let's copy the code we already made for the oscillating camera and replace the variable names with our new names so it works with colors:
if(colorBrightenFlag == true){
   redIntensity = redIntensity + 8;
}
if(colorBrightenFlag == false){
   redIntensity = redIntensity - 8;
} 
      
if(redIntensity > 255){
   redIntensity = 255;
   colorBrightenFlag = false;
}
       
if(redIntensity < 0){
   redIntensity = 0;
   colorBrightenFlag = true;
}

Looking at the above code, if 'colorBrightenFlag' is equal to 'true', then our 'redIntensity' variable gets added 8 units to itself and it grows every animation frame.  Likewise, if 'colorBrightenFlag' is equal to 'false', then our 'redIntensity' variable gets subtracted 8 from itself and it shrinks every frame.  I arbitrarily chose the number 8 because this produced a faster glowing effect.  Try different values and see how it affects the glow speed.  Remember, the higher the number, the faster it will oscillate between light and dark. 
To keep our program from adding and subtracting too far out of range, we next 'clamp' the 'redIntensity' value to a range between 0 and 255, which is the required range for rgb codes.  When the intensity wanders out of range and it is time to be clamped, we also flip the 'colorBrightenFlag' switch, so that the intensity starts to go in the opposite direction (just as we did for our camera oscillation before). 

Now we must update our 'redColor' Three.js color object that we declared earlier.  This actually holds all the color information, including the intensities of the r, g, and b components.  Since we used Three.js to declare this color, it now has handy properties and built-in functions that come with it.  One of these properties is the 'r' intensity of red, which is indeed what we want to change every animation frame.  We access it like this:
redColor.r = redIntensity;
We access the redColor's 'r' property by simply typing 'redColor' then ' . '(dot) then 'r'.  We then fill this value with whatever 'redIntensity' happens to be at the moment (which is constantly rising and falling).  There's one catch though - Three.js color properties such as '.r' must be presented in a range from 0 to 1.  0 would be dark and 1 would be bright.  0.5 would be somewhere in the middle.  I wanted to work in 0-255 rgb ranges which I find easier to read and work with, but now we must convert the intensity and scale it down to a range between 0 and 1.  Don't worry though, this is easily done with a couple of keystrokes:
redColor.r = redIntensity / 255;
The above code reads out loud "redColor.r equals redIntensity divided by ( / ) 255".  All we had to do is divide our 255-range intensity by its highest possible value, which is 255.  This will clamp it down to a range somewhere between 0 and 1.  For example, if 'redIntensity' is 255, then 255 / 255 = 1 which is the brightest value.  If 'redIntensity' is 0, then 0 / 255 = 0, which is darkest.  If 'redIntensity' is 175, then 175 / 255 = 0.68627... which is a little over half-bright.  
One more thing to do; we have to attach this updated 'redColor' to our cube so that the cube will indeed turn to whatever shade of red that we want it to.  This requires more ' . ' (dots) to access all the different properties of the cube.  It might not seem intuitive right now, but the more you use Three.js, the more you will realize why they designed the library this way, and it actually will make sense as we keep doing it in the future.  Here's how we access the color of the cube:
cube.material.color.set(redColor);
I know, that's a lot of dots ( . ) to look at, but Three.js mesh objects necessarily have a lot of different properties that can be optionally set (which makes the library so robust).  Going down the list, we start by typing 'cube' which is our mesh object, followed by '.material', which is the cube's skin, followed by '.color', which is the skin's color, followed by '.set', which is an action that changes the skin color, followed lastly by '(redColor)' which is the name of our color-info variable that holds the actual r, g, and b intensities of the final color.
Thus, if 'redColor' has a low '.r' (red-component) inside of it, our cube will turn dark-red.  If 'redColor' has a higher '.r' inside of it, our cube will glow bright-red.  

Since we added color-changing code to our .js file, I have listed the new updated tempGame.js in its entirety below. Copy and paste the following code and then Save it as tempGame.js, overwriting the old one:   


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);


var redIntensity = 0;
var redColor = new THREE.Color( 'rgb(0,0,0)' );
var colorBrightenFlag = true;

camera.position.z = 5;
var forwardFlag = false;
animate();

function animate(){
   
   requestAnimationFrame(animate);

   cube.rotation.x = cube.rotation.x + 0.02;
   cube.rotation.y = cube.rotation.y + 0.03;

   if(forwardFlag == false){
      camera.position.z = camera.position.z + 0.1;
   }
   if(forwardFlag == true){
      camera.position.z = camera.position.z - 0.1;
   } 
      
   if(camera.position.z > 10){
      camera.position.z = 10;
      forwardFlag = true;
   }
       
   if(camera.position.z < 1){
      camera.position.z = 1;
      forwardFlag = false;
   }

   if(colorBrightenFlag == true){
      redIntensity = redIntensity + 8;
   }
   if(colorBrightenFlag == false){
      redIntensity = redIntensity - 8;
   } 
      
   if(redIntensity > 255){
      redIntensity = 255;
      colorBrightenFlag = false;
   }
       
   if(redIntensity < 0){
      redIntensity = 0;
      colorBrightenFlag = true;
   }
   
   redColor.r = redIntensity / 255;
   cube.material.color.set(redColor);
      
   renderer.render( scene, camera );

}

Once you have saved it, go back to your example01.html file and open with your Chrome browser.  If you saved everything correctly, you should see our cube now glowing red, going back and forth between light and dark. Pretty cool!

In the next post we will learn how to add lighting to our scene.  We will explore the Three.js library's different kinds of lights for different situations.  Most importantly, we will be able to see the edges and shaded sides of our cube, making it look even more 3D!   

Friday, September 20, 2013

Having Fun With the Camera (part 2)

At this point, we have the code ready to flip the camera movement back and forth.  But we don't have any code to regularly 'time' this flipping at set intervals.  This is where we need another if(condition)-type statement to check whether or not it is time to flip the camera going the opposite direction.  There are 2 ways of doing this.  We could make an artificial clock timer and at set times, flip the switch.  We might see this timer element later in our games, but for now I want to try the other easier option.  All we will do is set a distance limit that our camera can travel. Once it reaches this limit, we stop the camera, flip the switch, and send it in the opposite direction.  Here's the new 'if' statement that we will add:
if(camera.position.z > 10){
   camera.position.z = 10;
   forwardFlag = true;
}
Remember that when our program starts, the forwardFlag is set to 'false' and therefore the camera is constantly moving backwards with the '+' sign version of the camera movement code.  It starts out with a position.z value of 5 and every frame it is adding + 0.1 to that number (5.1, 5.2, 5.3, 5.4, etc.).  What the above code does is continually monitor the position and it watches for when the 'camera.position.z' passes the 10 boundary mark.  When it is indeed greater than 10, such as 10.1, it then executes the code right beneath the if statement.  Everything that is inside the curly braces { } will get executed.  If the condition is NOT met however and camera.position.z is still less than 10, it will keep skipping over the code right beneath it and resume the normal program flow after the curly braces { }.  

Also notice that we have a new if(condition) comparison above: using the greater-than sign ( > ) .  In the first 'if' statement that we learned about, we tested for 'is equal' by using the == (double equals sign).  In this new 'if' statement however, we are testing for 'greater-than', by using the > symbol.  As you can guess, we can also test for less-than ( < ), greater-than-or-equal-to ( >= ) and less-than-or-equal-to ( <= ).  We will at some later point use all of these tests throughout our code.  They really come in handy!

So, looking at the above code, if camera.position.z has crossed our boundary and is indeed greater than 10, what should we do?  Well, we use a technique I like to call 'snapping' or clamping.  We essentially snap the camera's position back into place right at the limit that we set, which is 10 units.  Notice that we use the single equals sign ( = ) to actually fill the variable with a new value, 10.  We'll take a look at why this snapping back into place is important in another later post.  Just understand now that this avoids the camera getting stuck at the extreme boundaries.
 By the way, we could have used another value besides '10' as our boundary, but I chose 10 because it looked good for this demo; it didn't let the camera get too far away from the cube.
After this snap-back, we need to flip the direction switch.  The very next line (forwardFlag = true;) now 'flips' the forwardFlag switch on, or in other words, forwardFlag is switched to 'true'.  And from our earlier code, you know what happens when forwardFlag is equal to 'true' right?  We use the ' - ' version of the camera movement code, and now our camera is going in the opposite direction, or towards the cube - which is what we want!

Almost done.  Now we have to test for the opposite condition - if the camera gets too close to the green cube, we must 'snap' it back and switch it to go in the opposite direction again.  The following code should now make sense:
if(camera.position.z < 1){
   camera.position.z = 1;
   forwardFlag = false;
}
In the above code, we perform the same type of test but in reverse.  We continually monitor the camera's position and once it crosses our boundary of 1 units (gets too close to the cube), it is time to 'snap' and 'switch'!  We 'snap' the camera.position.z to 1, which is at our boundary.  Then we flip 'forwardFlag' back to 'false' again.  This will have the effect of sending the camera back where it came from.  Also note that I chose a boundary of 1 unit from the cube, which is really close; almost touching.  This number 1 for the near boundary, like the other far boundary at 10 units away, looked good for this particular demo.  Just know that we are free to pick any number we want to be the boundaries.  

That's it - whew!  I know that was a lot of new info in the last couple of blog posts for you to digest, but don't worry; we will re-visit these topics and techniques again and again in the future.  Pretty soon this game coding will be second-nature to you.  Just hang in there!

Since we made a lot of changes to our .js file, here it is printed in its entirety.  Just copy and paste the following code and then Save it as tempGame.js, overwriting the old one:   


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;
var forwardFlag = false;
animate();

function animate(){
   
   requestAnimationFrame(animate);

   cube.rotation.x = cube.rotation.x + 0.02;
   cube.rotation.y = cube.rotation.y + 0.03;

   if(forwardFlag == false){
      camera.position.z = camera.position.z + 0.1;
   }
   if(forwardFlag == true){
      camera.position.z = camera.position.z - 0.1;
   } 
      
   if(camera.position.z > 10){
      camera.position.z = 10;
      forwardFlag = true;
   }
       
   if(camera.position.z < 1){
      camera.position.z = 1;
      forwardFlag = false;
   }
      
   renderer.render( scene, camera );

}
Once you have saved it, go back to your example01.html file and open with your Chrome browser.  If you saved everything correctly, you should see the cube 'oscillating' (remember our new technique?), or quickly moving back and forth, towards you and away from you.  And who said math was not fun? :-)

Next time we will look at coloring our cube different colors.  We will also learn how to add a light source so that we can more clearly see all 6 sides of the cube - some in light, and some in shadow.  Don't miss it!

Having Fun With the Camera (part 1)

Let's have a little fun with the camera movement, and at the same time learn a new technique called oscillation.  The general idea is that we would like to move the camera backwards, then forwards, then backwards, then forwards, and so on.  Anything that goes back and forth like this is said to be in an 'oscillation'.  That's just a fancy name for moving back and forth.  
Remember that we used the '+' sign to increase the distance between us and the green cube and the '-' sign to shrink the distance.  So what we need is a way of changing periodically between these positive and negative movements, and then we will have an oscillating camera.  If you are new to game programming, you might think, "Ok, let's just put both lines of code back-to-back, like so":
camera.position.z = camera.position.z + 0.1;
camera.position.z = camera.position.z - 0.1;
But you would quickly realize that this adds and subtracts too fast, actually resetting the camera each pass through the loop.  To get a smooth back-and-forth motion, we need to go positive (using '+') for a while and then, at some later point in time, flip the sign and go negative (using '-'), then at a later point, repeat the process and go positive, and so forth.  To do this right, we need to use the branching 'if' statement.  Branching is a fancy word for decision-making; yes or no, true or false, on or off.  The JavaScript keyword 'if' will test a condition inside its parentheses and if this condition is met, it will execute whatever code that is right below it.  However if the condition is not met, it will skip right over the code that is underneath it.  Let's see the design of the 'if' code:
if(condition){
   //if the condition was met, execute this code
   //inside the curly braces
}

//if the condition was NOT met, skip to here and resume flow
It is time to discuss 'true' and 'false' in JavaScript.  If you are familiar with Boolean values, you can skip this explanation.  Otherwise, JavaScript allows us to specify a variable as a Boolean value.  Boolean is a fancy name for 'switch' or 'flag', as I like to call it.  A flag variable is either on or off, true or false, 1 or 0, yes or no. Flag variables are immensely helpful in games and we will see them a LOT in our game programming journey.  For now let's use a flag that sets the forward motion of our camera either to 'true' (yes, we want to move forward) or 'false' (no, we want to move backward).  This will allow us to essentially flip a switch on and off, on and off, and thus move the camera forward and backward, forward and backward. Here is how we will declare our new flag variable:
var forwardFlag = false;
First I used the 'var' keyword whenever we declare a variable.  Next we give a descriptive name to our flag, which is 'forwardFlag'.  JavaScript convention is to have lowercase for the first word and Upper-case for the remaining words, all mashed together into a compact name without any spaces.  Since you are not allowed to put spaces in your names anyway, this alternating lower and upper-case convention helps you read the words that are all mashed together.  This mix of lower and Upper-case is appropriately called Camel-Case, because of the 'humps' caused by the occasional Capital letters. 
Anyway, after we type the name of our flag, we should fill it with a value.  And since we want this to be an on/off switch, we set it equal to 'false', which means off or no, for now.  We could have easily set it to 'true' also.  In this case, it doesn't really matter because we don't care whether the camera goes forwards first or backwards first, just as long as it does both alternatively over and over again.

Now, inside the animate() function that quickly loops, we can test the condition of this forwardFlag repeatedly.  If it is true, we move the camera forward.  If it is false, we move the camera backward.  Remember, we learned how to test a condition by using the 'if' keyword.  Now the complete 'if' condition looks like this:
if(forwardFlag == false){
   camera.position.z = camera.position.z + 0.1;
}
If you are new to JavaScript, you might be asking, "Why is there a double equals sign ( == ) in the condition?"  Well, if you just use one equals sign ( = ), you will accidentally fill our forwardFlag with the value of 'false' over and over again!  That is not what we want.  We just want to test it.  So, the first line in the above code actually reads aloud:  "if forwardFlag is equal to false".  The == stands for "is equal?" and is a safe way to test the variable without changing it.  If we forget to add the extra equals sign, the statement will "assign or fill the variable with this value" and will definitely change the value of the variable, which messes up our program.  Try to get used to this, because we will encounter both types of equals sign usage ( = and == ) many times in our game programs.  Just remember; one equals ( = ) means assign or 'fill' the variable.  Double equals ( == ) means 'only test' the variable against a value, but do NOT change it.  
To get the hang of this, let's try this once more with the opposite camera condition.  We need to have a test for the forwardFlag being 'true' and execute the appropriate camera action if that condition is met.  Do you remember how to change the camera movement?  Yes, by changing the plus ( + ) to a minus ( - ).  Here's how the other test condition looks now:
if(forwardFlag == true){
   camera.position.z = camera.position.z - 0.1;
}
In this manner we can safely test 'forwardFlag' over and over again as the program loops, without accidentally changing its value.  If 'forwardFlag' turns out to be false, we pull the camera backward with the ' + ' sign.  If it is true, we push the camera forward with the ' - ' sign.  Recall that in an 'if' statement, if the condition is met, it will execute the statement(s) right below the condition. If the condition is NOT met and that test fails, the code right below it will be safely skipped over, and the program will keep flowing after that.  In this way, we the programmers can accurately control the flow of the program by switching things 'true' and 'false' whenever we want.  

Great, so now we have the appropriate camera movement to match the appropriate tests, but how and when do we switch the forwardFlag on and off, or 'true' and 'false' , so that the camera indeed goes smoothly back and forth?  The 'how' answer is easy:  by typing forwardFlag = true; and forwardFlag = false;  Notice I only used one equals sign ( = ), which means 'fill the variable with a new value'.  This will definitely change it.
The 'when to change' forwardFlag answer is a little more involved and requires one more 'if' condition statement in order to switch the camera movement just at the right time.  We will learn how in the next post!

Continued in part 2....

Thursday, September 19, 2013

Moving the Camera

In addition to animating the game objects such as our green cube, we can also move and rotate the camera (or eye position) in the game world.  We'll get into camera rotation in a future blog post, because that is slightly more involved.  For now we will focus on camera position movement, which is a little easier to grasp right away.

Remember when we picked up the camera and moved it back along the positive z-axis (going behind you) so that we could step back and see more of our scene?  In case you need a refresher, that line of code looks like:
camera.position.z = 5;
We typed the name of our camera, 'camera' and then used the dot (.) and then the 'position' property, followed by another dot (.) and finally the axis that we wanted, which is 'z' in this case.  Then we filled this property using the = sign followed by the number value that we would like to assign to it, which was '5'. 

What will happen if this number value changes every animation frame?  Let's find out!  First, we will try something that we already know how to do, which is add to it every frame so that the 'position.z' value keeps growing larger and larger.  Here's how that would look:
camera.position.z = camera.position.z + 0.1;
Here again, we have to first set the position equal to itself and then add a number to that.  Each time the program reads this line (60 times a second!), it will add to itself 0.1 units, (which is 5 initially, 5.1, 5.2, 5.3, 5.4, 5.5, etc.), thus becoming larger and larger over time.  
Let's try adding this line and see what happens to our view of the game world.  Remember that we have to add any animating or moving code inside the animate() function.

Here is the newly updated animate() function with our added line of code:

function animate(){
   
   requestAnimationFrame(animate);

   cube.rotation.x = cube.rotation.x + 0.02;
   cube.rotation.y = cube.rotation.y + 0.03;
  
   camera.position.z = camera.position.z + 0.1;

   renderer.render( scene, camera );

}

Can you guess what this will look like before we run it?  I'll give you a hint: the z axis represents how close or far we are to the cube, which is located at the very center of the game world.  And every loop this distance from us to the cube keeps growing and growing, getting farther.  Here is the entire updated tempGame.js file with our new line of code inserted inside the animate() function:


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;
animate();

function animate(){
   
   requestAnimationFrame(animate);

   cube.rotation.x = cube.rotation.x + 0.02;
   cube.rotation.y = cube.rotation.y + 0.03;
  
   camera.position.z = camera.position.z + 0.1;

   renderer.render( scene, camera );

}
Save this as tempGame.js, overwriting the old file, and then go to example01.html and open with your Chrome browser.

Is it what you expected?  The cube starts out where it did last time, pretty close to us.  But this time, it appears to recede into the distance as we wave bye-bye to it.  Actually it is not the cube that is moving, but us, the camera, that is moving quickly backwards (how 'special relativity' Einsteinian of us!).  So it appears if the cube is vanishing into the distance.  This same effect can be achieved by instead moving the cube.position.z along the negative z-axis every animation frame (negative z goes into your computer screen) while keeping us, the observer, absolutely still.

Now let's try moving the camera in the opposite direction - instead of backing up away from the cube, let's move forwards and meet it head-on.  Can you guess how we would do that with just one little change to our code?  Here's the answer: 
camera.position.z = camera.position.z - 0.1;
Turns out we just have to change the '+' to a '-'.  Now, every frame, the camera.position.z value will get smaller and smaller (5 initially, 4.9, 4.8, 4.7, 4.6, etc) and thus the distance between us and the green cube will get smaller as well.  It will look like it is moving towards us, but we know better!  The cube is actually still, while we keep moving our camera closer to it.  Eventually we will pass right through the cube and it will be behind us.  
Change the '+' to a '-' like I did above, then Save the new tempGame.js over the old one, and try running your example01.html file in the Chrome browser again.

Did you flinch?  Come on, be honest!  After we pass right through the cube, it seems to disappear, but it is actually still in the game world - it's just behind us so we can't see it.  In a future post, I will demonstrate how to look around (rotate) with our camera so that we can confirm that the green cube is indeed still there. 

Up, next... Moving the camera back and forth, 1970's style! 

Wednesday, September 18, 2013

How the Animate() Function Works

Let's take a look at what is going on inside the new animate() function.  Here is the function printed again for reference:

function animate(){
   
   requestAnimationFrame(animate);

   cube.rotation.x = cube.rotation.x + 0.02;
   cube.rotation.y = cube.rotation.y + 0.03;
  
   renderer.render( scene, camera );

}

The first line inside the animate() function is a call to requestAnimationFrame().  This comes from the RAF (Request Animation Frame) API that has been developed mainly by Mozilla and the WebKit team (Google and Safari) for use in high performance apps for the web, such as games that we want to make!  The requestAnimationFrame() function will try to update the rendering (drawing) of your game at a smooth 60 frames per second.  As of this writing in 2013, this is the best way to quickly update your game's logic and graphics inside a browser.  
Notice that the requestAnimationFrame() function takes a parameter inside its parentheses, which is the name of your animation function.  Since we named ours 'animate', we type 'animate' inside the parentheses.  This creates a loop as the requestAnimationFrame(animate) keeps calling the function that it is already located in, which is animate(). 

Before it heads back to animate() though, it will quickly run through what is right below it.  And what it will see is our game object updates, such as the cube rotation.  In future blog posts we will look at ways of updating the game objects and game logic in more detail.  But for now, let's consider how to spin our green cube:  
   cube.rotation.x = cube.rotation.x + 0.02;
   cube.rotation.y = cube.rotation.y + 0.03;
When we created the 'cube' mesh earlier in the program, it inherits the Three.js library's properties and helper functions for all mesh objects.  And one of these properties is called rotation. Since we are working in 3D, we can rotate an object in 3 dimensions, which are the x-axis, the y-axis, and the z-axis.  Again, in future posts I will go into way more detail about 3d movement and rotation, but just understand for now that we are wanting to update the rotation along the x axis and the y axis.  Therefore we type:
'cube.rotation.x' to change the amount of x-axis rotation.  If you are new to game programming, you might wonder why we have written it twice in the same line.  We do this because we want it to always remember where it was last time it was updated.  If we just wrote cube.rotation.x = 0.02; and that's it, then the cube would rotate 0.02 units and stay there and not move on the next pass through this function.  That's because it keeps getting set to 0.02, 0.02, 0.02, etc., every time it sees this line of code.  Instead, we first set the rotation to its old self, which looks like 'cube.rotation.x = cube.rotation.x'.  Now it 'remembers' where it was the last time.  Then we add the '+ 0.02;' part which keeps adding 0.02 to itself, growing larger on every pass.  Now we correctly see the following values for cube.rotation.x as it loops: 0.00 (initial value is 0), 0.02, 0.04, 0.06. 0.08, etc...  It will now spin smoothly along the x-axis.  The next line of code does the same, but with the y-axis. 

By the way, the numbers 0.02 and 0.03 that are added every loop are arbitrary numbers that I chose because they worked well for this particular demonstration.  Basically the bigger the number, the faster our green cube will spin.  These number values can be anything really, and in future posts we will take a look at how changing numbers like these directly effects the motion of our game objects.

Finally on the last line of the animate function, we have a line of code that should look familiar:
   renderer.render( scene, camera );
This is a direct copy of the renderer line in our old tempGame.js file.  I stuck it inside this function because remember: anything that is inside the animate() function will get updated 60 times a second.  And since we want our game to draw, update, and run at 60 FPS, we put the 'renderer.render( scene, camera);' line right here so it draws the pixels of our game to the browser window as fast as possible.

Next up...  We will learn how to animate our camera (which is like our eyes) back and forth and make the cube look like it is popping out of the browser!  Till next time...

Monday, September 16, 2013

Animating the Cube In 3D

It's finally time for some 3D!  We are going to add 5 lines of code to our tempGame.js file that will make our green cube come to life with spinning and movement, right in your browser.

First we must create our own custom function (or block of code) that will animate the cube.  In JavaScript we create a function by using the 'function' keyword and giving our function a name.  The name should make sense to you and others who may read your code, and it should be descriptive of what it does.  Since we want to have an animation-type function, we will name our function 'animate'.  There are different ways to declare and use functions in JavaScript, but for now we will use this format:
function animate(){

   //our code goes here

}

I first used the 'function' keyword followed by the name we give to our function, in this case 'animate'.  Open and closed parentheses () follow the name.  If you choose, you can put a comma-separated list of parameters inside these parentheses during the function's design phase, but we don't need any parameters right now so we'll leave it empty.  Next comes an open curly brace { which signals the start of the actual function code.  On the next line we put our code, which could be 1 line or many lines - it doesn't matter.  When the code is done, on the next line we use a closing curly brace } which signals the end of this function.

Here is the finished animate() function:

function animate(){
   
   requestAnimationFrame(animate);

   cube.rotation.x = cube.rotation.x + 0.02;
   cube.rotation.y = cube.rotation.y + 0.03;
  
   renderer.render( scene, camera );

}

There are some new commands inside this animate() function.  I will explain each line soon.  For now let's just update our .js file so that we can see the animation.  

By the way, our new animate() function will not do anything like it is.  We have to actually call it or execute it.  In JavaScript, we do this by writing the name of the function, its parentheses, and a semicolon at the end.  Here's how that looks:
animate();
This statement executes whatever is inside the design of our animate function.  Looking back at the entire animate() function above, you may recognize the very last line of code starting with the word renderer. I cut that line from our old tempGame.js file and pasted it inside the animate() function.  Since it is here now, we can safely remove the line where it came from.  Here is the full tempGame.js after it has been correctly updated:
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;
animate();

function animate(){
   
   requestAnimationFrame(animate);

   cube.rotation.x = cube.rotation.x + 0.02;
   cube.rotation.y = cube.rotation.y + 0.03;
  
   renderer.render( scene, camera );

}

Notice I called animate(); before the design phase of ' function animate(){...}' is even listed in the program.  Not to worry - when the JavaScript interpreter is running through this code it will read  'animate();' first and then go and find the design of that animate function wherever it is in the program.  Once it has located the design, it will execute everything inside the curly braces {} of that particular function (that's why we need curly braces for all blocks of code or functions).  

Copy and paste the above code and save it as tempGame.js, overwriting the old one.  Now go back and open up your example01.html webpage file with the Chrome browser.  If you've saved everything correctly, you should see our old green square now transformed into a spinning cube in all its 3D glory!

In the next post we will look at what the animate() function is doing, line by line.

Friday, September 13, 2013

What Did That Set-Up Code Do? (part 2)

.... Continued from part 1
06 var geometry = new THREE.CubeGeometry(1,1,1);
06 To see anything in our newly created scene, we have to create some game objects.    Again, we use the 'var' keyword and pick a name for our object, in this case it is called 'geometry'.  We then fill it with '= new' and a call to THREE.CubeGeometry(1,1,1).  Have you noticed a pattern yet?  The pattern is:
 var name = new THREE.something();  -  (where 'name' is the name you pick, and '.something' is the name of the helper function you are calling from the Three.js graphics library.
Get used to this pattern because you will see a LOT of instances of it throughout our code, especially the THREE.something part.  Moving on, '.CubeGeometry()' is a function of the Three.js library that creates a cube or box shape.  The 3 parameters inside the parentheses() give the dimensions of the cube in order: (width, height,depth).  So to create a box or cube with 1 unit of length on all sides, you would type (1,1,1) and that is indeed what we have done in the proceeding code.  Just for example, you could make a really tall box by typing (1,20,1) because remember that the second number represents how high the cube/box is.  One thing to note: we have created the shape or blueprint of a cube, but not the entire cube yet.  If you try to render 'geometry', it won't show anything because it doesn't have a skin or outer-material yet.  

07 var material = new THREE.MeshBasicMaterial({ color: 'rgb(0,255,0)' });
07 Now we create a skin or outer-material for our 'geometry' (the cube we just created).  Using our famous pattern, we type the 'var' keyword followed by our name for the material, in this case 'material', and fill it with '= new' and a call to THREE.MeshBasicMaterial();  The Three.js library offers us different kinds of materials for different texture and lighting situations and in the future we will explore these different materials.  But to keep things simple for now, we will just stick to 'MeshBasicMaterial'.  If you are new to 3D game development, you might be wondering about that word 'Mesh'.  Think of 'Mesh' as a mesh or combination of a geometric shape and its skin.  A wooden crate would be a mesh of a Cube geometry and a dull, wood material.  A crystal ball would be a mesh of a Sphere geometry and a glassy, transparent material.  A money safe would be a mesh of a Cube geometry and a metallic, slightly reflective material, etc.  Meshes could also be the combination of a really complex geometric shape, like the blueprint for a car or a human, and their skins (metal/rubber/plastic for the car, and complex fleshy/hairy material for the human).  But we will stick to basic shapes and their materials for now.
Next you'll notice that the THREE.MeshBasicMaterial() has parameters inside its parentheses.  You'll also notice that this is the first time we've seen the curly braces { } used.  The curly braces { } help to isolate a block of code from other statements.  In this case we wrap the { } tightly around the color: 'rgb(0,255,0)' part.  This is needed because the parameters require what is known as a 'key: value' pair in JavaScript. The correct language syntax is
key: 'value'
The key is a property you would like to set.  In this case it is the color property so we type color:  , then we have to assign a value to this color property and whatever you choose must be enclosed in single quotes ' '. In our example, we fill the color property with an RGB code.  RGB stands for Red, Green, and Blue.  So we write rgb(red,green,blue) where red, green, and blue must be a number between 0 and 255  (0 being the darkest for that color, and 255 being the brightest).  So if we have 'rgb(0,255,0)' for our value, you guessed it - we get the brightest green, which is indeed the color of our example cube.  One of our first experiments in the near future will be changing these numbers and seeing what happens to the color.

08 var cube = new THREE.Mesh(geometry, material);
08 Because we know what a mesh is now, this line of code should be pretty self-explanatory.   But just in case: We use our trusty pattern of the 'var' keyword, then a user-defined name for the completed mesh, in this case 'cube', followed by '= new'  and then fill it with a call to THREE.Mesh().  THREE.Mesh takes two parameters inside its parentheses - the name you chose for the geometry blueprint, and the name you chose for the skin material.  So in our case we type (geometry, material).  Under the hood, this function magically wraps the skin (material) around the object blueprint (geometry) to create a finished product.  And since we made a material of green skin, that is what we get; a green-skinned cube.

09 scene.add(cube);
09 Think of the scene object as the world in which the players and game objects exist and move around.  To see our newly-minted beautiful green cube, we need to make it exist in the game world.  So we add it to the scene.  We don't need the 'var' keyword or the 'new' keyword now because we already created a scene object on line 01.  We now call a function on itself - named .add(finishedObject) where finishedObject is the mesh that was just created.  Since we named it 'cube', we type scene.add(cube);  Our green cube now populates the scene world.  I can imagine on the outskirts of town a sign reading: 
Welcome to the town of scene
population: 1   (ha ha) :-)

10 camera.position.z = 5;
10 Remember that the camera is like our eyes.  Now that we've created a camera, we can move it around and rotate it all around to be able to look at the scene world.  We are just going to move it for now, because rotating is a little more involved (but we WILL do that, I promise).  The camera object has a function called position so if we want to move our camera around we type camera.position - but wait, the program needs more information than that.  Position can be described as x, y, and z coordinates.  Positive x goes to your right, negative x goes to your left, positive y goes up in the air, negative y goes down through the ground, positive z goes into your computer screen and negative z goes behind you.  What line 10 does is move the camera backwards 5 units (behind you) along the z axis.  We type camera.position.z and then the = sign tells the program we are about to fill 'z' with a value, and that value is 5.  To move the camera left we would type 
camera.position.x = -5;  
Remember that negative x goes left.
Why is this line 10 even here?  Well, when you add objects such as cubes, players, cameras, lights, etc, to your scene world, by default it places them in the middle of the world which is x=0, y=0, and z=0.  Problem with that is if our camera is already at that spot and we then add our new green cube, it will be right on top of us and we won't be able to see anything (remember the discussion about 'near clipping' planes earlier?).  So this line of code picks up the camera and moves it back 5 paces so we can get a better view of our green cube, which is at the center of the world (yeah, the cube can be kind of selfish).

11 renderer.render(scene, camera);
11 Now with this line, the magic of Three.js and WebGL happens.  If you didn't have this line, nothing would be displayed.  We use our renderer that we created earlier on line 03 and call a function on itself named render (the word render means draw the graphics).  So we type renderer.render().  The function render actually colors and draws the pixels of your world to your display screen.  Notice that this function takes 2 parameters - the scene that you wish to draw, and the camera that you want to view it with.  Since we named our scene 'scene' and our camera 'camera' (I know, real original right?), we type (scene, camera) inside the parentheses.  Don't forget the semicolon (;) after every statement!

Whew - we made it through the explanation!  If you've used any kind of 3D programs before like SketchUp, 3DS Max, Blender, Maya, etc., most of these concepts of camera, mesh, position and rendering should be familiar.  If you are totally new to all this, hang in there!  Soon we will start tinkering with small bits of code and you will immediately see what happens to the display, and therefore gain a better understanding of 3D game programming and the Three.js library.

In the next post, we will rotate and animate the green cube so that it shows us its true 3D depth.  You won't want to miss this part!  Till next time...

Thursday, September 12, 2013

What Did That Set-Up Code Do? (part 1)

So, how did those 11 lines of set-up code magically produce a green square (actually a cube as we will see) in our browser?  I will now explain each line of the code we just blindly copied so that we know what's going on.  Here is tempGame.js, printed again, but with my added line numbers so that we can examine each line  (p.s. Don't try to run the project with the exact code below, because it won't work with my added line numbers; this is just for explaining purposes).

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

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

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

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

If you are new to JavaScript, I will try to be as gentle as possible.  Here goes the code explanation:
01 var scene = new THREE.Scene();
01 All Three.js projects need 3 things to display graphics in your browser: a scene, a camera, and a renderer.  Line 01 declares a variable (using the 'var' keyword) called scene.  The 'new' keyword following the = sign means that your variable 'scene' is about to be filled with something.  And that something is a call to THREE.Scene().  If we want to use the Three.js library for our games, typing THREE.something() is how we access the library helper code that the Three.js developers have written for us.  In this case we want a new scene, so we type THREE.Scene().  Under the hood, this call sets up hundreds of lines of initialization code that the Three.js team has nicely wrapped up for us in this single line of code - nice, eh?!  Lastly, the semicolon (;) tells the browser that this is the end of this statement.  Think of semicolons as periods at the end of sentences.  They could have used periods for this purpose in computer programming languages I guess, but it would be confused with functions that have periods in them already, like THREE.Scene() - the semicolon clearly differentiates a statement-ending, from a function-call (where the period or 'dot' is used).
02 var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
02 All Three.js apps need a camera as well, and this is what line 02 initializes.  Think of the camera as your eyes.  The camera can have different properties such as field of view, aspect ratio, range of depth, as well as position and orientation (where you are in the game world and where you are looking).  Just like before we use the 'var' keyword and a user-defined name for our camera - in this case it's just named 'camera'.  Then we call the THREE.PerspectiveCamera() function which fills our named camera with info about how it should view the world.  For this blog series, I will always use THREE.PerspectiveCamera rather than THREE.OrthographicCamera.  Perspective is what 99% of 3D games use.  Perspective means that objects nearer to you appear bigger and objects farther away appear smaller, just like in real life.  Orthographic means everything is the same size, no matter how far away.  This is useful for architecture and CAD software, but not really for 3D games.  Next you'll notice that there are bits of info inside the parentheses after the call to PerspectiveCamera.  These are called parameters, or the classical name is 'arguments' for the function.  These user-defined parameters (75, window.innerWidth/window.innerHeight, 0.1,1000, etc.) will make our camera behave differently.  The first is the field of view (or FOV for short).  This number represents degrees (0-360).  If we use a much smaller number, like 20, we will have a narrow FOV and you will not be able to see as much out of your peripheral vision.  If we use a larger number, like 80, we will have a wider FOV and we will be able to see a lot more around us.  An extra large number, like 300, will give you a bent, fish-eye lens effect, similar to the output of an expensive wide-angle panoramic camera.  We'll just leave this number at 75 for now.  After that is what is known as the aspect ratio (hence the division).  2/1 is an example ratio, 4/3 is another example ratio, and in this case window width/height is the ratio we want.  It takes the current browser window width and divides it by the current browser window height (whatever that may be, on a per-user basis) and gives a nice aspect ratio.  We could just use static numbers here, but using the variables window.innerWidth and window.innerHeight is preferred, because if the user suddenly changes the window dimensions of their browser, this will automatically update the aspect ratio so that your game will not look incorrectly 'squished' or 'stretched'.  Finally we have the parameters 0.1 and 1000, which are the values for the near clipping plane and the far clipping plane.  For performance reasons we will look at later, game objects closer than '0.1' units to our camera will not be displayed, or 'clipped'.  Similarly, objects farther than '1000' units will not be displayed, or 'clipped'.  It's unnecessary work for your graphics display to try and draw things that are either inside your camera, or too far away to even see.  These clip-plane numbers can be changed, and on a per-game basis we might have to fine-tune them, but for now we will keep them the same. 
03 var renderer = new THREE.WebGLRenderer();
03 Finally, all Three.js projects need a renderer, or way of actually drawing pixels on your display screen.  We again use the 'var' keyword and name it 'renderer' and fill it with a call to THREE.WebGLRenderer().  This sets up our game to use WebGL in the browser, which utilizes our hardware accelerated graphics card to speed up the drawing, if it is available.  You could use the THREE.CanvasRenderer() but it will not be hardware optimized like WebGL and you will probably experience a slower, 'choppy' frame rate.
04 renderer.setSize(window.innerWidth, window.innerHeight);
04 Next we use the variable name for renderer that we chose ('renderer' in our case), and put a dot(.) after it to call the setSize function, which takes 2 parameters - width and height.  The name setSize is a little misleading because it does not make the game window smaller or larger, but rather the drawing resolution smaller or larger.  Again, we will just use the stock window.innerWidth and window.innerHeight values to give a crisp, clear look to our games.  You could use lower numbers in place of these variables, and it would maybe run faster on older systems - but it will look blurry. We will just leave it the same for now.

05 document.body.appendChild(renderer.domElement);
05 This next line attaches our newly created renderer to our webpage (example01.html) by using a canvas element.  Don't worry if you don't quite understand what this is doing, because we will never change this line in our games.  It just needs to be there so that you can see the graphics output on your webpage.  

Continued in part 2...

  

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!
  

Monday, September 9, 2013

Adding Our Template Game File

Now we will add our own .js (JavaScript) file to our game project.  Go inside your text editor and create a new blank file.  Save it as tempGame.js  and place it in the same folder as example01.html and three.min.js so that all the files can "see" each other. 
Also make sure you save our new tempGame file as a .js extension.  This extension tells the browser that our file will add functionality to the webpage - in our case the game and graphics code.  There's one more line to add to our old HTML file now so that it can find our new .js file that we just created. 

Now copy the following line:
<script src="js/tempGame.js"></script> 
   

Open up the example01.html file in your text editor and paste it right below the "three.min.js"line.  The finished file should look like this:
<!DOCTYPE html>
<html>
   <head>
      <title> Hello World </title>
   </head>
   <body>
      Hello World! It Works!
      <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).  And don't worry that our tempGame.js file is blank at this time.  Do you remember how to test everything?  Right-Click example01.html and 'open with...' and choose Google Chrome.  Then click on Chrome's menu button in the upper-right-hand corner (a 3 horizontal line button).  Go to Tools-> JavaScript Console.  If you don't see any Errors in red color... Congratulations once again!  You have successfully created a .js shell where we will place our future game code.  If you see any errors, make sure you spelled the file names and extensions exactly like I did.  Also make sure all 3 files now (example01.html, three.min.js, and tempGame.js) are in the same folder so that they can all see each other.

 Next up, easy graphics set-up with Three.js, and then hang in there - in the post immediately after that, I promise we will start drawing 3D graphics inside the browser! 

Saturday, September 7, 2013

Adding the Three.js Library

We are about to include the Three.js graphics library in our webpage.  If you don't know much about how HTML and JavaScript work, I'll give you the fastest re-cap possible!  All websites use some form of HTML to tell the browser (Chrome browser in our case) how to display a webpage. That's why we needed the simple HTML webpage code that you just copied.  The .html extension tells the browser that it can open up this file and display its contents.  But to have true functionality such as moving page elements, user interaction, and special graphics displays, we must use the JavaScript language.  Think of it this way: HTML for basic content, JavaScript for functionality/interaction.

If we want to use WebGL for 3D graphics on a webpage, JavaScript is how we access it.  The problem is that WebGL on its own has a steep learning curve and takes a lot of JavaScript coding just to set up the graphics, and you still won't have drawn anything to the screen!  This is where Three.js comes to the rescue.  The wonderful Three.js team has done all the hard work for us, by typing the hundreds of lines of WebGL initialization code and complex math functions to be able to correctly display and manipulate 3D objects easily in the browser.  To my knowledge, Three.js is the easiest to use and most robust 3D graphics library for the web.  

But how do we gain access to this library for our own projects?  Follow these steps and we will be ready to go!


  • Step 1: Find where your example01.html file is located on your computer.  When you have found it, right-click in an area close to it, and create a New... Folder.  Name this folder js .  That's the letter j followed by the letter s , which is short for JavaScript.  This will hold all our js files and libraries for our future game projects.
  • Step 2: Click on the following link to see the code for Three.js:  three.min.js 
  • Step 3: When you arrive at that page, right-click on the webpage and Save As... three.min.js.  The 'min' part means 'minified' , which is a fancy word for code that is shrunk down to the tightest size possible, so that it loads fast in your browser when you navigate to a webpage that uses this library. 
  • Step 4: Navigate to your 'js' folder that you just created, go inside this folder and save the three.min.js file inside here.
 Looking now at the project as a whole, you will have an 'example01.html' file with a folder named 'js' sitting right beside it.  If you double-click on this 'js' folder to open it up, you will find the 'three.min.js' file.  Our projects must be saved in this exact way, otherwise things will not work.  

Now copy the following line:
<script src="js/three.min.js"></script> 
   

The above line will make our webpage navigate to the 'src' (source) link.  It will first look for a folder named 'js' and then it will look inside that 'js' folder for a file named 'three.min.js' .  Go inside your text editor and paste the above code right below the line that reads "Hello World!  It Works!".  The finished file should now look like this:
<!DOCTYPE html>
<html>
   <head>
      <title> Hello World </title>
   </head>
   <body>
      Hello World! It Works!
      <script src="js/three.min.js"></script>        
   </body>
</html>

Save the updated file as example01.html (it's o.k. to overwrite the previous one) and open it in your browser.  If you want to confirm that it loaded the three.js library, while your webpage is still open, go to the menu of Chrome (which is a 3 horizontal line button on the upper-right corner), go to Tools->, then select 'JavaScript console' from the menu.  If you do not see any errors typed in Red color, everything worked perfectly!  If you see typed in Red - "Failed to load resource", either it can't see the file because it is not in the right folder, or the three.min.js file is incorrectly saved as another type of file - check the spelling and extension and make sure it is located inside the 'js' folder, which is right next to the example01.html file so the webpage can "see" it.

When you have no errors, Congratulations!  We can now use the Three.js graphics library on our webpage game.  Next up.. creating our own .js (JavaScript) file that will hold the code to our future games!

Thursday, September 5, 2013

Creating an HTML Template

First, we have to create an HTML template webpage to hold our future game code.  Copy and paste the following HTML code into your text editor:   
<!DOCTYPE html>
<html>
   <head>
      <title> Hello World </title>
   </head>
   <body>
      Hello World! It Works!  
   </body>
</html>

Once you've done that, it's time to save the file: click File, Save As...  example01.html 
You must type all the letters including .html at the end, because if you don't, the text editor will incorrectly save your webpage as a text file (a .txt extension) and the icon might change to a notepad - that won't work -  what you want is an html file (a .html extension).

Now when you correctly save this as an .html file, the icon for your file might change to whatever browser will open it. Right-click the icon and choose to "open with"...Google Chrome.  If you've installed the Chrome browser and saved your template webpage correctly, the example01.html file will open inside Chrome and you should see the following:
If your Chrome browser looks like this, congratulations!  You have successfully set up the webpage template.  In my next post, we will see how to add the Three.js library to our webpage so that we can access all of its awesome helper functions.

Wednesday, September 4, 2013

How Much Coding Experience Do I Need?

Actually, not a lot - even none if that is the case!  This blog series is intended for the casual coder and the hobby game programmer.  Of course it helps if you have at least some experience in JavaScript or C, or any language really.  And you don't need to be a website developing guru because although this is a web development environment, the amount of actual HTML code that we will be doing is negligible.  We just need a simple web page shell or template to house the true game code running inside of it. And since the wonderful Three.js library is written in JavaScript, that will be the main language used. 

If you've never used JavaScript before, don't worry: I've found that it is one of the most flexible, stripped-down languages out there.  In my programming travels I have used Basic, Pascal, C, C++, Java, and JavaScript.  JavaScript was the easiest for me to get going with right away.  It doesn't have a lot of constraints and it's nice not to have to deal with topics such as classes and pointer references, which can be really confusing to amateur programmers. 

Finally, if you have never hand-coded anything before, you will still be able to follow along with this blog.  We will start out by doing what every programming novice does - copy and paste!  To get our bearings, we'll look at some basic 3D examples that have already been made.  I will walk us through each line.  What happens next is the most important: we will tinker with values in other people's code and see what happens.  This is basically how I learned back in the 80's - Copy, paste, fiddle, repeat...

After seeing enough examples, pretty soon you will get the feel of what will happen before you change something in the code. When we reach this level, we can start thinking about higher level topics like game design and gameplay.    

So, enough exposition.  In my next post, we will assemble all the tools together to make a template page for our upcoming game projects!    

What You Need To Get Started

Here's a list of what you need to follow along with my series and run the examples that we will be making:

  • Either a desktop, a laptop, or tablet for development (doesn't matter what operating system).  You could use a smartphone, but the smaller screen size makes it cumbersome for typing and editing code.  However, our finished examples and games WILL run on all devices, no matter what size or operating system, even phones!
  • A Chrome browser.  Google is leading the way in cutting-edge technology for the modern web browser, and at the time of this writing, Chrome is the best choice to run our games and test our code.
  • A text editor for typing in and editing HTML files and JavaScript files.  Every device comes with some kind of text editor.  There are more fancy ones out there like Sublime Text , but there's really no need to install anything on your computer.
  • A copy of the library Three.js (a JavaScript file) which is available for free from GitHub.  For now, don't worry how to get this - in the first part of my game development series I will systematically show you how to locate and save this file to your computer so we can access all the goodies inside. 

And that's it!  That's the beauty of web game development:  no overhead, no huge workspace environment downloads - just a browser and a text editor, both of which are free.  As we go more in depth into 3D games, there will be some additional helper JavaScript files to download and save.  But these are very small files, measured in Kb rather than Mb. 

Using the Right Tools

Today there are tons of resources available to the noob game developer.  From pre-made texture art, to 3D models, to physics engines, to full-blown game studio environments like Unity.  Although there are a lot of tools out there on the internet, it's difficult to narrow your search down to the essentials needed to get started.  Enter Web game development!  Just in the last few years, HTML5 web games have really taken off and the web platform is becoming a major contender in the graphics/game development world.  At first there was only Flash, and although there are some cool 2D Flash games out there, I wanted more - true 3D worlds in the browser. 

Recently, WebGL has made its way into the spotlight as a tool to make the browser come to life with 3D graphics.  One of the premiere examples is QuakeLive , which runs Quake III Arena-style graphics in the browser. This was the first game that truly opened my eyes to the possibility of the web browser as a 3D gaming platform.  However I wanted to start from scratch and create my own simple 3D games, but at the time, there were no tools to help me.


Three.js to the rescue!


Three.js is a library for rendering fast 3D graphics in your browser.  It was created with the web developer in mind - someone who could get simple web pages up and running, but maybe did not know a lot about graphics pipelines, vector math, rotation matrices, real-time controls, etc..   

Even if you do not know web development, you can follow my blog series.  I will try to take you by the hand, as much as I can, and walk you through every step from creating a simple web page template in a text editor, to using the basic set-up code for Three.js, to actually putting elements of a real game together for a finished product.    

Tuesday, September 3, 2013

A Short History

This might show my age, but I first got the desire to learn game programming back in the 80's as a young teen playing around with my Commodore 64.  I used to buy Compute! magazine with sample program listings inside and type hundreds of lines of Basic code into my C64, and save it to floppy disk (a REAL bendable floppy disk!).  As I laboriously copied the listings line by line, I had no idea what the code did, but the thought of controlling this machine and make it run games I had entered was just too good to pass up.  Then I typed RUN and hoped for the best.  Often what I got was a bunch of Syntax errors, but once in a while my C64 would come to life with graphics and sounds - I was hooked!

Fast forward to the year 2000 and I discovered OpenGL.  I had fooled around in Basic before but to use OpenGL for Windows I needed to learn C and basic Windows development - both of which are no easy tasks.  I muscled through and actually (with the help of great books like the OpenGL SuperBible) I was able to crank out about 4 good-looking 3D games.  At the time, my brother was doing some sounds and textures and we called ourselves the BinaryBrotherz (with a 'z', because the Brothers with an 's' was already taken).  If you Google these BinaryBrotherz games you will see some cool snapshots:  
Virtual Bombard
GladiaTron 3D
3D Asteroid Patrol
Deep Space Pong

We no longer have website hosting, so sorry you can't really download them.  I will try to get a website of my own going so that I can offer them again.  They do still run on Windows machines.  The last game I worked on was back in 2002.  As I stated in this blog's title, this is a hobby so I don't always get enough time to devote to game programming.  Also I was stuck running these games on Windows environments and I wasn't about to try to learn how to port over to other native systems.  I wanted my games to run on everything, even mobile devices, but I did not have the tools nor the knowledge to make that happen.  Fast forward to today!

Welcome to Hobby 3D Game Programming!

Hi and welcome to my game programming blog.  My name is Erich and I am a hobbyist 3D game developer.  In other words, I make simple 3D computer games in my spare time... for fun!

Goals for this blog:

  • Learn the basics of creating an .html template page to hold our games
  • Learn how to use the awesome Three.js library for drawing the 3D graphics
  • Discover what's going on beneath the surface of simple games that make them work
  • Learn basic algorithms that move the game's objects and characters around realistically
  • And most importantly, to have fun!
Obviously we won't be making the latest triple-A hit games; that usually requires a dedicated team of software engineers and artists working round the clock.  However what we will be able to make in this blog series are simple, solid, true 3D games that are fast and responsive to player's input. 

So if you are ready,  let's get started on a deep and fun journey into 3D game programming!