Fishes flocking fun with JavaScript

This spring I was working on a “ocean themed” site taking the user on a journey to the great depths of the North Sea. And of course, in every ocean there needs to be
fish happily swimming in flocks. So I started doing some research into flocking, and with some experience from creating particle systems, the first prototype was done in in a day.

See the Pen Fish flocking simulation by Pål Smitt-Amundsen (@gadgetgnome) on CodePen.

The basics of flocking is that one fish tries to find a buddy to follow, one that it can see in a sector relative to it’s swimming direction. Once a buddy is found, it tries to follow as best it can, limited by its max speed among other properties.

To see who a fish is following, hold the shift-button on your keyboard. Red lines will point out the leader, also green lines will display the “negative force field” that the mouse cursor is to the fishes. The are just really scared of the cursor, trying to avoid it the best they can.

Feel free to peek into the code using the link below, there are some comments that should explain the basics. I wrote the code from scratch with a JS “class” for a Fish, making it easy to instantiate a thousand of them with the “new” operator. The particle system is drawn on a canvas, drawing the fish from a bitmap with correct rotation and position from its “particle” properties.

Go ahead, visit CodePen:

Automatic brakes on bumper cars!

Late summer I was lucky enough to participate in a build project we did for our client Volkswagen. The idea was illustrating their automatic braking system by creating a similar system for bumper cars, filming people driving them unbeknownst of our modification. Take a look at the result here:

And if you are interested in how created this, check out the “behind the scenes” video with Knut explaining the basics of the setup.

The brake system was powered by pneumatics, so several large dive tanks was needed to keep the smaller bottles refilled the whole recording day. This picture was taken after, with the brake system parts all back in boxes after restoring the bumper cars to their normal brake-less setup.
Dive tanks and parts

The parts for each cars setup, hidden under the seat for a surprising effect (from L to R):

  • Small “pony bottle” diving tank
  • Pressure regulators
  • Blue Festo air tubes (awesomeness with quick-release!)
  • Computer box with battery, Raspberry PI and Arduino interfacing the ultrasonic sensor-array and sending the the data to the server via the tailor made SW.
  • Massive relay to withstand the big current drawn by the car
  • Festo solenoid electromagnetic air valve to feed air into the brake valves.

Car brake parts

The feeling of just holding one of these beautiful Festo cylinders cannot be described with words, the build quality is unbelievable. We used two in each car, each capable of lifting 178KG (1750 Newtons) at 10 bars!
By the power of Festo!

All in all I’m in awe of the design and production that Knut and Morten did, mostly just contributing to the electro mechanic part myself.

A “flappy” game prototype in JS with 1k tips

Last winter I was working on a Unity game project, discussing game concepts with 3D artist colleague Magne, namely the simplicity of “Flappy Bird”. How can it be that simple, and at the same time so addictive? We talked about having a go at it ourself, creating a spin-off or tweak to the concept. Shortly the idea of making a circular scene came up, like the old classic ‘defender’, but also inspired a little by the brilliant iPad game Osmos. Instead of the player going through ports, he/she would rather circle a planet only avoiding colliding into satellites or entering outer space. Our first goal was then to see if this was something worth spending time on – to answer that I created a prototype of the game. Try it for yourself, keep your black “spaceship” within the red “atmosphere” of the darker red planet, pressing the mouse or keyboard to add thrust clockwise.
Game screenshot

Did you like it? Was it to hard? Was it at all addictive? I knew creating a prototype of the game mechanics was the only way to answer this, as simple and quick as possible. JavaScript provides that with simple coding, great number of resources, and using a service like JSBin – a super quick start without needing anything else than a browser installed. JSBin also provides revisions, so you can demo and compare the game to older versions. For more control now however, I have moved the game to my Dropbox continuing coding with trusty editor Sublime. I also find that it’s easier to debug outside JSBin, using breakpoints and the handy debugger statement.

I started developing the game with just moving DOM-objects around, but due to performance issues on mobile I ported it to use Canvas as it is highly optimised on mobile browsers. It also meant more lean code, as I could eliminate both jQuery and CSS from all together.

A (1k) challenge arises

After being more or less happy with the game itself, my focus turned to the code. Could it be squeezed into, and be suitable as a 1k JS game? A challenge was created for myself, which really ignites an extra fun factor in coding. I first remember reading a post on creating 1k games, with tips including substituting and and shorting method and variable names. This of course creates a lot of unreadable code, so a lot of comments was desirable. Take a peak at these excerpts from the game code:

var a, //Angle to player from origo var
h, //Radius of player from origo
M=Math, //Sub Math
S=M.sin, //Sub Sin()
R=M.round, //Sub Round()
P=M.PI, //Sub PI
d=document, //Sub document
s=400, //Half the width of the game, width of planet
F = d.createElement('canvas'), //create a canvas to draw on

Shortening variable names saved a whole lot of bytes in combination with normal tools to minify JS. However I later learnt that Google Closure has this ability built in, without needing do make your own variable names unreadable. I bit of information I wish I had before obfuscating my code into byte sized ugliness.

Google Closure
As a bonus Closure also analyses your code for efficiency and checks for errors. Note that while Closure shortens and substitutes your own variable names, it does not substitute JS own functions. There are a lot of bytes to be saved substituting Math method names, as they are extensively used in games.

A note on difficulty

After the first afternoon of coding, I wanted to preview it to a number of people. I posted it on our work intranet resulting a nice portion of constructive feedback. Interesting enough, I got colleagues both complaining it was to difficult, and at the same time having others achieving three times the high score I had. Surely it was a good sign that they bothered to play it so much.

The initial version started with numerous enemy satellites to crash with, a little too difficult start for some players. To mend this, the game now starts with zero enemy satellites, adding on for every 100 points the user scores, with the maximum of seven.

So, what do you think? Post your score and feedback in the in the comments. If positive, Magne and I might progress into implementing the game in Unity and publishing on the app-stores!

Artikkel om meg i Kreativt Forum

Hvis lurer på hva jeg gjør på jobben – så får du et ganske utfyllende svar i denne artikkelen publisert på Kreativt Forum. Det står litt om prosjekter jeg har jobbet med, rollen min som innovasjonansvarlig og litt om undertegnede.

English: If you are wondering what I do for work – “Kreativt Forum” (Creative Forum), a web page covering the norwegian communication industry has published an article on me. It covers some projects, my role as a innovation manager and overall background. Try the Google Translated edition of it at your own risk :-)

Our talk at Making Web 2013

October 24th, Knut and I held a talk at Making Web 2013 about the project we did together at Apt. Namely how we built and developed the technical systems on “Solo – the world’s largest message in a bottle”. This was my first time speaking at a conference, and I must say it was both a challenging and fun experience. One I really would like to repeat in the near future (hint hint, conference organizers). Still, the necessary preparations and rehearsals sure tok a lot more work than I imagined. Never the less, it was the work we put in that made it possible to give the talk in a comfortable manner. Well, after a the first 5 minutes that is :-)

A video recording of our talk is available at the Making Web page. Take a look if you would like to hear about:

  • Building stuff, and integrating it’s electronics with Javascript
  • Running an unorthodox project with many suppliers
  • Creating tools for yourself in development and production
  • Using the Google Maps JavaScript API for drift prediction
  • A great story with a happy ending

Thanx to the organizers at the Making Web conference 2013 for a great experience! If you know of any other opportunities to give our talk, please get in touch. We can also modify it to be more/less about the build/electronics, web, JavasScript or just telling the story.

I’m speaking at Making Web 2013

I’m really happy to say I will be speaking with Knut Skåla at this years Making Web conference! We will be telling the story on the most amazing and challenging project I ever worked on – “Solo – The world’s largest message in a bottle”. The talk will reveal the technical solutions allowed the 8 meter bottle to report pictures and data onto the project’s webpage. The talk is named “From the Atlantic ocean to your browser“, which pretty much sums it up.

As this is the first time speaking on a conference, I’m really happy about seizing this opportunity and really hope there will be more to come. I will post a link to the talk as soon as it is published.


A real time strategy game with, Backbone and Coffeescript

This article is “work in progres”, and is as much a future reference for myself as hopefully some useful information for you as a reader. One of the options for this article is turning it into a talk/presentation, I would like to hear your opinion on that!

From spring 2012 until November 2012 I worked in project team with the purpose of recruiting more students to become engineers in the energy sector. The project should both educate, inspire and ignite a curiosity about how Norway’s offshore oil industry works. With a target audience of young people looking into a higher education, we choose to make a game. A real time strategy game. The best player would be awarded a scholarship worth 50.000$, and hence the first challenge was created.

Cheating on the front end? Move it to the back end!

Creating games on the web where there are prices involved is challenging, as games run in the browser are notoriously easy to hack. Our first challenge was then to make sure that cheating would be too hard, keeping the competition aspect fair to all participants. Including those without any Javascript skills potentially being used for mischief.

As front end on the web is easy to manipulate, the back end is another story all together. There most is invisible from the outside, with wiring and logic being “eyes only” for us developers. Our solution was then to move all game logic and state to the server, with having the front end as lean as possible. However we wanted a game that would act quick and feel responsive. At the same time the server had to be able to contact the client, so posting forms and AJAX calls were out the question. With modest experience with Node.js and, we thought:
- Why not use just that technology, even though it’s a just single player game?

Game session on server, with backup

At game startup, we would create a game on the server and use websockets via to do real time communications between the client and server. Hence it would be impossible to directly manipulate any any state or logic on the client, eliminating obvious opportunities to cheat. Also the server was set up to save all state data to DB both at intervals and disconnect, making sure games were never lost. The user could just continue  whenever he/she would like to, being on the same PC or maybe on the phone riding the subway.

Start with responsive, continue with mobile first.

Today there is no way one can ignore the amount of mobile users on the web, with some of our campaigns reaching over 30% traffic from mobile devices. This was no exception, but building a complex RTS game was already a handful, so we had to think smart. As searching and producing petrolium was the objective in this game, it was obvious that we main part of the game would be based on a map. Luckily maps are per definition responsive, with bigger screens just displaying more of the map. But games cannot only be based on maps alone, other GUI elements must also exist for interaction with the user. So our designer came up with the idea that we would just use a board game metaphor, with playing cards as the base of the UI. Cards are small and fits neatly within a mobile display, they also have a natural border – making them also look good when there is more space available. Except for the intro page, and the HQ-menu we eluded the need for media queries in most of the game UI.

Game in development, stay at your post!

Most at the time when developing for the web, you want to work at a single part at the time until it’s done. When you have a game that’s progressing as you develop, that can be challenging, like working on a card that’s triggered from an event. You certainly don’t want use a lot of time searching for oil, just so that you can work on the card that tells that you found some. Luckily my colleague Anders came up with the idea of locking revisions of save games in the DB, so that every time I reloaded the game, it would start from the same exact spot! Brilliant, and a massive time-saver in the development process. We could also name save games, if we would like to start the game at those states later.

Debug screen, shortcuts to the developers delight

For all repetitive tasks as a developer, one should create tools that eliminate them. Some examples are:

  • Restarting the game from a save game, with automatic login
  • Keyboard shortcuts for saving a game and refresh the browser
  • Skipping to a specific view
  • Manipulating the model
  • Simulating data from the server
  • Simulating series clicks on UI elements to test a workflow
  • Displaying debug information

I really urge developers to use their imagination to create those little sweet tools, they are both extremely useful and lots of fun to create! As this project was built on Backbone, I just created a Backbone.View called Debugger, with references to the models so that it could listen for change events.

Interaction design crisis, not to be taken lightly!

Exploring, finding and pumping oil from a rig you have to build is not simple. There a lot of steps that has to be done before the “black gold” is ready to be sold by the barrel. Communicating and teaching the user that process was already a challenging task, making the user complete all those steps in a game, even harder. A complex concept dictated a complex interaction, with too many choices on each map tile for the user to comprehend.

This challenge really manifested itself when I just had completed all major parts of the game and was ready to try it. A bit excited I started from the beginning, creating a new company “Snake Oil” and started the game from the top.

There was just one problem, I could not understand how to play the game which UI I had created myself!

An interaction crisis was a fact, and I rallied the troops for a whole day meeting, loaded with Post-Its, whiteboards and markers. We first tried to map all steps the user had to visit before making money on oil production, and from there we looked into solutions that would help him on his way. It was a long process, but in the end we came up with a solution that in my opinion really saved the whole game and project in whole.

A stitch of the result post-its. Showing all steps for the user to take before pumping oil.

From a solution where the user had all options available at all times for a map tile, we drastically simplified the workflow by forcing the user into a “wizard” mode for each tile. So the only choice the user had, was clicking a map tile, and the next action for the tile be presented. So instead of having a massive hierarchical menu, we just sat a logic order on all steps available. When exploring a map tile, instead of the user having to select from “2D seismic”, “3D seismic”, “environmental inquiry” and “geological research”. A click on the tile would just trigger purchasing the one action after the other. This also saved us the massive design challenge of pushing abbreviations of all those choices on a menu that would fit into a mobile display.

Result and statistics

Some statistics of the game in it’s competition phase. More to come later:

  • In the most intense weeks, average time on site was 40 minutes. On our other typical campaigns, the average is closer to 4 minutes.
  • 100 000 games were played. That’s the number equal to 2% of the Norwegian population
  • 75% of the visitors was returning, they wanted to play more

In short, we were extremely pleased with the response we got from the users and in the numbers above. The users really enjoyed the game we had created, and some even begged us to keep it running after the competition ended.

The game is still playable at it’s original link, albeit only in Norwegian:

Project team

Art Director Sebastian Rasch
Copywriter Anders Holm
Copywriter Sigurd Solberg
Consultant Ole Hustad
Project management Mona Larsen
Developer Anders Stalheim Øfsdahl
Developer Emil Jönsson
Developer Pål Smitt-Amundsen
Developer Knut Skåla
Project Music Dedmau5

Running Box2D on server with Node.js via

I was kinda bored from the TV this friday and decided that learning a little more on Node.js was more fun. Once able to run a “Hello World” example, I wanted to advance into working on websockets using Socket.IO. Socket.IO is a library for both browser and server which simplifies working with websockets, and at the same time provides fallbacks for older browsers. It was really easy to get started, sending messages between browser and server after short peek into the docs & examples.

Next step was mixing it all up and adding my favorite js library – Box2D.js! I took the code from my Box2D DOM demo in to the main file and created a module from Box2D, exposed  via module.exports. And shockingly the backend-to-frontend-port worked on (almost) the first run! So now instead of the browser animates it’s own DOM objects via JS, it receives CSS for all objects at 30fps from server!

4 browsers, 2 iPhones and 1 iPad, with a lot of boxes animated in sync:

You can download the source here. . All needed libs are embedded, just run ‘node box2dserver.js’ and host the same folder on your localhost. Also remember to change the ‘host’ address in index.html to the one running Node:

window.socket = io.connect('http://<node-server-IP-or-name-here>:8080');

Animating a webpage with Box2d physics

Now this is what I call responsive design :-)

Now this is what I call responsive design!

You may have seen fun projects/demoes where a webpage is demolished using lifelike physics animations. Wario Land Shake It is a good example of that and it’s also allows the user to drag page elements around after the video is done playing. This however is created as a full page Flash, trying to look like a HTML page. Similar cases has also been done just by pre-rendering all into a video. So I wanted to have a go at doing this in HTML, as I haven’t seen that done before.

Continuing on what I learned creating my previous post about Box2d for JavaScript, I wanted to take it a step further replacing the debug renderer with elements from a webpage. The elements should be working as a blue print for the Box2d objects, and the transformation into the physics world should be transparent. I created a quick webpage using <div> elements with some mockup content and started on the steps to make it work:

  1. Scan the appropriate part of a webpage for <div> elements, creating the corresponding counterparts in the Box2d world. This turned out to be pretty straight forward, using a jQuery selector with the each() method looping through and creating boxes in Box2D. Positions and dimensions were extracted from CSS, being absolute positioned for the sake of simplicity. After they where reset to a 0,0 position, ready for letting the animation engine handle the positions later. A reference to the <div> was injected into the m_userdata of each of the Box2d bodies.
  2. Animating is done by looping through all fixtures within the bodies in the Box2d world, retrieving the position and rotation of the objects. Thus having rotation of the boxes, just using god ol’ top & left for positioning and animating had to be forfeit. Instead we use the transform property on CSS3, offsetting the position from 0,0 and setting the correct rotation. An added super bonus is setting transform: translateZ(0) in the parent element, we get super fast GPU accelerated animation. Using the -webkit vendor prefix, we even get pretty decent performance on iOS devices.
  3. Checking that all was in a 1:1 relationship between the browser rendering of the <div> elements and it’s Box2d counterparts also had to be done. I did this by using the debug renderer on a canvas, being displayed behind the elements. In the example you can turn it on and off, also making the <div> elements transparent to see both “worlds” at the same time.
  4. Handling both mouse and touch events is always a bit of a chore when you just want to focus at the task at hand. So I wrote my first Javascript tool ever, MouseAndTouch.js that handles both types of input in your typical “press-draw-up-end” manner. The code setup is probably not quite kosher, but writing it helped me along the way of learning JavaScript.

Ok, thats quite enough talk already. Go ahead and take it for a spin! Make sure that you drag the elements after they have been dropped :-) And please comment, esp. on my novice setup on the MouseAndTouch.js as a standalone tool.

For those of you that like more technical details, here are some things I found in the development process:

  • The rotate() method of CSS3 transform does not like negative values or infinite number of decimals. So you need to normalize the angle and fix the number of decimals. I ended up specifying the angle with degrees and setting the number of decimals to two.
  • Creating some shorthand methods for creating Box2d items helps speed up the development process.