Week 14
Simple class and GUI examples.
Processing class example
Not exactly what we did in class, but similar.
// Class representing a point that follows the mouse. class Point { // Constants final static float VMAX = 20; // Max velocity final static float DIAM = 50; // Max drawing diameter final static float VRAND = 1; // Random velocity increment final static float VDIR = 0.5; // Velocity component moving toward mouse final static float DT = 0.5; // Delta-time for location updates // Member variables float x; // x coordinate float y; // y coordinate float vx; // x velocity float vy; // y velocity float diam; int col; // color // Constructor Point(float x, float y) { this.x = x; this.y = y; vx = crand(VMAX); vy = crand(VMAX); diam = random(1, DIAM); col = color(random(255), random(255), random(255)); } // Instance methods // Draw using member variables defining color, location, and diameter void draw() { stroke(col); fill(col); ellipse(x, y, diam, diam); } // Update velocity, location, and diameter using random increments void update() { // Accelerate randomly with bias toward mouse vx += crand(VRAND) + (mouseX > x ? 1 : -1) * VDIR; vy += crand(VRAND) + (mouseY > y ? 1 : -1) * VDIR; // Constrain velocity within max range vx = constrain(vx, -VMAX, VMAX); vy = constrain(vy, -VMAX, VMAX); // Bounce off edges of screen by reversing velocity if new coordinates // would go off screen. if (x + vx > width || x + vx < 0) vx = -vx; if (y + vy > height || y + vy < 0) vy = -vy; // Update location x += DT * vx; y += DT * vy; // Update diameter diam += crand(1); diam = constrain(diam, 1, DIAM); } } // Return random number in range [-a, a). float crand(float a) { return random(2 * a) - a; } // List of active points List<Point> points; final int NPOINTS = 100; void setup() { size(500, 500); smooth(); reset(); } void reset() { // Initialize list and fill with points starting at center of screen points = new ArrayList<Point>(); for (int i = 0; i < NPOINTS; ++i) points.add(new Point(width/2.0, height/2.0)); } void draw() { background(255); // Update location and draw each point for (Point p : points) { p.update(); p.draw(); } } // Start over when mouse is clicked void mouseClicked() { reset(); }
Reading
Java for Everyone, chapter 7.
Homework
Finish your project! Please prepare 1-3 slides to describe your work, and plan to present for about 5 minutes.