Apple Day

National Apple Day is an actual thing, believe it or not, and there's long been a connection between Apples and Physics. I'm a fan of both so created this experiment to show my appreciation for the two using Matter.js

Tool kit

Matter.js is a pretty lightweight library around 75kb (minified). I was thinking at some point I'd use this in a display advertising concept. In the meantime I wanted to investigate the library and what it could do.

View Project

I intended on Tweeting a link to the project on #NationalAppleDay and not knowing if my audience was going to be on Desktop or Device meant this really needed to be cross-platform.

Code wise it's not an issue, Matter.js runs fine across all HTML5 browsers, the amount of physics equations you can run however is a different ... matter. The more "nodes" you create the harder the processor has to work. Having, for instance, a million apples all bouncing around would probably cause older devices to grind to a halt so the apple amount has been limited.

There's a little bit of random in here too, since apples are both red and green there's a simple if statement that runs "onload" and checks what state the apples and background should be in.

App.appMain.setColours = function(){ if(App.config.whatState === 1){ //Green App.sprites.messageTexture = 'img/greenMessage.png'; App.sprites.appleTexture = 'img/redApple.png'; App.config.baseColour = App.colours.green; App.dom.messageContainer.style.backgroundColor = App.colours.green; App.dom.greenErrorApple.style.display = "inline-block"; App.dom.greenRefreshButton.style.display = "inline-block"; }else{ // Red App.sprites.messageTexture = 'img/redMessage.png'; App.sprites.appleTexture = 'img/greenApple.png'; App.config.baseColour = App.colours.red; App.dom.messageContainer.style.backgroundColor = App.colours.red; App.dom.redErrorApple.style.display = "inline-block"; App.dom.redRefreshButton.style.display = "inline-block"; } App.appMain.configureWindow(); }

This determines if the apples are green and the background red...

alt

...or if the apples are red and the background green.

alt

There was one slight issue when handling orientation changes with how to re-render the canvas and collision boundaries but, since this was a physics experiment and not a RWD experiment, I opted for a graceful degradation which simply informs the user of such with a prompt to refresh should they rotate their device or resize their browser, at which point the code "onload" will work itself out in accordance with the the screen dimensions.

I wrote a blog post which goes into a bit more detail. If you'd like to know more all the source code is available on my GitHub