Tue
Apr 14th

Beautiful Algorithms 1: Fire

In this two-part article we’re going to use Ruby to make a fire animation.  It’ll look like this:

In my previous Ruby tutorial, Let’s Make a Game, I explained how to use Ruby and Shoes to make a game.  Another way to get graphics on the screen in Ruby is to use Processing.

Note: Code examples require JavaScript to run, so please view this article in your browser rather than a feed reader.

Processing

Processing is a Java-based system for creating interactive art.  It’s fast too, so you can create pretty complex graphical effects and scenes, even using 3D graphics.  The processing site has lots of examples which will run in your browser.

Like Shoes, Processing gives you a simple toolkit for working with graphics.  Take a look at the Processing reference to see how simple the API is: shapes can be made with rect(), triangle(), ellipse(); stroke and fill colours can be set with stroke() and fill().

Try downloading Processing and run a few examples.

Ruby Processing

The Processing API might be simple, but learning Java to use it is not.  It requires relatively strict syntax, and you need to pay attention to types.  Ruby Processing is a way of using Processing from a Ruby script, and takes some of the pain out of the Processing experience.

To install Ruby Processing you need rubygems installed.  If you’ve got Mac OS Leopard, you’ve probably got it.  If you’re using an older Mac OS (or Linux), it’s best to download it from the rubygems site and install it manually.

Then use either gem1.8 or the gem command to install (it was gem1.8 for me in Ubuntu):

sudo gem install processing

This will make the rp5 command available.

Ruby Processing Basics

Start a project (Processing calls projects sketches) like this:

rp5 create fire

Next, edit the fire.rb file so it looks like this:

This will draw a white rectangle.  The setup and draw methods are automatically added by Ruby Prototype;  setup is called when the sketch is started, and draw is called every frame.

To run the sketch, type this:

rp5 run fire.rb

Next Part

Now you’ve got Ruby Processing going, you can try out the full fire example.  The code is in my GitHub repository: fire-p5r.  I’ll explain how it works in the next part.

Windows Users: If you use Windows and get Ruby Processing running, please leave a comment for Windows users and I’ll include it in the article.

Comments (View)
Related Posts Widget for Blogs by LinkWithin