edit upload recent print
Search

                                          



* WikiDocs

Main » ProgramFlow

Program Flow (in Processing)

As discussed, Processing provides two 'special' functions that you will use in each of your programs: "setup" and "draw". Like any function, there can only be one (each) of these, and they must have the exact signature (case-sensitive) as you see below, otherwise they will not be called by Processing.

setup()

The setup function is run once (called automatically), at the start of every Processing program. It is typically used to set things like size(this should generally be first), frameRate (how fast the pgroam runs), to load fonts and other media(images, sound files, video, etc.) and do other things that only need to happen once.

        void setup()
        {
            // YOUR CODE IS RUN ONCE AT STARTUP
        }

draw()

The draw function is executed in a loop (also called automatically). It is run continuously throughout the execution of the program.

        void draw()
        {
            // YOUR CODE IS RUN OVER AND OVER AGAIN
        }

stop() [optional]

The stop() function is optional and (like 'startup') will be executed exactly once, when the program exits.

       void stop()
        {
            // YOUR CODE IS RUN ONCE AT END OF PROGRAM
        }

Here's a common use of setup():

        // Notice that we (generally) declare our variables 
        // at the top, outside of both setup() and draw().
        // For more info on this, see variable scope

        int myInt = 0;  

        void setup()
        {
            size(500,500);
            background(255,255,255);
            frameRate(15);  // Defines how many times per second draw() will run
            fill(255,0,0);  // (red,green,blue [0-255])
            stroke(0,0,0);  // (red,green,blue [0-255])
        }

Here's a simple draw() which includes some variable usage (see the 'int myInt = 0;' line above):

        void draw()
        {            
            rect(myInt, myInt, 50, 50);  
            myInt = myInt + 1;
        }

If we copy these lines of code into Processing we will see a rectangle move from the top left of the screen down to the bottom right; a simple animation. The setup function sets up our window and the draw function runs 15 times per second, giving us the appearance of movement.


Here's a typical stop() function:

        void stop()
        {
           DirtyLibrary.stop(this);
        }

The stop() function is where you'd do any clean-up of resources you've used. Often, calls to a library's stop() method are placed here so the library knows to do its own clean-up.

If you're not using a library that requires it, or doing something fancy, you can generally leave out this method.



Instructor: Daniel C. Howe

Resources

     MORE

Page last modified on February 09, 2008, at 01:11 PM EST