Blog

GiantBomb Blog

I used to be a writer for the gaming blog Bits ‘n’ Bytes Gaming, which was shut down due to the head editor moving on to bigger and better things. However, before it died I got an export of most of the articles I had written and I took the time to transfer them over to my profile on GiantBomb, adding the images and references to games as much as I could. The articles span about a year and they vary greatly in scope and quality, the crown jewel being my analysis of the use of Viking themes in games, which took me two months to research and write.

So check it out as I may be posting more articles and reviews if the mood strikes me: My Blog on GiantBomb

Standard
Web

Creating an Animation Loop with JavaScript

So you want to animate some JavaScript, do you? Thinking about creating an eternal loop using setInterval or maybe a recursive method that calls itself using setTimeout? You’re thinking that if you use 1000/60 as the interval time you’ll get a smooth 60 FPS which will look really cool and smooth. I used to be like you, until I discovered that setTimeout isn’t guaranteed to wait the allotted time before calling the passed function, which (in extreme cases) may result in jittery and unpredictable animations.

Before we begin, you should note that CSS animations exist and are a great way to add small animations to your web apps without having to manually transition the values of style properties, but it may not provide you with what you want, so if you need a more programmatic way of creating animations, this may help.

To understand what we’re doing you should understand the concept of the “main loop” as it pertains to game development (see Wikipedia if you’re curious). In essence, it is a never-ending loop that runs as long as the application is running and receives as its only parameter the delta-time, or time since the last time the method was called. The delta-time (referred to as Δt from now on) is usually a float which represents the seconds since last iteration of the loop and can be terrifyingly small if your system is fast enough. It is used to separate the animation logic from the clock speed of the computer, as faster computers will result in faster loops which may break the code unless you use Δt as a “balancer”. For example:

// Move the object 100 pixels every time the loop is run.
// This will result in a different speed for faster/slower computers.
position = position + 100

// Move the object 100 pixels per second.
position = position + (100 * dt)

Wrapping your animations in a “main loop” and using Δt to adjust all your speed/timing code to be based on time rather than the speed of the loop will result in the same result no matter which computer is running the code. However, you should also throttle the loop rather than letting it run as fast as it wants, because otherwise you’d consume all of the computer’s processing power to run your animations. In JavaScript, this can be done by using setTimeout to call a loop function rather than using something as crazy as while(true).

Finally, you’ll need some way to calculate Δt, which can be as simple as using the built in Date.now() method to determine the amount of milliseconds which has passed since the last loop iteration. Putting it all together, you get a code snippet which looks like this, which will move something by 100 pixels per second and attempts to have 30 frames per second:

var then = Date.now(),
    interval = 1000/30;

function animation(dt) {
    position = position + (100 * dt);
}

function looper() {
    var now = Date.now(),
        dt = then - now;
    animation(dt / 1000);
    setTimeout(looper, interval);
    then = now;
}
setTimeout(looper, interval);

This will work as a basic template for getting animations to work, but you should be aware of a function called requestAnimationFrame, although you should be aware that Opera and Internet Explorer are lagging behind on supporting it. It’s a better way to handle animations, as it will be called every time the page can be redrawn, rather than using an arbitrary interval that you specify. Also, it’ll not be called if the browser is showing another tab or is in some way unable to redraw the page, which will save on processing power but this may result in some odd bugs as the animation will not continue running in the background. requestAnimationFrame takes a single callback as a parameter and will pass along a steadily increasing timestamp, which you can use to determine the Δt. Updating the code snippet above to use requestAnimationFrame will make it look like this:

var then = 0;

function animation(dt) {
    position = position + (100 * dt);
}

function looper(now) {
    var dt = then - now;
    animation(dt / 1000);
    then = now;
    requestAnimationFrame(looper);
}
requestAnimationFrame(looper);

I’ve put together a basic animation template which uses requestAnimationFrame if it’s available and falls back to relying on setTimeout if not, available over at jsFiddle: Animation Loop Demo

Standard
Web

Removing jQuery From a Web App

My little dice-rolling app, RPG Dice Bag, isn’t a severely complicated app, so I thought I’d take a chance at removing the jQuery JavaScript Library and rewriting the code to use “vanilla” JavaScript. I, like probably a lot of other web-developers, have become increasingly dependent on jQuery to handle the heavy (and light) lifting in our JavaScript-powered websites and apps so this would be a great challenge for me to learn how to do it the old-fashioned way. Also, no AJAX calls necessary, so that’s a plus.

Removing jQuery from a project is pretty simple, you remove the jquery.js file (jquery.min.js if you’re in production) and you’re all set, but I soon realised that after nearly 3 years of habitually including it to every web-project I came near, I’ve plum forgotten (or never learned) how to do many fundamental things.

document.ready

The first challenge that hit me was how to listen for when the document was ready for JavaScript events to be attached to the DOM. In jQuery, it’s rather straightforward and simple.

$(document).ready(function() {
    // all ready for you ;) 
});

There is no such thing as “document.onready” in bare-bones JavaScript, but searching for it lead me down a path of learning about the native way to handle events, known as addEventListener, which can be applied to all DOM elements and is also used to handle clicks (coming up later). It’s supported by most modern browsers (I’ve completely cut IE out of my diet), so it became my first step to removing the jQuery code from my app. There are various ways of checking whether the DOM is ready, but I opted for the following:

document.addEventListener('readystatechange', function() {
    if (document.readyState === 'complete') {
        // let's do this thing!
    }
});

CSS-Style Selectors

One of the greatest benefits of jQuery is to be able to drill down into the DOM by using CSS-style selector strings to specify which element you’re looking for. Something as complicated as “#app ul .title a:hover > span.left" can be used to choose one specific element, or a set of elements that are situated in various places around the document. Unfortunately there isn’t a direct replacement in native JavaScript, but a combination of getElementById, getElementsByTagName and getElementsByClassName, as well as iterating through the results, can be used to select the element(s) you need and not being able to rely on CSS pseudo-classes or some of the more esoteric selectors may result in structuring the HTML in a less convoluted way, avoiding unnecessary strain on the browser who has to deal with all your crazy shenanigans.

// Get the data-foo attribute of all links inside a .button list
var buttons = document.getElementsByClassName('buttons'),
    foo = '';
for (var i = 0; i < buttons.length; i++) {
    var links = buttons[i].getElementsByTagName('a');
    for (var j = 0; j < links.length; j++) {
        var link = links[j];
        foo += link.attributes['data-foo'];
    }
}

Edit: My good friend Torjus Bjåen made me aware of the querySelectorAll function, which provides the same CSS-style selector capabilities that jQuery does, albeit without some of the more “magical” selectors. It works like you’d expect and can be used to easily fetch elements that may be spread about the DOM.

var links = document.querySelectorAll('.buttons a.special');
for (var i = 0; i < links.length; i++) {
    links[i].style.backgroundColor = '#f09';
}

Click Event Delegation

To avoid overloading the browser with too many event handlers in the cases where you have sets of elements that need to react similarly, you should try to add your events to their parent element and delegate the event to the correct element by using a selector.

$('#buttons').on('click', 'a', function(event) {
    // button was clicked
});

Translating this to vanilla JavaScript isn’t really possible without understanding that the Event object which is passed to the function you attach to an event has a property called target which is the DOM element which received the event. Note that this is not necessarily the element which you attached the event listener to, but it could be the child of the child of the child of the child of said element, which may be further down in the tree than you really need to go. In that case you’ll need to traverse your way upwards, using the parent property until you find the one you’re looking for (if you ever do).

var elem = document.getElementById('buttons');
elem.addEventListener('click', function(event) {
    var target = event.target;
    while (target.tagName !== 'A') {
        target = target.parent;
    }
    if (typeof target !== 'undefined') {
        // "#buttons a" was clicked
    }
});

Auto-wrap Everything in Conditionals

All this work was getting me closer to understanding the fundamentals of the DOM and how JavaScript (and the browser) worked when trying to parse and understand the ever-complex world of HTML. However, there is one small thing that jQuery does which I’m going to miss, nevermind how much “better” my code is now.

// jQuery
$('#buttons').css('background-color', '#f09');

// native
var buttons = document.getElementById('buttons');
buttons.style.backgroundColor = '#f09';

The biggest difference between those two examples (which accomplish the same thing) is that jQuery will fail silently if the element doesn’t exist. This is a major difference for web development where your dynamic HTML may not always be in sync with the JavaScript you wrote for it and when JavaScript hits an error it stops, spits out something in the console and then goes home to sulk. jQuery essentially removes the potential headache of an app-breaking bug resulting from not wrapping the line in an if statement, which is a blessing for any project of sizeable complexity.

Becoming too dependent on jQuery is one of the many casualties of the splintered JavaScript support that the various browsers support and even my tiny app probably has some code that isn’t supported in any of the browsers if you go far enough back. Its biggest strength (and most often repeated party line) lies in the cross-browser support, but my own experiences shows that there are a slew of jQuery-isms that I’m learning in lieu of doing it “the right way”, which will probably just end up hurting me in the long run, especially when I see how complicated things can get when I have to traverse the DOM tree manually.

I’m not saying that using jQuery is bad (hell, I’d rather avoid XMLHttpRequest for the rest of my life if I can help it), but it’s interesting to note how much of the DOM is hidden behind its flair and rounded corners and the dangers that are posed by relying on dangerously slow and memory intensive CSS-style element selection for something that could be handled faster/harder/stronger with a slight restructuring of your HTML.

Standard
Blog

Lorem Ipsum Coda 2 Plugin

When I need my fix of dummy text, I hit the lipsum bar down by the marina. It’s a nice place, decently clean and gives me what I need. I’ve also gotten to know the bartender, Johnny, who lost his leg in Iraq and has foolish dreams of playing accordion. However, when the local sentence generator just isn’t closeby enough, I turn to code to get the job done. My editor of choice Coda 2 is full of lots of fancy features, but a menu option for generating dummy text wasn’t among them, so like any sane person I built my own.

Lorem Ipsum Coda Plugin  Lorem Ipsum Coda Plugin  Lorem Ipsum Coda Plugin

It works by spitting out a sentence of random words, taken from a pool of common Lorem Ipsum words. If you only need a single sentence you press it once, but spamming the keyboard command will cover you in a blanket of gibberish.

Lorem Ipsum Coda Plugin

Source on GitHub

Standard
Web

Animating CSS Transformations (with jQuery)

CSS transformations are an awesome way to add some crazy effects to your website, but what if you want to animate them using jQuery? The standard way of doing things doesn’t work because the transform property isn’t a basic value, so you’ll have to do it yourself using the step parameter in jQuery’s animate method.

$('.container').css('data-scale', 0);
$('.container').animate({ dataScale : 1 }, {
    step: function(now,fx) {
        // the "now" variable will go from 0 to 1
    },
    duration:'slow',
});

I do a little hackish thing by setting a css property which doesn’t exist (data-scale) to zero and then asking the animate method to grow it to one. Then inside the step function I get access to the now variable which will go from zero to one and can be used to determine at what point in the animation we are. This way I can manipulate as many css properties as I want in any form I want.

function(now,fx) {
    // Scale the element from invisible to twice the size
    var scale = 'scale(' + (2 * now) ')';
    $(this).css({
        '-webkit-transform' : scale,
        '-moz-transform' : scale,
        '-ms-transform' : scale,
        '-o-transform' : scale,
        'transform' : scale
    });
}

This way you can go crazy with the animations and have eased matrix transformations going on all your elements, using the power of math.

Check out this demo to see it in action.

Standard
Blog

Retrospective: Slipfeed

Slipfeed (version 1.0)

Slipfeed was a blindingly ambitious project I undertook while still studying at the University of Oslo, at the time IndieDB had yet to open its doors and I was in the need of a place where indie games could be published and promoted in a way that gave me a constant stream of new indie games to play. The original project was completed as a part of a course in building websites, but it wasn’t until I rewrote the website from scratch (in the course of a frantic few weeks) where it became the guiding light of indie-game-promotion that I wanted it to be. I was young, inexperienced and thought that building a social network from scratch was a smart idea.

The page was based around feeds where you could get updates on specific (favorite) projects, your friends or all the projects on the site, each with the means to filter out and only show the types of updates that you were interested in. The resulting feed could be subscribed to using RSS and I was planning to expand on this possibility in the future. The idea was that I wanted a constant stream of new indie games to play and the best way to do so was to have some sort of automated process which filtered out the noise and showed me just what I wanted to see.

The problem was that nobody used the page. “Build it and they will come” really doesn’t work in the world of web apps and this was a great example of developer hubris taken to its (il)logical extreme. I had crafted an elegant home for all the wayward indie games who spent a lot of time (too much, if you ask me) trying to get attention around their independent blogs or promotional sites. Instead they should come to Slipfeed, where they would be given an audience who were hungry for games. An audience which didn’t exist, yet.

The feed for a single project, showing test data for LÖVE as the original data was lost a while back.

The feed for a single project, showing test data for LÖVE as the original data was lost a while back.

I know next-to-nothing about marketing, but I knew even less back then, and weeks went by with no activity flooding in. I did everything I knew to do, spamming forums, cold-emailing developers and even trying to get some cross-promotion going with an indie games competition, but in the end I just had a meager amount of friends-of-friends to speak for. Disillutioned, I left the site to its own devices and, several months later with no activity, I opted for shutting it down; the last content update had been my own, many weeks earlier.

I felt defeated, but it hammered home the adage that ideas aren’t worth anything without execution. The technical aspect was adequate and given time it could have grown into something beautiful, but user-made-content-based sites aren’t worth their salt without users and getting over the hump of having nobody show up to my party was beyond my capabilities, knowledge, and to a certain degree, my interest. I wanted to build something awesome, not spend my time telling people how awesome it was. I got to experiment with a lot of cool stuff, like OpenID integration, building “metaphysical” database tables, creating tiered/timed content (which I intended to monetize), so I ended up a more experienced developer in the end. I’m not bitter from the experience, I’m smarter and maybe just a little humbler.

Standard
Web

Instagram Hashtag Analyzer

I’m a semi-active user of Instagram and I’ve noticed that peoples’ use of hashtags usually results in a few specific patterns. There are those who avoid hashtags altogether, others who use it to tag their post by adding the hashtags at the end of the caption, others who use hashtags intermixed in their caption to highlight certain thematic words and finally there are those weirdos who like to #hashtag #every #word #like #a #madman.

Statistics are interesting to me, and because it has been years since I did any work with Python I wrote a script which will load the latest popular entries and analyze the caption for the aforementioned patterns. The end result is InstagramHashtagAnalyzer, a Python class (which can be run by itself) that transform the caption of media posts to a pattern that can be analyzed using regular expressions.

“This is an #example of #hashtag use” becomes “0001010″

The end result was curious, as I discovered that most people avoid using hashtags alltogether and prefer to just use text, which isn’t what I expected based on my small list of friends. Running the analyzer with 10,000 entries worth of data resulted in the following output:

Analyzing 10000 media items:
Unknown: 72 (0%)
Hashtags only: 309 (3%)
Tags: 1600 (16%)
Text only: 7530 (75%)
Highlight: 489 (4%)

Which I plotted into this nice Google documents graph, because numbers are so passe.

InstagramHashtagAnalyzer results

The script is rather rudimentary as of now, but there is chance for growth, including the means to analyze your own entries, those of the poeople you follow as well as tying up the hashtag use with social data (such as age, gender, location, etc.)

Source on GitHub

Standard