<?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>Wed, 08 May 2013 18:14:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>Looking at Git</title>
		<link>http://www.96methods.com/2012/11/looking-at-git/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=looking-at-git</link>
		<comments>http://www.96methods.com/2012/11/looking-at-git/#comments</comments>
		<pubDate>Fri, 23 Nov 2012 19:50:30 +0000</pubDate>
		<dc:creator>gblake</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.96methods.com/?p=373</guid>
		<description><![CDATA[I don&#8217;t seem to have posted anything of value for quite a while. Of course it&#8217;s always debatable as to whether anything that I write is of &#8216;value&#8217;! I&#8217;ve written several draft posts in recent months but none of them &#8230; <a href="http://www.96methods.com/2012/11/looking-at-git/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I don&#8217;t seem to have posted anything of value for quite a while. Of course it&#8217;s always debatable as to whether anything that I write is of &#8216;value&#8217;! I&#8217;ve written several draft posts in recent months but none of them have come to anything. This time I&#8217;m going to see if I can draft and commit a post on Git. Nice segway from a reference about committing a blog post to talking about Git you may have noticed there.</p>
<p>I&#8217;ve used CVS and SVN at work and I&#8217;ve used SVN for any personal projects that I&#8217;ve worked on at home, and they have served me well. SVN in particular. I have no real reason to use Git at the moment other than to give it a try, as I&#8217;ve heard a LOT about it in last two years or so, and to gain some experience in using it.</p>
<p>I didn&#8217;t want to mess around with having to set-up my own server and I didn&#8217;t want to spend lots of money on it. Ok I didn&#8217;t want to spend any money. Initially I considered GitHub as it almost seems to be the de facto standard for hosting of Git repositories. The thing with GitHub is that you can host a repo with them for free if it&#8217;s an open source project but you have to pay for private projects. Of course I don&#8217;t have an issue with that, they need to have some kind of business model where they make money. However I didn&#8217;t want to host my little project as open source. Just on principle really. It&#8217;s not that I am being precious about the code that I write but it just doesn&#8217;t seem right in principle. If I was writing a code library or framework then I would definitely host the code in an open source repo but not for a little personal coding project.</p>
<p>I&#8217;ve gone for <a href="https://bitbucket.org" title="bitbucket" target="_blank">Bitbucket</a> instead where small private projects can be hosted for free. I cannot comment on the quality of their free service too much at the moment as it&#8217;s early days but all seems good so far. They also have a free GUI application that is, at the time of writing this post, I believe available for Mac OS only? The app is named <a href="http://sourcetreeapp.com/" title="Sourcetree" target="_blank">SourceTree</a>. I did download and install this app but it seemed better to gain some familiarity with the use of Git at the command line initially.</p>
<p>One thing that I have noticed in using Git for a very short time is that using it in a development team of one, i.e. just myself, does feel a little odd. When I&#8217;ve used SVN in the past I&#8217;ve not had this sensation. With SVN you have your local copy of your code and you commit to the repository depending on your regime, after a significant change or when you&#8217;ve made a change and everything runs correctly (i.e. compiles or whatever). Ok I have to admit that most of time I will make a commit once I&#8217;ve made a relatively minor change to my code and I simply want to make sure that I&#8217;ve got a backup. Also to ensure that I have a copy of that code that&#8217;s tucked away before I make further changes to it and break things so much that I want to return to that previous, working version. Because commits with Git mean that you still have code on your local drive, ok committed to the repo but still being held locally, the question in my mind is when do you make that push to the server?</p>
<div id="tweetbutton373" class="tw_button" style=""><a href="http://twitter.com/share?url=http%3A%2F%2Fwww.96methods.com%2F2012%2F11%2Flooking-at-git%2F&amp;text=Looking%20at%20Git&amp;related=&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Fwww.96methods.com%2F2012%2F11%2Flooking-at-git%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/11/looking-at-git/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>iPad</title>
		<link>http://www.96methods.com/2012/09/ipad/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=ipad</link>
		<comments>http://www.96methods.com/2012/09/ipad/#comments</comments>
		<pubDate>Thu, 20 Sep 2012 17:29:57 +0000</pubDate>
		<dc:creator>gblake</dc:creator>
				<category><![CDATA[Mobile]]></category>

		<guid isPermaLink="false">http://www.96methods.com/?p=361</guid>
		<description><![CDATA[I write this blog post on my &#8216;new&#8217; iPad. It wasn&#8217;t until I was looking at my options in the store that I realised that the new iPad was actually called the &#8216;New&#8217; iPad and not the iPad 3. What&#8217;s &#8230; <a href="http://www.96methods.com/2012/09/ipad/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I write this blog post on my &#8216;new&#8217; iPad. It wasn&#8217;t until I was looking at my options in the store that I realised that the new iPad was actually called the &#8216;New&#8217; iPad and not the iPad 3. What&#8217;s the next iPad going to be called? The New, New iPad? Anyway I&#8217;m sure that question&#8217;s been asked before by better people than myself.</p>
<p>Typing on the iPad keypad isn&#8217;t actually as bad as I thought it would either.</p>
<p>Anyway. I actually purchased a Google Nexus 7 from eBuyer some weeks ago. I didn&#8217;t want to pay the price of an iPad and had the thought that an Android driven tablet would be better from a mobile platform development point of view. After less than an hour of using my Nexus 7 I discovered that the screen was separating from the main body of the device at the left-hand edge. After a little searching online I discovered that this is a relatively common problem. I umm-ed and ahhh-ed about this for a while, trying to decide if I should live with it or whether to return it. I decided that the problem could get worse and so decided to return it and get a refund (predicting that I had a unit that was part of a dodgy batch and that any replacement would come from the same batch).</p>
<p>After spending way too long in an attempt to return the device to eBuyer and finally getting a refund (must check my bank account) I decided to purchase the same device from a walk-in store, namely John Lewis as they have an excellent returns policy (in case I had the same problem as with the previous unit). This I attempted this weekend. Unfortunately I could not find a 16GB version of the Nexus, finding only an 8GB version; this I found in a PC World store as John Lewis had no stock. This led me to have a re-think and consider the iPad again.</p>
<p>Well, it&#8217;s performing well so far and I have no complaints. Apart from the fact that my partner uses it more than I would like!</p>
<div id="tweetbutton361" class="tw_button" style=""><a href="http://twitter.com/share?url=http%3A%2F%2Fwww.96methods.com%2F2012%2F09%2Fipad%2F&amp;text=iPad&amp;related=&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Fwww.96methods.com%2F2012%2F09%2Fipad%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/09/ipad/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ellipse Class for KineticJS</title>
		<link>http://www.96methods.com/2012/05/ellipse-class-for-kineticjs/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=ellipse-class-for-kineticjs</link>
		<comments>http://www.96methods.com/2012/05/ellipse-class-for-kineticjs/#comments</comments>
		<pubDate>Thu, 31 May 2012 17:23:44 +0000</pubDate>
		<dc:creator>gblake</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.96methods.com/?p=330</guid>
		<description><![CDATA[I&#8217;ve been taking a look at the KineticJS library in recent weeks. I wanted to draw an ellipse, rather than a circle and did a little Googling before discovering a solution. The solution, once I saw it, was a lot &#8230; <a href="http://www.96methods.com/2012/05/ellipse-class-for-kineticjs/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been taking a look at the KineticJS library in recent weeks. I wanted to draw an ellipse, rather than a circle and did a little Googling before <a title="Draw oval on Canvas" href="http://www.scienceprimer.com/draw-oval-html5-canvas" target="_blank">discovering a solution</a>.</p>
<p>The solution, once I saw it, was a lot more obvious than I was expecting. I decided to extend the Kinetic.js Shape object with an Ellipse object as detailed in the following code block:</p>
<pre class="brush: jscript; title: ; notranslate">
///////////////////////////////////////////////////////////////////////
//  Ellipse
///////////////////////////////////////////////////////////////////////
/**
 * Ellipse constructor
 * @constructor
 * @augments Kinetic.Shape
 * @param {Object} config
 */
Kinetic.Ellipse = function(config) {
    this.setDefaultAttrs({
        width: 0,
        height: 0
    });

    this.shapeType = &quot;Ellipse&quot;;

    config.drawFunc = function() {
        var canvas = this.getCanvas();
        var context = this.getContext();

		var w = this.attrs.width / 2;
		var h = this.attrs.height / 2;
		var xPos, yPos;

		context.beginPath();
		this.applyLineJoin();

		for (var i = 0 * Math.PI; i &lt; 2 * Math.PI; i += 0.1 ) { // was 0.01 but slow with lots of circles

		    xPos = (0 + (this.attrs.width / 2)) - (h * Math.sin(i)) * Math.sin(0 * Math.PI) + (w * Math.cos(i)) * Math.cos(0 * Math.PI);
		    yPos = (0 + (this.attrs.height / 2)) + (w * Math.cos(i)) * Math.sin(0 * Math.PI) + (h * Math.sin(i)) * Math.cos(0 * Math.PI);

		    if (i == 0) {
		        context.moveTo(xPos, yPos);
		    } else {
		        context.lineTo(xPos, yPos);
		    }
		}
		context.closePath();
		this.fillStroke();
    };
    // call super constructor
    Kinetic.Shape.apply(this, [config]);
};
/*
 * Ellipse methods
 */
Kinetic.Ellipse.prototype = {
    /**
     * set width
     * @param {Number} value
     */
    setWidth: function(value) {
        this.attrs.width = value;
    },
    /**
     * get width
     */
    getWidth: function() {
        return this.attrs.width;
    },
    /**
     * set height
     * @param {Number} value
     */
    setHeight: function(value) {
        this.attrs.height = value;
    },
    /**
     * get width
     */
    getHeight: function() {
        return this.attrs.height;
    }
};

// extend Shape
Kinetic.GlobalObject.extend(Kinetic.Ellipse, Kinetic.Shape);
</pre>
<div id="tweetbutton330" class="tw_button" style=""><a href="http://twitter.com/share?url=http%3A%2F%2Fwww.96methods.com%2F2012%2F05%2Fellipse-class-for-kineticjs%2F&amp;text=Ellipse%20Class%20for%20KineticJS&amp;related=&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Fwww.96methods.com%2F2012%2F05%2Fellipse-class-for-kineticjs%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/05/ellipse-class-for-kineticjs/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<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>3</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>18</slash:comments>
		</item>
	</channel>
</rss>
