Forging Forgecraft: Integrating CSS3 Transitions with Javascript

January 15, 2012

Forgecraft is a game currently in development using Ruby on Rails, Backbone.js, and all sorts of HTML5 buzzwords. Read an introduction here, and play the demo here.

With Forgecraft, and any game really, there are usually quite a few animations running concurrently. I found these moments to be choppy, unresponsive and frustrating when they were implemented in javascript (especially on lower CPU environments like the iPad) and needed another solution. CSS3 transitions were an obvious choice to check out, as they’ve been shown to be a great way to add a little pizzazz to a modern web app and can be executed natively (and even GPU accelerated).

But, can they provide the technical underpinnings for an interactive gamely element? To be effective in this context, they’d have to be:

  • responsive, consistent and reliable
  • noticeably smoother than their javascript counterparts
  • simple to integrate with scripting

Regarding the first 2 points, CSS3 transitions’ effectiveness will really depend on your particular use-case. With Forgecraft they were definitely response, reliable, and smoother than javascript and I decided early on to use them in lieu of javascript wherever I could. But, I won’t go into the benchmarks and A/B comparisons in this article… perhaps later. Let’s just skip straight to the useful part:

Product Intergortion obscure 30 Rock reference →

Integrating CSS3 transitions with the game’s scripting is pretty straight forward:

  • Define transitions in CSS on your master element
  • Define classes with resulting properties changed
  • Trigger a class change using javascript
  • Listen for the transition-end event with javascript

Of course, there are a few pitfalls with each of these steps that I’ll go into here. Let’s take an example from Forgecraft: the Bonus Strike event. Randomly while forging the player will see a bar pop-up like this:

The bar moves from left-to-right and the player’s goal is to click the icon when the moving bar is directly under the target (large white) bar. The moving bar is animated with CSS3 transitions.

Defining the CSS:

We have a bar that needs an initial negative offset (the start position) that transitions to its final position. Simple enough: we define the base CSS on the #bar element and give it two classes (.new and .activated) defining each of its states. We also define the transition between the two states: