Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // @themoep
- // keep track of color. is float so change can be slow without huge numbers
- float c = 0;
- // the moving points are balls, but we don't draw them as such see visualize() later
- Ball[] balls;
- void setup() {
- size(800,800);
- // make 50 new balls to bounce around
- balls = new Ball[50];
- for(int i=0; i<50; i++) {
- balls[i] = new Ball();
- }
- strokeWeight(2); //makes lines 2 pixels thick
- colorMode(HSB, 100); // changes red-gree-blue mode to hue-saturation-brightness with a range of 0-100
- }
- void draw() {
- // change this to make the colours change faster/slower
- c+=0.05;
- if(c > 100) c = 0; // if it gets bigger than our colormode, wrap around back to 0
- // the hue alone now controls the color; saturation and brightness at max
- stroke(color(int(c), 100, 100));
- // first we update the position of each ball
- for(Ball ball : balls) {
- ball.update();
- }
- // and then we draw the connections. if we do both in the same loop we might
- // update a position after drawing some lines and before drawing others, making tiny glitches
- for(Ball ball : balls) {
- ball.visualize(balls);
- }
- }
- class Ball {
- // each ball has a position and velocity. we could use PVectors instead, but I forgot about them.
- float x, y, dx, dy;
- // a new ball starts at a random position and with a random speed that's limited by 5 in either dimension
- Ball() {
- x = random(width);
- y = random(height);
- dx = random(-5,5);
- dy = random(-5,5);
- }
- // here we apply the velocity and check if it hits an edge. if so, we swap the direction of the velocity to make it bounce off the edge
- void update() {
- x+=dx;
- y+=dy;
- if(x > width || x < 0) dx*=-1;
- if(y > height || y < 0) dy*=-1;
- }
- // this is pythagoras applied: we first get the absolute value of the difference of x and y respectively
- // then square the x and y difference and take the square root of that.
- // would be prettier with PVectors, but as I said, I forgot about them >_>
- float distance(Ball other) {
- return sqrt(pow(abs(this.x-other.x),2)+pow(abs(this.y-other.y),2));
- }
- void visualize(Ball[] balls) {
- // we need all the balls there are
- for(Ball other : balls) {
- // and skip if the current one is the same
- if(this.equals(other)) {
- continue;
- }
- // and only draw a line if the distance is less than 150
- if(this.distance(other) < 150) {
- line(x,y,other.x, other.y);
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment