Difference between revisions of "Graphics With Processing II"
Line 88: | Line 88: | ||
y = 100 * sin(2 * PI * t) + centerY; // not pre-defined anymore | y = 100 * sin(2 * PI * t) + centerY; // not pre-defined anymore | ||
}} | }} | ||
+ | |||
+ | == Step 5: Making a game out of these elements == |
Revision as of 12:30, 3 April 2012
COMP 1010 Home > Back to Extra Labs
IntroductionIn this lab, we'll learn how to create animation using Processing language.
|
---|
Step 1: Setting up the animation with frame rate
When you draw anything, the method draw is actually called repeatedly to form the shape. It is by default 60 frames per second, and it might be considered too fast for an animation. We can define our own frame rate by using Processing's frameRate method:
int sides = 3; void setup() { size(600, 600); frameRate(6); // 6 frames per second }
Step 2: Increment/Decrement decisions
void draw() { float x, y; float xPrev = 0, yPrev = 0; float tinc = 1.0 / sides; background(0); stroke(255, 0, 0); for (float t = 0; t <= 1 + tinc; t +=tinc) { x = 100 * cos(2 * PI * t) + 200; // pre-defined in code y = 100 * sin(2 * PI * t) + 180; // pre-defined in code if (t > 0) { line(x, y, xPrev, yPrev); } xPrev = x; yPrev = y; } sides++; }
For this part, notice that when sides gets really large, it is going to become imperceptible. We need something to control the change of the sides so that incrementation and decrementation interchanges upon reaching some limits. For example, we can specify a state boolean variable outside our methods(boolean increasing = true). So before we change the size, we check whether the increasing is true or false. If it is true, increment the sides, else decrement it.
if (increasing) { sides++; }else { sides--; }
And you can determine the limits where you want the increment/decrement to be switched.
if (sides > 49) { // you can decide increasing = false; }else if (sides < 1{ // you can decide increasing = true; }
Step 3: Eliminate the awkward point
You may notice a point sitting on its place all the time. This is the point where t = 0. We can add another state variable float start = 0
Step 4: Working with Processing interactivety power
First of all you want to add two other state variables. Those two combines together is a coordinate of the center of your polygon. Here, we will use the same coordinate we used earlier.
int centerX = 200, centerY = 180;
Then, Processing is able to detect if a click has been made.
if (mousePressed) { centerX = mouseX; centerY = mouseY; }
This will make the clicked point to be the new center of the polygon.
And the new polygon can be drawn at the new position by modifying contents inside our for loop:
x = 100 * cos(2 * PI * t) + centerX; // not pre-defined anymore y = 100 * sin(2 * PI * t) + centerY; // not pre-defined anymore