<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>96methods</title>
	<atom:link href="http://www.96methods.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.96methods.com</link>
	<description>The online space of Graham Blake</description>
	<lastBuildDate>Tue, 17 Apr 2012 15:22:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>Code Challenge Project</title>
		<link>http://www.96methods.com/2012/04/code-challenge-project/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=code-challenge-project</link>
		<comments>http://www.96methods.com/2012/04/code-challenge-project/#comments</comments>
		<pubDate>Tue, 17 Apr 2012 15:22:34 +0000</pubDate>
		<dc:creator>gblake</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.96methods.com/?p=316</guid>
		<description><![CDATA[Fred Boyle&#8217;s code challenge project. Learn a new language or environment. Tweet]]></description>
			<content:encoded><![CDATA[<p>Fred Boyle&#8217;s <a title="Code challenge" href="http://fredboyle.com/codechallenge/" target="_blank">code challenge project</a>. Learn a new language or environment.</p>
<div id="tweetbutton316" class="tw_button" style=""><a href="http://twitter.com/share?url=http%3A%2F%2Fwww.96methods.com%2F2012%2F04%2Fcode-challenge-project%2F&amp;text=Code%20Challenge%20Project&amp;related=&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Fwww.96methods.com%2F2012%2F04%2Fcode-challenge-project%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://www.96methods.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.96methods.com/2012/04/code-challenge-project/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>From the Archive: Gamification</title>
		<link>http://www.96methods.com/2012/03/from-the-archive-gamification/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=from-the-archive-gamification</link>
		<comments>http://www.96methods.com/2012/03/from-the-archive-gamification/#comments</comments>
		<pubDate>Sat, 17 Mar 2012 17:39:29 +0000</pubDate>
		<dc:creator>gblake</dc:creator>
				<category><![CDATA[Gamification]]></category>
		<category><![CDATA[My Site]]></category>

		<guid isPermaLink="false">http://www.96methods.com/?p=286</guid>
		<description><![CDATA[Here&#8217;s one of my old posts from my older Ruby on Rails based blog site. I was rummaging around in my old archive and dug this one up&#8230; Gamification has been a buzzword on the net for some time now. &#8230; <a href="http://www.96methods.com/2012/03/from-the-archive-gamification/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s one of my old posts from my older Ruby on Rails based blog site. I was rummaging around in my old archive and dug this one up&#8230;</p>
<p>Gamification has been a buzzword on the net for some time now. Can&#8217;t remember when I first heard the term used. May have been when listening to the Think Vitamin podcast; think that it was this <a title="Think Vitamin" href="http://thinkvitamin.com/tvr/think-vitamin-radio-episode-20/" target="_blank">episode</a>.</p>
<p>I was also listening to the TechStuff podcast last weekend and they had a podcast dedicated to the topic. Whilst listening to this podcast last weekend I was kind of inspired, which is odd as I was carrying out the weekly chore of ironing at the time!</p>
<p>I jotted down some thoughts and ideas at the time. However I feel that it&#8217;s one of those occasions where you have what seems to be a great idea at the time and then turns out to be a really crappy idea when you wake-up the next morning. I thought of using gamification principles to drive traffic to my personal site and to keep people coming back. Seemed a good idea at the time but now seems a rather lame idea.</p>
<p>In essence my thoughts were to give readers of my blog &#8216;points&#8217; if they followed me on Twitter, submitted a genuine comment, followed a particular link, FaceBook &#8216;liked&#8217; a particular post, etc. These points would either be displayed on the site in the form of a leaderboard or by using a badge system. I even thought that I might be able to get a few media types who I know to produce some nice badges for me. But, as I say, the next day, in the cold light of day it seemed a rather daft idea.</p>
<p>Stupid idea or not, it&#8217;s not stopped me from carrying out a little research about gamification every time I go online. Found a rather interesting post about gamification at the <a title="UX Magazine" href="http://www.uxmag.com/design/a-gamification-framework-for-interaction-designers" target="_blank">UX Magazine</a> site.</p>
<p>Can&#8217;t remember how I came across the <a title="Bigdoor" href="http://www.bigdoor.com/" target="_blank">BigDoor site</a>, whether it was via the TechStuff podcast or on one blog post or other. It seems like a very fast way of adding gamification elements to a web site but my concern is where is all of the data that&#8217;s being collected actually stored and how is it used? I know that if I create my own server-side code to support gamification on my site any user data will be stored in my backend database and it won&#8217;t be sold to any third party. I don&#8217;t have that same feeling about using someone else&#8217;s services.</p>
<p>Anyway, I&#8221;ve rambled on for long enough. My research into gamification will continue, be it the ethics behind it or the technical implementation. I will surely blog about it in the future.</p>
<p>*UPDATE* Just wanted to mention the <a title="Practical Ethics" href="http://blog.practicalethics.ox.ac.uk/2011/02/the-ethics-of-gamification-little-rewards-for-everything/" target="_blank">Practical Ethics</a> post on the ethics of gamification.</p>
<div id="tweetbutton286" class="tw_button" style=""><a href="http://twitter.com/share?url=http%3A%2F%2Fwww.96methods.com%2F2012%2F03%2Ffrom-the-archive-gamification%2F&amp;text=From%20the%20Archive%3A%20Gamification&amp;related=&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Fwww.96methods.com%2F2012%2F03%2Ffrom-the-archive-gamification%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://www.96methods.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.96methods.com/2012/03/from-the-archive-gamification/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WhatFont</title>
		<link>http://www.96methods.com/2012/03/whatfont/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=whatfont</link>
		<comments>http://www.96methods.com/2012/03/whatfont/#comments</comments>
		<pubDate>Thu, 08 Mar 2012 19:36:57 +0000</pubDate>
		<dc:creator>gblake</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.96methods.com/?p=298</guid>
		<description><![CDATA[Trying to find out what font a particular site is using? WhatFont, a nice little browser extension that makes finding out what a particular font is. Check it out. Tweet]]></description>
			<content:encoded><![CDATA[<p>Trying to find out what font a particular site is using?</p>
<p><a title="WhatFont" href="http://chengyinliu.com/whatfont.html" target="_blank">WhatFont</a>, a nice little browser extension that makes finding out what a particular font is. Check it out.</p>
<div id="tweetbutton298" class="tw_button" style=""><a href="http://twitter.com/share?url=http%3A%2F%2Fwww.96methods.com%2F2012%2F03%2Fwhatfont%2F&amp;text=WhatFont&amp;related=&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Fwww.96methods.com%2F2012%2F03%2Fwhatfont%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://www.96methods.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.96methods.com/2012/03/whatfont/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Change of Appearance</title>
		<link>http://www.96methods.com/2012/03/change-of-appearance/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=change-of-appearance</link>
		<comments>http://www.96methods.com/2012/03/change-of-appearance/#comments</comments>
		<pubDate>Thu, 08 Mar 2012 18:56:05 +0000</pubDate>
		<dc:creator>gblake</dc:creator>
				<category><![CDATA[My Site]]></category>

		<guid isPermaLink="false">http://www.96methods.com/?p=295</guid>
		<description><![CDATA[I&#8217;ve finally updated the theme of my site so that it looks very much like my old site that was written with Ruby on Rails. I have a number of issues with it but it&#8217;ll do for the time being. &#8230; <a href="http://www.96methods.com/2012/03/change-of-appearance/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve finally updated the theme of my site so that it looks very much like my old site that was written with Ruby on Rails. I have a number of issues with it but it&#8217;ll do for the time being.</p>
<p>I&#8217;ve plans to change the styling again but it can wait.</p>
<div id="tweetbutton295" class="tw_button" style=""><a href="http://twitter.com/share?url=http%3A%2F%2Fwww.96methods.com%2F2012%2F03%2Fchange-of-appearance%2F&amp;text=Change%20of%20Appearance&amp;related=&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Fwww.96methods.com%2F2012%2F03%2Fchange-of-appearance%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://www.96methods.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.96methods.com/2012/03/change-of-appearance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Three.js: Very Basic Animation</title>
		<link>http://www.96methods.com/2012/02/three-js-very-basic-animation/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=three-js-very-basic-animation</link>
		<comments>http://www.96methods.com/2012/02/three-js-very-basic-animation/#comments</comments>
		<pubDate>Wed, 29 Feb 2012 18:57:17 +0000</pubDate>
		<dc:creator>gblake</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[three.js]]></category>

		<guid isPermaLink="false">http://www.96methods.com/?p=223</guid>
		<description><![CDATA[My previous post described how I created a simplistic 3D model with Blender and how I imported that into a three.js 3D scene. In this post I look at how a Blender model can be loaded and animated with the &#8230; <a href="http://www.96methods.com/2012/02/three-js-very-basic-animation/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>My <a title="Three.js: Importing a Model" href="http://www.96methods.com/2012/02/three-js-importing-a-model/" target="_blank">previous post</a> described how I created a simplistic 3D model with Blender and how I imported that into a three.js 3D scene. In this post I look at how a Blender model can be loaded and animated with the aid of the three.js library. Oh, it seems a rather long post too. Give yourself a treat if you manage to read all of the way through!</p>
<h2>Work in Blender</h2>
<p>To begin I returned to Blender and created a new 3D model. A model that was even more simplistic than my previous robot-type model. I wanted to produce something very simple that I could animate easily. I didn&#8217;t want to worry about having to add bones to my 3D model or anything like that. In the end I essentially created a box with some C-shaped &#8216;feet&#8217; and I animated the movement of the feet and the box &#8216;body&#8217; in Blender to give the illusion of, erm, a walking box I guess! An example of the final result can be seen <a title="Animating box on feet" href="http://www.96methods.com/wp-content/plugins/scripts/2012/02/animatecharacter01.html" target="_blank">here</a>. Only works in WebGL-enabled browsers by the way.</p>
<p>As I write this post I&#8217;m trying to recall where I located the Blender Python script file that allowed me to export a javascript (.js) file from Blender. I&#8217;m fairly sure that I found it amongst the files that I&#8217;d downloaded from the three.js github repository, located down in the <em>utils/exporters/blender</em> path somewhere.</p>
<p>In order to export my model from Blender I used the <em>Export &gt; Three.js (.js) </em>option from the Blender <em>File</em> menu; thus calling upon the Python export script that I&#8217;d previously installed.</p>
<div id="attachment_236" class="wp-caption aligncenter" style="width: 607px"><a href="http://www.96methods.com/wp-content/uploads/2012/02/blender01_export_js1.png"><img class="size-full wp-image-236" title="blender01_export_js" src="http://www.96methods.com/wp-content/uploads/2012/02/blender01_export_js1.png" alt="Export option in Blender" width="597" height="518" /></a><p class="wp-caption-text">Export option in Blender</p></div>
<p>From the Blender export window I then selected the options shown in the next image.</p>
<div id="attachment_237" class="wp-caption aligncenter" style="width: 246px"><a href="http://www.96methods.com/wp-content/uploads/2012/02/blender01_export_js_options.png"><img class="size-full wp-image-237" title="blender01_export_js_options" src="http://www.96methods.com/wp-content/uploads/2012/02/blender01_export_js_options.png" alt="Blender Export Options" width="236" height="849" /></a><p class="wp-caption-text">Blender Export Options</p></div>
<p>This gave me a .js file that contained the definition of my simple model.</p>
<p>I  want to briefly make a reference to the site of Kadrmas Concepts which is where I found a nice tutorial on how to use bones in Blender. I didn&#8217;t actually use bones in my simple model in the end but <a href="http://www.kadrmasconcepts.com/blog/2012/01/24/from-blender-to-threefab-exporting-three-js-morph-animations/" target="_blank">this post about modelling and exporting</a> was to the point.</p>
<p>I also found the superb <a title="THREE Fab" href="http://blackjk3.github.com/threefab/" target="_blank">THREE Fab</a> tool at the same time. I think that I mentioned this in my previous post; it&#8217;s a great way of importing models and just playing with primitives and lighting. I managed to solve some minor issues that I had with my basic animation by using this tool. It&#8217;s nice and easy to just drag and drop the exported .js file onto the window in the browser and view (and animate) your model.</p>
<p>Onto the interesting bit&#8230;</p>
<h2>The Code</h2>
<p>Again I&#8217;ve used the same code set-up that I&#8217;ve used and discussed previously in this series of blog posts. Therefore I&#8217;m not going to explain all of the details again such as how the require.js stuff works or setting-up of the basic 3D scene.</p>
<p>Here&#8217;s the first chunk of javascript.</p>
<pre class="brush: jscript; title: animatecharacter01.js; notranslate">
require(['96methods/BotCharacter', 'libraries/RequestAnimationFrame', 'libraries/Three', 'jquery'], function(Character) {

	var camera, stage, renderer;
	var character = new Character('./models/robot02_01_feet.js');

	// Initialise and then animate the 3D scene!
	init();
	animate();

	function init() {

		// Begin loading the character model:
		character.load();

		// Instantiate the 3D scene:
		stage = new THREE.Scene();

		// Instantiate an Orthographic camera this time.
		// The Left/Right/Top/Bottom values seem to be relative to the scene's 0, 0, 0 origin.
		// The best result seems to come if the overall viewable area is divided in 2 and
		// the Left &amp; Bottom values set to negative
		camera = new THREE.OrthographicCamera(
			window.innerWidth / -2, 	// Left
			window.innerWidth / 2,		// Right
			window.innerHeight / 2,		// Top
			window.innerHeight / -2,	// Bottom
			-2000,						// Near clipping plane
			1000 );						// Far clipping plane

		// Set the camera position:
		camera.position.y = 100;
		camera.position.x = 200;
		camera.position.z = 200;

		camera.lookAt(new THREE.Vector3(0, 0, 0));

		// Add the camera to the scene/stage:
		stage.add(camera);

		// Add some lights to the scene
		var directionalLight = new THREE.DirectionalLight(0xffffff, 1.0);
		directionalLight.position.x = 1;
		directionalLight.position.y = 0;
		directionalLight.position.z = 0;
		stage.add( directionalLight );

		var directionalLight2 = new THREE.DirectionalLight(0xeeeeee, 2.0);
		// A different way to specify the position:
		directionalLight2.position.set(-1, 0, 1);
		stage.add( directionalLight2 );

		// Instantiate the renderer
		renderer = new THREE.WebGLRenderer();
		// .. and set it's size:
		renderer.setSize(window.innerWidth, window.innerHeight);

		// Place the renderer into the HTML (inside the #container div):
		$('#container').append(renderer.domElement);

	}
</pre>
<p>At line 4 I&#8217;m simply calling the constructor of my <em>Character</em> class again as I have in previous examples. This time I&#8217;m passing in an argument that specifies the path of my 3D model. The <em>Character</em> class will load this model, when the <em>load()</em> method is invoked, and will control the animation for me; more of that shortly.</p>
<p>Again, at lines 7 &amp; 8, I am initialising the scene and beginning the animation loop. Following this is the definition of the <em>init()</em> method.</p>
<p>Main point of interest here is at line 13 where I call the <em>load()</em> method of my <em>Character</em> class. Think that&#8217;s the only main point of interest in the <em>init()</em> function actually!</p>
<p>This leads us to the remainder of the file and the <em>animate()</em> function.</p>
<pre class="brush: jscript; first-line: 62; title: animatecharacter01.js continued; notranslate">
	function animate() {
		// Defined in the RequestAnimationFrame.js file, this function means that the
		// animate function is called upon timeout:
		requestAnimationFrame( animate );

		// Find out if the robot has loaded:
		if(character.hasLoaded()) {
			// Add the character to the stage?
			if(!character.onStage()) {
				character.addToStage(stage);
			}
			// Animate:
			else {
				character.animateCharacter();
			}
		}

		render();

		// Update the character position
		TWEEN.update();
	}

	function render() {

		// *** Update the scene ***
		renderer.render(stage, camera);
	}
});
</pre>
<p>Lines 68 to 77 contain the key points of interest. Essentially here I&#8217;m trying to determine if my 3D model has loaded, if it has loaded have I added it to the stage yet and if it&#8217;s already on the stage I then call my <em>animateCharacter()</em> method to update the character animation.</p>
<p>Right, now onto the <em>Character</em> class definition.</p>
<pre class="brush: jscript; title: BotCharacter.js; notranslate">
define(['libraries/Three', 'libraries/mootools-core-1.4.2'], function() {

	return new Class(function(modelPath) {

		// Private members
		var mesh = null;
		var modelLoader = null;
		var loadedModel = false;

		var onStage = false;

		var animCycleDuration = 1000,
			numKeyframes = 39,
			scaleFactor = 20.5;

		var currentKeyframe,
			lastKeyframe;

		var lastFrameRenderedFlag = false;

		Object.append(this, {
			// Getters/setters
			getMesh: function() { return mesh; },
			setMesh: function(value) { mesh = value; },

			// Load the model
			load: function() {
				// Instantiate the JSON loader:
				modelLoader = new THREE.JSONLoader();

				// Initiate loading of the model and define callback:
				modelLoader.load( modelPath, function ( geometry ) {

					// Create a mesh based upon the loaded geometry:
					mesh = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: 0xFF6060, morphTargets: true } ) );

					// Scale-up the model so that we can see it:
					mesh.scale.set( scaleFactor, scaleFactor, scaleFactor );

					// Perhaps set flag and the main scene can ask this character if it's loaded?
					loadedModel = true;
				});
			},

			// Checks if the character model has loaded:
			hasLoaded: function() {	return loadedModel; },
			// Checks if the character model has been added to the stage:
			onStage: function() { return onStage; },
			// Adds the character model to the stage:
			addToStage: function(stage) {
				stage.add(mesh);
				onStage = true;
			},

			animateCharacter: function() {

				// Calculate interpolation - how long a single frame is shown for:
				var interpolation = animCycleDuration / numKeyframes;

				// Determine the current frame (keyframe) by calculating how much
				// more time of our animation cycle remains to be played thru.
				var time = Date.now() % animCycleDuration;

				var keyframe = Math.floor( time / interpolation ) + 1;

				// Update the frame details if the keyframe just calculated is different to the
				// current keyframe:
				if ( keyframe != currentKeyframe ) {

					// Update the morphTargetInfluences array to progress the animation cycle:
					mesh.morphTargetInfluences[ lastKeyframe ] = 0;
					mesh.morphTargetInfluences[ currentKeyframe ] = 1;
					mesh.morphTargetInfluences[ keyframe ] = 0;

					// Track previous/last keyframe and the current keyframe:
					lastKeyframe = currentKeyframe;
					currentKeyframe = keyframe;

					// Not 100% sure about this little bit. I think it helps for a smoother animation,
					// especially when animation duration is long, according to the catchvar.com site!
					// However I have found that it screws up the my little bot animation so I've taken it out.
					// Essentially the movement is very jerky when it comes to the forward movement of the whole mesh.
					//mesh.morphTargetInfluences[ keyframe ] = ( time % interpolation ) / interpolation;
					//mesh.morphTargetInfluences[ lastKeyframe ] = 1 - mesh.morphTargetInfluences[ keyframe ];

					// Determine if the character mesh should be moved forward.
					// The character mesh should be moved once the animation cycle has completed,
					// to provide the suggestion of continuous walking.

					// Has the final frame of the cycle been rendered and, thus, we are now going
					// to render the first frame in the cycle?
					if(lastFrameRenderedFlag) {
						// Clear the flag:
						lastFrameRenderedFlag = false;
						// The character in the Blender animation moves forward by 2 units during a complete
						// animation cycle, so want to move character by that amount
						// and factor in the scaling-up, hence multiplying scale factor by 2:
						mesh.position.x = mesh.position.x + (2* scaleFactor);
					}
					// The keyframe will be &lt; the lastKeyframe when the last frame
					// of the animation cycle is being rendered, i.e. when the final
					// frame is reached:
					if(keyframe &lt; lastKeyframe)
					{
						// Flag that the last frame has been reached:
						lastFrameRenderedFlag=true;
					}
				}
			}
		}); // End of Object.append
	});
});
</pre>
<p>I apologise as I have rather dumped a lot of code there. I&#8217;ve also written a lot of comments in that block of code.</p>
<p>The first interesting bit is on lines 12 to 14 where I&#8217;ve declared some local variables. Here they are again:</p>
<pre class="brush: jscript; first-line: 12; title: ; notranslate">
var animCycleDuration = 1000,
			numKeyframes = 39,
			scaleFactor = 20.5;
</pre>
<p>My animation in Blender runs for a second, so that&#8217;s where the 1000 came from, i.e. 1000 milliseconds. I have a total of 40 frames in my animation and I probably should have named my <em>numKeyframes</em> variable something like <em>lastKeyframe</em> as the frame numbering goes from 0 to 39. I&#8217;m scaling-up my model as it can barely be seen otherwise.</p>
<p>Next comes the <em>load()</em> method that we saw being called earlier in the <em>init()</em> function:</p>
<pre class="brush: jscript; first-line: 26; title: ; notranslate">
// Load the model
load: function() {
	// Instantiate the JSON loader:
	modelLoader = new THREE.JSONLoader();

	// Initiate loading of the model and define callback:
	modelLoader.load( modelPath, function ( geometry ) {

		// Create a mesh based upon the loaded geometry:
		mesh = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: 0xFF6060, morphTargets: true } ) );

		// Scale-up the model so that we can see it:
		mesh.scale.set( scaleFactor, scaleFactor, scaleFactor );

		// Perhaps set flag and the main scene can ask this character if it's loaded?
		loadedModel = true;
	});
},
</pre>
<p>I am using the JSONLoader class to load my 3D model. At line 32 I am calling the <em>load()</em> method and specifying a callback function that will be invoked once the model has loaded. Once loaded I define a mesh using the loaded model geometry, scale it up and set a flag to show that the model has loaded (this flag is used by the <em>animate()</em> function in my main block of javascript code to determine if the model is loaded).</p>
<p>Following this are the definitions of some methods used by the main javascript code to determine if the model is loaded, if it&#8217;s been added to the scene (or stage as I&#8217;ve called it) and a method used to add the loaded model to the stage.</p>
<p>Next comes the <em>animateCharacter()</em> method. Note I&#8217;ve reduced some of comments in the following section to make it a little easier to follow.</p>
<pre class="brush: jscript; first-line: 55; title: ; notranslate">
animateCharacter: function() {

	// Calculate interpolation - how long a single frame is shown for:
	var interpolation = animCycleDuration / numKeyframes;

	// Determine the current frame (keyframe) by calculating how much
	// more time of our animation cycle remains to be played thru.
	var time = Date.now() % animCycleDuration;

	var keyframe = Math.floor( time / interpolation ) + 1;

	// Update the frame details if the keyframe just calculated is different to the
	// current keyframe:
	if ( keyframe != currentKeyframe ) {

		// Update the morphTargetInfluences array to progress the animation cycle:
		mesh.morphTargetInfluences[ lastKeyframe ] = 0;
		mesh.morphTargetInfluences[ currentKeyframe ] = 1;
		mesh.morphTargetInfluences[ keyframe ] = 0;

		// Track previous/last keyframe and the current keyframe:
		lastKeyframe = currentKeyframe;
		currentKeyframe = keyframe;

		// Determine if the character mesh should be moved forward.
		// The character mesh should be moved once the animation cycle has completed,
		// to provide the suggestion of continuous walking.

		// Has the final frame of the cycle been rendered and, thus, we are now going
		// to render the first frame in the cycle?
		if(lastFrameRenderedFlag) {
			// Clear the flag:
			lastFrameRenderedFlag = false;
			// The character in the Blender animation moves forward by 2 units during a complete
			// animation cycle, so want to move character by that amount
			// and factor in the scaling-up, hence multiplying scale factor by 2:
			mesh.position.x = mesh.position.x + (2* scaleFactor);
		}
		// The keyframe will be &lt; the lastKeyframe when the last frame
		// of the animation cycle is being rendered, i.e. when the final
		// frame is reached:
		if(keyframe &lt; lastKeyframe) {
			// Flag that the last frame has been reached:
			lastFrameRenderedFlag=true;
		}
	}
}
</pre>
<p>At lines 58 to 64 I am essentially calculating which of my 40 keyframes I should be displaying.</p>
<p>The statement at line 68 is determining if there has been a change in the keyframe to be rendered since the last time this method was called. If so, the <em>morphTargetInfluences</em> array is updated so that the array cell, that refers to the frame that needs to be shown, is set to 1. Bearing in mind that <em>currentKeyframe</em> always refers to the frame being rendered on that pass. Next lines 76 and 77 store the <em>currentKeyframe</em> and <em>keyframe</em> ready for the next time around.</p>
<p>The code described thus far achieves the animation of our model; cycling through the frames of our animation and looping back once we have completed one full cycle of animation, i.e. once we&#8217;ve rendered all 40 frames of animation. The remainder of the code in the <em>animateCharacter()</em> method moves the whole model forwards a little bit each time we complete one cycle of animation. The result is that the character appears to walk slowly forwards.</p>
<p>The condition at line 85 determines if the <em>lastFrameRenderedFlag</em> has been set and, if it has, resets the flag and moves the model mesh forward by 2 units (the character model in Blender was 2 units in size) multiplied by the scale factor that was used to enlarge our model in the first case. The condition that follows this on line 96 determines if we are about to render the last frame in the animation cycle and, if so, sets the <em>lastFrameRenderedFlag</em> so that the mesh movement, as just described, can take place on the next time through the render sequence.</p>
<h2>Conclusions</h2>
<p>The <a title="Working example of animation" href="http://www.96methods.com/wp-content/plugins/scripts/2012/02/animatecharacter01.html" target="_blank">working example can be found here</a>. It&#8217;s a bit ugly but this is a work in progress. Also remember that it only works in WebGL-enabled browsers.</p>
<p>I&#8217;ve realised that the material applied to my model doesn&#8217;t seem to be showing up correctly. Pretty sure, upon editing this post, that it&#8217;s because of the mesh definition at line 35 of my BotCharacter.js code.</p>
<p>Whilst writing-up this post I discovered that my character model had the wrong pivot point, or centre of rotation. I was going to amend my example code so that the character walked in a circle by rotating the mesh each time an animation cycle was complete, but this was when I found that the character did not rotate as intended. I went back to the THREE Fab site and dropped-in my model. When rotating around the y-axis I saw the weird rotation again. Going back to take a look in Blender I recalled that the pivot point was out. This is something I&#8217;ll need to look into in the future. It raises a number of concerns that I have about how I&#8217;m achieving the character animation and if there&#8217;s a much better way of doing it. I realised that the centre-point of my 3D scene is the point around which the animating character will rotate. I have no idea at the moment if this centre-point can be moved while the character is animating or not. If anyone reading this has any thoughts on the topic and would like to enlighten me then please comment.</p>
<div id="tweetbutton223" class="tw_button" style=""><a href="http://twitter.com/share?url=http%3A%2F%2Fwww.96methods.com%2F2012%2F02%2Fthree-js-very-basic-animation%2F&amp;text=Three.js%3A%20Very%20Basic%20Animation&amp;related=&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Fwww.96methods.com%2F2012%2F02%2Fthree-js-very-basic-animation%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://www.96methods.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.96methods.com/2012/02/three-js-very-basic-animation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Three.js: Importing a Model</title>
		<link>http://www.96methods.com/2012/02/three-js-importing-a-model/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=three-js-importing-a-model</link>
		<comments>http://www.96methods.com/2012/02/three-js-importing-a-model/#comments</comments>
		<pubDate>Tue, 28 Feb 2012 18:42:04 +0000</pubDate>
		<dc:creator>gblake</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[three.js]]></category>

		<guid isPermaLink="false">http://www.96methods.com/?p=210</guid>
		<description><![CDATA[This post discusses a small piece of code that uses the three.js library to load a 3D collada scene. Upon starting to write this blog post I thought I&#8217;d take a look at some of the problems I&#8217;d encountered on the &#8230; <a href="http://www.96methods.com/2012/02/three-js-importing-a-model/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This post discusses a small piece of code that uses the three.js library to load a 3D collada scene. Upon starting to write this blog post I thought I&#8217;d take a look at some of the problems I&#8217;d encountered on the way. To my surprise I realised that I probably had enough information for two posts rather than just one.</p>
<p>This post will look at the exporting of a 3D model from Blender to be used with three.js. I&#8217;ll create another post to look at how I then managed to produce a 3D model in Blender and animate it with three.js.</p>
<h2>Blender</h2>
<p>I had first used Blender several years ago, I even bought one of those &#8216;For Dummies&#8217; books, but the Blender interface has changed since I last used the software and viewing a video seemed a nice quick way of diving back into it. Therefore I looked at a few <a title="Blender tutorials" href="http://cgcookie.com/blender/get-started-with-blender/" target="_blank">Blender tutorials</a> initially to get my head into the application.</p>
<p>After some hours playing around with what I&#8217;d seen in the video tutorials I managed to make an extremely crude-looking robot. When I say crude I don&#8217;t mean that it featured any phallic appendages! It was simply a very simplistic model.</p>
<p>In order to export my robot model from Blender I used the <em>Export &gt; COLLADA (.dae)</em> option from the Blender <em>File</em> menu. This generated a Collada .dae file for me. At a later point in my experimentation with Blender I attempted to produce a very simplistic animation within Blender and to export this animation. Well this didn&#8217;t work terribly well until I installed a script for Blender that allowed me to export my model as a Three.js (.js) file. But more on that in my next post.</p>
<p>One of the first problems that I encountered when initially loading my robot model into the three.js scene was that of weirdly rotated objects. Essentially, objects that I had rotated in Blender in order to create my robot model were appearing non-rotated when imported into my scene. I went so far as to put a question up on the <a title="StackOverflow" href="http://stackoverflow.com/questions/9109115/lack-of-object-rotation-when-using-three-js-to-import-collada-file" target="_blank">StackOverflow</a> site but then, after investigation, managed to answer my own question. Well, ok I didn&#8217;t fix the problem myself but thanks again to the <a title="three.js github issues" href="https://github.com/mrdoob/three.js/issues/771" target="_blank">Mr. Doob github area</a> I found the answer. I downloaded the three.js library from the &#8216;dev&#8217; branch rather than the &#8216;master&#8217; branch on github and my immediate problems were solved.</p>
<p>In order to be able to export my model from Blender <a title="Blender import with three.js" href="https://github.com/mrdoob/three.js/issues/143" target="_blank">this post</a> came in handy; again on the Mr. Doob github pages. Although this only came into use when I began investigating animation of loaded models.</p>
<h2>The Source</h2>
<p>Anyway the code is as follows. I&#8217;ve based much of this code on my previous examples so some elements, such as my use of <em>require()</em> at the top , may make more sense if you read some of my earlier posts about my experimentation with three.js. I&#8217;ve only included the javascript source here.</p>
<p>I think that the code, with its comments, is fairly self explanatory.</p>
<pre class="brush: jscript; title: ; notranslate">
require(['libraries/RequestAnimationFrame', 'libraries/Three', 'jquery'], function() {

	var camera, scene, renderer;
	var dae;

	// Create an instance of the collada loader:
	var loader = new THREE.ColladaLoader();

	// Need to convert the axes so that our model does not stand upside-down:
	loader.options.convertUpAxis = true;

	// Load the 3D collada file (robot01.dae in my example), and specify
	// the callback function that is called once the model has loaded:
	loader.load( './models/robot01.dae', function ( collada ) {

		// Grab the collada scene data:
		dae = collada.scene;

		// No skin applied to my model so no need for the following:
		// var skin = collada.skins[ 0 ];

		// Scale-up the model so that we can see it:
		dae.scale.x = dae.scale.y = dae.scale.z = 25.0;

		// Initialise and then animate the 3D scene
		// since we have now successfully loaded the model:
		init();
		animate();
	});

	function init() {

		// Instantiate the 3D scene:
		scene = new THREE.Scene();

		// Instantiate an Orthographic camera this time.
		// The Left/Right/Top/Bottom values seem to be relative to the scene's 0, 0, 0 origin.
		// The best result seems to come if the overall viewable area is divided in 2 and
		// the Left &amp; Bottom values set to negative
		camera = new THREE.OrthographicCamera(
			window.innerWidth / -2, 	// Left
			window.innerWidth / 2,		// Right
			window.innerHeight / 2,		// Top
			window.innerHeight / -2,	// Bottom
			-2000,						// Near clipping plane
			1000 );						// Far clipping plane

		// Set the camera position so that it's up top and looking down:
		camera.position.y = 100;

		// Rotate around the x-axis by -45 degrees:
		camera.rotation.x -= 45 * (Math.PI/ 180);

		// Add the camera to the scene:
		scene.add(camera);

		// Add some lights to the scene
		var directionalLight = new THREE.DirectionalLight(0xeeeeee , 1.0);
		directionalLight.position.x = 1;
		directionalLight.position.y = 0;
		directionalLight.position.z = 0;
		scene.add( directionalLight );

		var directionalLight2 = new THREE.DirectionalLight(0xeeeeee, 2.0);
		// A different way to specify the position:
		directionalLight2.position.set(-1, 0, 1);
		scene.add( directionalLight2 );

		// Add the loaded model to the scene:
		scene.add(dae);

		// Instantiate the renderer
		renderer = new THREE.WebGLRenderer();
		// .. and set it's size:
		renderer.setSize(window.innerWidth, window.innerHeight);

		// Place the renderer into the HTML (inside the #container div):
		$('#container').append(renderer.domElement);
	}

	function animate() {
		// Defined in the RequestAnimationFrame.js file, this function
		// means that the animate function is called upon timeout:
		requestAnimationFrame( animate );

		render();
	}

	function render() {
		// *** Update the scene ***
		renderer.render(scene, camera);
	}
});
</pre>
<div id="tweetbutton210" class="tw_button" style=""><a href="http://twitter.com/share?url=http%3A%2F%2Fwww.96methods.com%2F2012%2F02%2Fthree-js-importing-a-model%2F&amp;text=Three.js%3A%20Importing%20a%20Model&amp;related=&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Fwww.96methods.com%2F2012%2F02%2Fthree-js-importing-a-model%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://www.96methods.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.96methods.com/2012/02/three-js-importing-a-model/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Three.js: Simple Collision Detection</title>
		<link>http://www.96methods.com/2012/01/three-js-simple-collision-detection/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=three-js-simple-collision-detection</link>
		<comments>http://www.96methods.com/2012/01/three-js-simple-collision-detection/#comments</comments>
		<pubDate>Sat, 28 Jan 2012 19:54:27 +0000</pubDate>
		<dc:creator>gblake</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[three.js]]></category>
		<category><![CDATA[vector]]></category>

		<guid isPermaLink="false">http://www.96methods.com/?p=169</guid>
		<description><![CDATA[I&#8217;ve been spending some time trying to work out how to perform basic collision detection with the three.js library. After a combination of Googling, looking at the three.js source code and looking at the sample code on the three.js github &#8230; <a href="http://www.96methods.com/2012/01/three-js-simple-collision-detection/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been spending some time trying to work out how to perform basic collision detection with the three.js library. After a combination of Googling, looking at the three.js source code and looking at the sample code on the three.js github pages I&#8217;ve managed to get something working.</p>
<p>I found the best collision detection example at <a title="three.js repository on github" href="https://github.com/mrdoob/three.js/commit/6ad7cbb47bd4a0e441c744030a8a0e2e3f2edfd2" target="_blank">Mr.Doob&#8217;s three.js repository</a> on github. In fact that are a number of examples there. These examples use a couple of utility files, namely CollisionUtils.js and Collisions.js that can be found along with the example code. I&#8217;m pretty sure that I checked out the latest revision of the three.js code from github but the CollisionUtils.js and Collisions.js utility files that are available <a href="https://github.com/mrdoob/three.js/commit/6ad7cbb47bd4a0e441c744030a8a0e2e3f2edfd2" target="_blank">here</a> didn&#8217;t seem to come with it. I used these utility files in order to implement collision detection in my little exploration where they allowed me to use:</p>
<pre class="brush: jscript; title: ; notranslate">
THREE.Collisions.colliders.push(
	THREE.CollisionUtils.MeshOBB( cube ) );
</pre>
<p>Essentially this creates an Object Bounding Box (OBB) around a THREE.Mesh object (<em>cube</em> in this example) and adds it to a collision detection list (THREE.Collisions.colliders as defined in Collisions.js). The <em>MeshOBB()</em> method is defined in the CollisionUtils.js file. In my code I added a number of cuboid objects to my 3D scene and also added them to the collision detection list (using the code snippet above). My plan was to then determine if my moving 3D object, or character, had collided with any of these cuboids.</p>
<p>In order to determine if my moving character had collided with any of the other objects in the scene (the objects on the collision detection list) I used the THREE.Ray class. The following segment of code determines the position of a theoretical focal point of this ray (think beam of light) that lies somewhere in front of our character. As our character rotates the focal point rotates also.</p>
<p>I believe that the distance specified in the second argument to the THREE.Ray constructor essentially represents the direction in which the ray is to be sent. I&#8217;ve used a value of 1000 in this example but it could have been a much smaller value.</p>
<pre class="brush: jscript; title: ; notranslate">
// Using a little trigonometry calculate a point in
// space 1000 units in front of our character
var deltaX = Math.floor(Math.sin(mesh.rotation.y) * 1000);
var deltaZ = Math.floor(Math.cos(mesh.rotation.y) * 1000);

// Calculate where this collision focus point is in
// relation to our character position
var focusX = mesh.position.x - deltaX;
var focusZ = mesh.position.z - deltaZ;

// Fire a ray from the centre point of our character to the
// collision focus point
var ray = new THREE.Ray(mesh.position,
	new THREE.Vector3(focusX, 0, focusZ));

var c = THREE.Collisions.rayCastNearest( ray );

if(c &amp;&amp; c.distance &lt;= 50)
{
	console.log(c.distance);
	tween.stop();
}
</pre>
<p>The <em>rayCastNearest()</em> method is used to determine if the ray coincides with any of the objects that were added to the collision detection list that was populated earlier. If there is an object (or collider object as I&#8217;ve shown in the figure below) that the ray intersects then the object returned by the <em>rayCastNearest()</em> method includes a <em>distance</em>property that tells us the distance between position of our character and the collider object. In the code extract above I&#8217;ve specified a distance of &lt;= 50 as my character had a length of 100 and so 50 is the point at which the face of my character would potentially collide with any collider objects. If a collision occurs I stop the tweening update so that my character stops moving.</p>
<p><a href="http://www.96methods.com/wp-content/uploads/2012/01/collisiondetection01.png"><img class="aligncenter size-full wp-image-171" title="collisiondetection01" src="http://www.96methods.com/wp-content/uploads/2012/01/collisiondetection01.png" alt="Collision detection" width="247" height="207" /></a></p>
<p>Note: In the figure above I&#8217;m pretty sure that I should have shown the z-axis as -z.</p>
<p>Once I&#8217;ve actually produced a practical demonstration of this theory I will post again with an example.</p>
<h2>Finally</h2>
<p>I just wanted to provide some further links as I did a little bit of trawling on the net when I was first researching into collision detection. I&#8217;m not sure that I&#8217;m using the best technique but there still seems to be validity in the methods that I&#8217;ve used. I came across a <a title="Discussion on determining Ray direction" href="https://github.com/mrdoob/three.js/issues/960" target="_blank">discussion on the Mr.Doob github pages</a> where someone was unsure of how to find the direction for the THREE.Ray. The individual concerned did some searching themselves and came up with a slightly different method of determining the Ray direction than I did.</p>
<p>At one stage I was considering the use of the JigLibJS library as discussed on <a title="Three.js and JigLibJS" href="http://timothypoon.com/blog/2011/03/08/using-three-js-and-jiglibjs-together/" target="_blank">Tim Poon&#8217;s site</a>. Didn&#8217;t go down this road in the end but could be interesting.</p>
<p>Of course I also found the code examples that come with the three.js library fairly useful too.</p>
<div id="tweetbutton169" class="tw_button" style=""><a href="http://twitter.com/share?url=http%3A%2F%2Fwww.96methods.com%2F2012%2F01%2Fthree-js-simple-collision-detection%2F&amp;text=Three.js%3A%20Simple%20Collision%20Detection&amp;related=&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Fwww.96methods.com%2F2012%2F01%2Fthree-js-simple-collision-detection%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://www.96methods.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.96methods.com/2012/01/three-js-simple-collision-detection/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Three.js: Moving Objects</title>
		<link>http://www.96methods.com/2012/01/three-js-moving-objects/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=three-js-moving-objects</link>
		<comments>http://www.96methods.com/2012/01/three-js-moving-objects/#comments</comments>
		<pubDate>Sat, 28 Jan 2012 11:53:43 +0000</pubDate>
		<dc:creator>gblake</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[three.js]]></category>
		<category><![CDATA[vector]]></category>

		<guid isPermaLink="false">http://www.96methods.com/?p=85</guid>
		<description><![CDATA[Thought that I should write another post about my discoveries with the Three.js library as my last post was written sometime before Christmas. Having said that I didn&#8217;t make much progress with my Three.js investigations over the Christmas and New &#8230; <a href="http://www.96methods.com/2012/01/three-js-moving-objects/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Thought that I should write another post about my discoveries with the Three.js library as my last post was written sometime before Christmas. Having said that I didn&#8217;t make much progress with my Three.js investigations over the Christmas and New Year period. Quite a bit of time was spent pondering how to best implement an Object Orientated Programming approach with my JavaScript work.</p>
<p>In the end I elected to use the MooTools library; actually I&#8217;m only using the Class definition of that library so far. I&#8217;m just rather unimpressed with how classes, sorry reference types, are defined in JavaScript. Certainly when compared to how easily and seemingly naturally this is done with other modern languages. There seem to be a number of different techniques, or patterns, in use by the JavaScript community but in the end I decided to just use MooTools. I think that my main reason for electing to use the MooTools library was due to my desire to find out how to distinguish between private and public class members in JavaScript. I was doing some Googling one day and found something about how to define private class members with MooTools. I know this can be done without resorting to the use of a framework but sometimes I just want to get on with things and not worry about the boring details. Note to self: have a good look at the underlying principles of reference types in JavaScript sometime, e.g. the use of prototype.</p>
<p>So, I&#8217;ve been playing with a bit more of the Three.js library, been using the <a title="tween.js" href="https://github.com/sole/tween.js" target="_blank">Tween.js library</a> to perform some very simple movement and the <a title="require.js" href="http://requirejs.org/" target="_blank">Require.js library</a> to bring everything together in a structured way.</p>
<p>Using the require.js library allows me to have just a single &lt;script&gt; tag in my HTML that references my main JavaScript file, namely main.js.</p>
<h2>Managing JavaScript Files with require.js</h2>
<p>Here&#8217;s the HTML.  The main point of interest here is the &lt;script&gt; tag I think. I&#8217;ve added some buttons to control the movement of the 3D object that I&#8217;ll discuss in a bit. I&#8217;m not going to apologise for the lack of styling and the ugly buttons; but I am sorry about that! In future posts I will attempt to make things a little tidier.</p>
<pre class="brush: xml; title: main.html; notranslate">
&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
	&lt;head&gt;
		&lt;title&gt;A moving shape - Made with three.js&lt;/title&gt;
		&lt;meta charset=&quot;utf-8&quot;&gt;
	&lt;/head&gt;
	&lt;body&gt;

		&lt;div id=&quot;container&quot;&gt;&lt;/div&gt;
		&lt;div&gt;
			&lt;input type=&quot;button&quot; id=&quot;fwdbtn&quot; value=&quot;FWD&quot;/&gt;
			&lt;input type=&quot;button&quot; id=&quot;rotateleftbtn&quot; value=&quot;ROTATE LEFT&quot;/&gt;
			&lt;input type=&quot;button&quot; id=&quot;rotaterightbtn&quot; value=&quot;ROTATE RIGHT&quot;/&gt;
		&lt;/div&gt;

		&lt;script data-main=&quot;js/main&quot; src=&quot;js/require.js&quot;&gt;&lt;/script&gt;

	&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Next is the JavaScript. Firstly is my main.js file that creates the 3D scene, adds objects to the scene and assigns event handlers to the buttons that were defined in the HTML previously. The first point of interest is the use of the <em>require()</em> function (line 1 in the main.js file shown below). I&#8217;m not going to discuss the details of the require.js library, suffice to say that this line ensures that the Character.js, Tween.js, RequestAnimationFrame.js, three.js and jquery.js dependency files are loaded before the inner function is executed. I&#8217;ve found that the use of the require.js library has given me the ability to place JavaScript code in smaller files rather than one large file and means that I don&#8217;t have to place numerous &lt;script&gt; tags in my HTML. There are many other benefits to using the require.js and I urge you to take a look at it.</p>
<h2>Animating</h2>
<p>I&#8217;ve attempted to place all code that deals with my movable object, or character as I have called it, in its own JavaScript file, Character.js. The Character.js file contains the definition of the Character class that is instantiated on line 4 below. Below this a little jQuery is used to bind methods of the Character class to click events on the buttons.</p>
<pre class="brush: jscript; title: main.js; notranslate">
require(['96methods/Character', 'libraries/Tween', 'libraries/RequestAnimationFrame', 'libraries/Three', 'jquery'], function(Character) {

	var camera, scene, renderer;
	var character = new Character();

	// Add some button click event handlers:
	$(&quot;#rotateleftbtn&quot;).bind('click', character.rotateCharacterLeft);
	$(&quot;#rotaterightbtn&quot;).bind('click', character.rotateCharacterRight);
	$('#fwdbtn').bind('click', character.forwardCharacter);

	// Initialise and then animate the 3D scene!
	init();
	animate();
</pre>
<p>Following this is the <em>init()</em> method again as I&#8217;ve used previously in other posts (and in fact seems almost like the three.js standard). The key diferences between this version and what I did previously are rotating the camera so that it&#8217;s looking down upon the scene a little and using the <em>createCharacter()</em> method to add the &#8216;character&#8217; object to the scene. Again this method is defined in the Character.js file (see later in this post).</p>
<p>Then come the <em>animate()</em> and <em>render()</em> function calls to perform the scene update; again as I&#8217;ve described in my previous post. The key difference here is the addition of the <em>TWEEN.update()</em> method call (line 79). TWEEN is yet another JavaScript library that I&#8217;m using to give me tweening functionality. Essentially everytime the <em>animate()</em> function is called the character object&#8217;s update method is called to reposition my character.</p>
<pre class="brush: jscript; first-line: 15; title: ; notranslate">
	function init() {

		// Instantiate the 3D scene:
		scene = new THREE.Scene();

		// Instantiate an Orthographic camera this time.
		// The Left/Right/Top/Bottom values seem to be relative to the scene's 0, 0, 0 origin.
		// The best result seems to come if the overall viewable area is divided in 2 and
		// the Left &amp; Bottom values set to negative
		camera = new THREE.OrthographicCamera(
			window.innerWidth / -2, 	// Left
			window.innerWidth / 2,		// Right
			window.innerHeight / 2,		// Top
			window.innerHeight / -2,	// Bottom
			-2000,						// Near clipping plane
			1000 );						// Far clipping plane

		// Set the camera position so that it's up top and looking down:
		camera.position.y = 100;
		// Rotate around the x-axis by -45 degrees:
		camera.rotation.x -= 45 * (Math.PI/ 180);

		// Add the camera to the scene:
		scene.add(camera);

		// Define a cylinder object, well a cone anyway:
		cylinder = new THREE.Mesh(
			new THREE.CylinderGeometry(25,	// Radius top
				100,						// Radius bottom
				100,						// Height
				25,							// Number of segments in circumference (i.e. how smooth)
				5,							// Number of segments high
				false						// Open ended
			),
			new THREE.MeshBasicMaterial( {color: 0x372AFF} )
		);
		// Position it slightly to the right of the scene...
		cylinder.position.x = 400;
		// ...and add it to the scene:
		scene.add(cylinder);

		// Define our character shape and location within the scene:
		character.createCharacter(0, 0);
		// Add it to the stage:
		scene.add(character.getMesh());

		// Instantiate the renderer
		renderer = new THREE.CanvasRenderer();
		// .. and set it's size:
		renderer.setSize(window.innerWidth, window.innerHeight);

		// Place the renderer into the HTML (inside the #container div):
		$('#container').append(renderer.domElement);

	}

	function animate() {
		// Defined in the RequestAnimationFrame.js file, this function means that the
		// animate function is called upon timeout:
		requestAnimationFrame( animate );

		render();

		// Update the character position
		TWEEN.update();
	}

	function render() {

		// *** Update the scene ***
		renderer.render(scene, camera);
	}
});
</pre>
<p>As mentioned earlier, I&#8217;m trying to place all of the code that handles my moveable object in the character.js file, and therefore in my Character class.</p>
<p>There&#8217;s more require.js magic here to define my character module and specify the dependencies for this module, i.e. the three.js, mootools-core-1.4.2.js and Tween.js files. Once these files have been loaded a new instance of the Class object is returned (and thus available to the main.js file). Details of how the Class function works can be found in the MooTools documentation (see links later in this post).</p>
<p>Firstly a number of private member variables are declared and initialised then, to differentiate between private members and public members, the class is &#8216;appended&#8217; to (at line 24 of character.js) specifying the public methods.</p>
<p>The <em>getMesh()</em> and <em>setMesh()</em> accessor methods are simply used to get/set the mesh data that is encapsulated within the Character class.</p>
<p>The <em>createCharacter()</em> method is responsible for instantiating the mesh for the character and setting its initial position in the 3D scene.</p>
<pre class="brush: jscript; title: character.js; notranslate">
// 96methods/Character.js

// Character class definition

define(['libraries/three', 'libraries/mootools-core-1.4.2', 'libraries/Tween'], function() {

	return new Class(function() {

		// Private members
		var mesh = null;
		var width = 25, height = 25, length = 100;

		var tween = null;

		var currentAngle = { angle: 0 };
		var targetAngle = { angle: 45 };

		var currentZPos = { zPos: 0 };
		var targetZPos = { zPos: 100 };

		var actualAngle = 0;
		var actualZPos = 0;

		Object.append(this, {
			// Getters/setters
			getMesh: function() { return mesh; },
			setMesh: function(value) { mesh = value; },

			// Methods
			createCharacter: function(xpos, ypos) {
				mesh = new THREE.Mesh(
					new THREE.CubeGeometry(width, height, length),
					new THREE.MeshBasicMaterial( { color: 0x121212} ) // Material
				);

				mesh.position.x = xpos;
				mesh.position.z = ypos;
				mesh.position.y = 0;
			},
</pre>
<p>The <em>forwardCharacter()</em>, <em>rotateCharacterLeft()</em> and <em>rotateCharacterRight()</em> methods are bound to the buttons in the HTML and are responsible for controlling the movement of the character (ok it&#8217;s an oblong and not a well defined character but I&#8217;m taking small steps at a time here) when the buttons are clicked. If we focus on the <em>rotateCharacterLeft()</em> method:</p>
<pre class="brush: jscript; first-line: 40; title: ; notranslate">
			rotateCharacterLeft: function(event) {

				// Reset angle info:
				actualAngle = 0;
				currentAngle = { angle: 0 };

				// Define the tween along with the update function:
				tween = new TWEEN.Tween(currentAngle)
					.to(targetAngle, 1000)
					.onUpdate(function() {

						// Calculate the difference between current angle and where we want to be:
						var difference = Math.abs(currentAngle.angle - actualAngle);
						actualAngle = currentAngle.angle;

						// Rotate about Y:
						mesh.rotation.y += difference * (Math.PI / 180);
					})
					.start();
			},
</pre>
<p>The tween variable is assigned an instance of the Tween class; again see the Tween.js library (links a little later in this post). The argument to the Tween class&#8217;s constructor, currentAngle in this case, specifies the variable that will be used to track the current state of the animation as time progresses. The <em>to()</em> method then takes the target state and the time in milliseconds that the animation should take. In my example I&#8217;ve set the duration to 1000 milliseconds or 1 second. The <em>onUpdate()</em> method allows us to specify a callback function that is called when the <em>TWEEN.update()</em> method is called (see the <em>animate()</em> method of main.js shown earlier). In the case of the <em>rotateCharacterLeft()</em> method example the angle will be updated until it reaches the target angle of 45 degrees. Each time the callback function is called we calculate the difference between the current angle as determined by the tween and the actual angle the character is positioned at and move the character by this difference. The end result is that the character object rotates by 45 degrees in 1 second.</p>
<p>Here&#8217;s the remainder of the character.js file. The main point of interest here is in the <em>forwardCharacter()</em> method where the <em>translateZ()</em> method is used to move the character object, rather than rotating it.</p>
<pre class="brush: jscript; first-line: 60; title: ; notranslate">
			rotateCharacterRight: function(event) {

				// Reset angle info:
				actualAngle = 0;
				currentAngle = { angle: 0 };

				// Define the tween along with the update function:
				tween = new TWEEN.Tween(currentAngle)
					.to(targetAngle, 1000)
					.onUpdate(function() {

						// Calculate the difference between current angle and where we want to be:
						var difference = Math.abs(currentAngle.angle - actualAngle);
						actualAngle = currentAngle.angle;

						// Rotate about Y:
						mesh.rotation.y -= difference * (Math.PI / 180);
					})
					.start();
			},

			forwardCharacter: function(event) {

				// Reset z-pos info:
				actualZPos= 0;
			 	currentZPos = { zPos: 0 };

			 	tween = new TWEEN.Tween(currentZPos)
			 		.to(targetZPos, 1000)
			 		.onUpdate(function() {
						// Calculate the difference between current frame number and where we want to be:
						var difference = Math.abs(currentZPos.zPos - actualZPos);
						actualZPos = currentZPos.zPos;

						// Moving in -Z direction:
						mesh.translateZ(-difference);
			 		})
			 		.start();
			}

		}); // End of Object.append

	});
});
</pre>
<h2>Summary</h2>
<p>I&#8217;ve uploaded an <a title="Moving Object Demo" href="http://www.96methods.com/wp-content/plugins/scripts/2012/01/Main.html" target="_blank">example of the movable object</a> to demonstrate the code discussed in this post. One of my colleagues pointed out to me recently that none of my examples worked in IE. I think this is because of the issues with Canvas on earlier versions of IE.</p>
<p>I also appreciate that the graphics that these brief examples reveal are far from being attractive. Ok, so they are ugly and primitive (yep, quite literally primitive)! I hope that, in future posts, that will be resolved. At the moment I&#8217;m just happy to be playing around with the technology and recording my discoveries.</p>
<p>I decided with this post to place links mostly at the end of the piece. The silly idea was to tempt people to read the whole post before clicking on links and leaving my site.</p>
<p>Full details of the require.js library can be found at the <a title="require.js" href="http://requirejs.org/" target="_blank">require.js site</a>. I recall that I initially heard about this library on the excellent <a title="Think Vitamin" href="http://thinkvitamin.com/code/javascript/organize-your-code-with-requirejs/" target="_blank">Think Vitamin</a> site.</p>
<p>I happened across a <a title="keetology.com" href="http://keetology.com/blog/2009/07/23/up-the-moo-herd-iii-its-classy-not-classic" target="_blank">post by Mark Joseph Obcena</a> whilst searching for information on how best to implement private methods in JavaScript. This then led me to begin using the <a title="mootools" href="http://mootools.net/" target="_blank">MooTools framework</a>. I also came across <a title="David Walsh Blog" href="http://davidwalsh.name/mootools-requirejs" target="_blank">David Walsh&#8217;s post</a> about the combination of require.js and MooTools that you may find interesting reading. <a title="MooTools API Documentation" href="http://mootools.net/docs/core" target="_blank">Documentation for the MooTools framework</a> is also a good starting point.</p>
<p>The tween.js code can be found on <a title="tween.js" href="https://github.com/sole/tween.js" target="_blank">github</a>. I found out about this library/engine at the <a title="Learning Three.js" href="http://learningthreejs.com/blog/2011/08/17/tweenjs-for-smooth-animation/" target="_blank">Learning Three.js</a> site. I&#8217;ve recently found another <a title="gskinner tween.js" href="http://tweenjs.com/" target="_blank">tweening library by gskinner</a>. I may need to look into this one at some point in the future.</p>
<p>If you&#8217;ve found this post useful or if you&#8217;ve constructive comments please add a comment or send me an email to let me know. It&#8217;s sometimes nice to know if anyone out there in web land finds any of this stuff useful.</p>
<div id="tweetbutton85" class="tw_button" style=""><a href="http://twitter.com/share?url=http%3A%2F%2Fwww.96methods.com%2F2012%2F01%2Fthree-js-moving-objects%2F&amp;text=Three.js%3A%20Moving%20Objects&amp;related=&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Fwww.96methods.com%2F2012%2F01%2Fthree-js-moving-objects%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://www.96methods.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.96methods.com/2012/01/three-js-moving-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pastry</title>
		<link>http://www.96methods.com/2012/01/pastry/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=pastry</link>
		<comments>http://www.96methods.com/2012/01/pastry/#comments</comments>
		<pubDate>Sat, 14 Jan 2012 14:11:35 +0000</pubDate>
		<dc:creator>gblake</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.96methods.com/?p=93</guid>
		<description><![CDATA[Saturday morning. Now Saturday afternoon. Procrastinating by looking at things on the interwebs. Telling myself that I&#8217;m doing research. Came across a post by Keir Whitaker about one of his many projects: The Pastry Box Project. Looks interesting so thought &#8230; <a href="http://www.96methods.com/2012/01/pastry/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Saturday morning. Now Saturday afternoon. Procrastinating by looking at things on the interwebs. Telling myself that I&#8217;m doing research. Came across a post by <a href="http://keirwhitaker.com/">Keir Whitaker</a> about one of his many projects: <a href="http://www.the-pastry-box-project.net/">The Pastry Box Project</a>.</p>
<p>Looks interesting so thought that I&#8217;d share.</p>
<div id="tweetbutton93" class="tw_button" style=""><a href="http://twitter.com/share?url=http%3A%2F%2Fwww.96methods.com%2F2012%2F01%2Fpastry%2F&amp;text=Pastry&amp;related=&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Fwww.96methods.com%2F2012%2F01%2Fpastry%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://www.96methods.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.96methods.com/2012/01/pastry/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Three.js: Moving the Camera</title>
		<link>http://www.96methods.com/2011/12/three-js-moving-the-camera/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=three-js-moving-the-camera</link>
		<comments>http://www.96methods.com/2011/12/three-js-moving-the-camera/#comments</comments>
		<pubDate>Thu, 15 Dec 2011 19:08:03 +0000</pubDate>
		<dc:creator>gblake</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.96methods.com/?p=78</guid>
		<description><![CDATA[My previous post took a look at the three.js 3D JavaScript engine. I&#8217;ve made some simple embellishments since that last post. I&#8217;ve worked out how to implement an orthographic camera rather than a PerspectiveCamera and how to move the camera &#8230; <a href="http://www.96methods.com/2011/12/three-js-moving-the-camera/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>My <a title="The Three.js Library" href="http://www.96methods.com/2011/12/the-three-js-library/">previous post</a> took a look at the <a href="&quot;https://github.com/mrdoob/three.js">three.js</a> 3D JavaScript engine. I&#8217;ve made some simple embellishments since that last post.</p>
<p>I&#8217;ve worked out how to implement an <a href="http://http://en.wikipedia.org/wiki/Orthographic_projection">orthographic</a> camera rather than a PerspectiveCamera and how to move the camera within the scene while ensuring that the camera is still pointing (or focused) on the centre of the scene.</p>
<p>I&#8217;ve simply taken the code from the last post and made some changes to it.</p>
<p>Here is my <a title="cubedemo01" href="http://www.96methods.com/wp-content/plugins/scripts/2011/12/cubedemo01.html" target="_blank">cube and cylinder example</a>.</p>
<p>Here&#8217;s the HTML:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
	&lt;head&gt;
		&lt;title&gt;A moving camera - Made with three.js&lt;/title&gt;
		&lt;meta charset=&quot;utf-8&quot;&gt;
	&lt;/head&gt;
	&lt;body&gt;

		&lt;div id=&quot;container&quot;&gt;&lt;/div&gt;

		&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js&quot;&gt;&lt;/script&gt;
		&lt;script src=&quot;js/Three.js&quot;&gt;&lt;/script&gt;
		&lt;script src=&quot;js/RequestAnimationFrame.js&quot;&gt;&lt;/script&gt;
		&lt;script src=&quot;cubedemo01.js&quot;&gt;&lt;/script&gt;

	&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>No appreciable change since last time.</p>
<p>Here&#8217;s the JavaScript. Comments in the code to aid understanding.</p>
<p>I came across the RequestAnimationFrame function while looking at a three.js <a href="http://http://creativejs.com/tutorials/three-js-part-1-make-a-star-field/#1">tutorial on the CreativeJS site</a>. Details about <a href="http://http://paulirish.com/2011/requestanimationframe-for-smart-animating/">RequestAnimationFrame can be found on Paul Irish&#8217;s site</a>.</p>
<pre class="brush: jscript; title: ; notranslate">
var camera, scene, renderer;
var cube, cylinder;

init();
animate();

function init() {

	var numberOfSegments = 1;

	// Instantiate the 3D scene:
	scene = new THREE.Scene();

	// Instantiate an Orthographic camera this time.
	// The Left/Right/Top/Bottom values seem to be relative to the scene's 0, 0, 0 origin.
	// The best result seems to come if the overall viewable area is divided in 2 and
	// the Left &amp; Bottom values set to negative
	camera = new THREE.OrthographicCamera(
		window.innerWidth / -2, 	// Left
		window.innerWidth / 2,		// Right
		window.innerHeight / 2,		// Top
		window.innerHeight / -2,	// Bottom
		-2000,						// Near clipping plane
		1000 );						// Far clipping plane

	// Set the camera position so that it's not on top of our object in the scene:
	camera.position.y = 100;

	// Add the camera to the scene:
	scene.add(camera);

	// Define a Cylinder object
	cylinder = new THREE.Mesh(
		new THREE.CylinderGeometry(25,	// Radius top
			100,						// Radius bottom
			100,						// Height
			25,							// Number of segments in circumference (i.e. how smooth)
			5,							// Number of segments high
			false						// Open ended
		),
		new THREE.MeshBasicMaterial( {color: 0x372AFF} )
	);
	cylinder.position.x = 400;

	scene.add(cylinder);

	// Define the cube object
	cube = new THREE.Mesh(
		new THREE.CubeGeometry(200, 200, 200,
			numberOfSegments, numberOfSegments, numberOfSegments), // Cube geometry
		new THREE.MeshBasicMaterial( { color: 0x373737} ) // Material
	);

	// Add the cube to the scene:
	scene.add(cube);

	// Instantiate the renderer
	renderer = new THREE.CanvasRenderer();
	// .. and set it's size:
	renderer.setSize(window.innerWidth, window.innerHeight);

	// Place the renderer into the HTML (inside the #container div):
	$('#container').append(renderer.domElement);

}

function animate() {
	// Defined in the RequestAnimationFrame.js file, this function means that the
	// animate function is called upon timeout:
	requestAnimationFrame( animate );

	render();
}

function render() {

	// *** Update the scene ***

	// Set the camera to always point to the centre of our scene, i.e. at vector 0, 0, 0
	camera.lookAt( scene.position );

	// Move the camera in a circle with the pivot point in the centre of this circle...
	// ...so that the pivot point, and focus of the camera is on the centre of our scene.
	var timer = new Date().getTime() * 0.0005;

	camera.position.x = Math.floor(Math.cos( timer ) * 200);
	camera.position.z = Math.floor(Math.sin( timer ) * 200);

	renderer.render(scene, camera);
}
</pre>
<p>More posts to come on this topic I hope as I dig into the Three.js engine a little further.</p>
<p>&nbsp;</p>
<div id="tweetbutton78" class="tw_button" style=""><a href="http://twitter.com/share?url=http%3A%2F%2Fwww.96methods.com%2F2011%2F12%2Fthree-js-moving-the-camera%2F&amp;text=Three.js%3A%20Moving%20the%20Camera&amp;related=&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Fwww.96methods.com%2F2011%2F12%2Fthree-js-moving-the-camera%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://www.96methods.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.96methods.com/2011/12/three-js-moving-the-camera/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

