// // Snowflake 2 // // Global varables ----------------------------------------------------- int NrFlakes = 3000; // Maximum number of flakes. int NrUseFlakes = 100; // Number of using flakes. float Wind = 0; // Strength of the wind. Snowflake Flake[]; // Snowflake array. // Global functions ---------------------------------------------------- // Initializations. void setup() { // Set screen size. size(600, 400); // Create snowflakes. Flake = new Snowflake[NrFlakes]; for (int i = 0; i < NrFlakes; i++) { Flake[i] = new Snowflake(); } } // Main loop. void loop() { background(0); snow(); } // Control snow. void snow() { for (int i = 0; i < NrUseFlakes; i++) { Flake[i].Behave(); Flake[i].Draw(); } } // Event handlers ------------------------------------------------------ // On mouse dragged. void mouseDragged() { // Horizontal drag brings wind. Wind = constrain(Wind + float(mouseX - pmouseX) / 10.0, -20, 20); } // On key pressed. void keyPressed() { int delta = 0; if (key == 'a') delta = 10; // Inc. snowflake by 'a' key. if (key == 'z') delta = -10; // Dec. snowflake by 'z' key. NrUseFlakes = constrain(NrUseFlakes + delta, 100, NrFlakes); } // Class definitions --------------------------------------------------- // Snowflake class. class Snowflake { // Constructor. Snowflake() { // Distribute around the screen. _x = random(width); _y = random(height); _p = radians(random(360)); _a = random(1); _c = int(random(255)); } // Snowflake behavior void Behave() { // Advance the windage phase. _p += random(1); // Fluctuate the windage amplitude. _a = constrain(_a + random(-0.2, 0.2), -2, 2); // Windage effect (wrap around the screen width). _x += _a * sin(_p) + random(1) * Wind; if (_x > width) _x -= width; if (_x < 0) _x += width; // Heavier flake drops faster. _y += random(-0.25, 2.0 + _c / 240.0); if (_y > height) { _y = 0; _x = random(width); _p = radians(random(360)); } } // Draw the snowflake. void Draw() { stroke(_c); point(_x, _y); } // Data members. float _x; // X coordinate. float _y; // Y coordinate. float _p; // Phase of windage. float _a; // Amplitude of windate. float _c; // Color (weight). }