mstropka-Project 03-Section E

sketch

//Max Stropkay
//Section E
//mstropka@andrew.cmu.edu
//Project 03

var squares = []; //empty array for squares
var speed = 5; // speed multiplyer for motion of squares
var squaresize = 40; //initial square size
var angle = 0 //initial rotation of squares

function setup() {
    angleMode(DEGREES);
    createCanvas(640, 480);

    //loop that continually makes 400 squares inside the array
    for (var i = 0; i < 400; i++) {
      squares[i] = {
      //squares are drawn at a random location on canvas
      x : random(0, width),
      y : random(0, height),
      //draw the squares
      display: function() {
        push();
        noFill();
        stroke(225);
        //if the mouse is within 100 pixels of any of the squares
        if(dist(mouseX, mouseY, this.x, this.y) < 100){
          stroke(255,0,0); //stroke will become red
          rotate(angle + random(-10,10)); //squares will rotate +-10 degrees
          squaresize = squaresize + 10; //squares will grow by 10 pixels in the x and y direction
        }else{
          squaresize = 40; //if the mouse is not close, the squares will return to normal size
        }
        rect(this.x, this.y, squaresize, squaresize); //draw the squares
        pop();
      },
      //gives squares random movement in x and y direction if mouse is within 100 pixels
      move: function() {
        if(dist(mouseX, mouseY, this.x, this.y) < 100){
          this.x = this.x + random(-1, 1) * speed; //causes squares to move in a random x direction
          this.y = this.y + random(-1, 1) * speed; //causes squares to move in a random y direction
          }else{
          this.x = this.x //if the mouse is not within 100 pixels, dont move
          this.y = this.y
        }
      }
    }
  }
}
function draw() {
    background(120);
    //make squares until the array is full
    for (var i = 0; i < squares.length; i++){
    squares[i].move(); //runs move function
    squares[i].display(); //runs display funtion

  }

}

For this project I wanted the mouse to interact with a lot of shapes in the sketch. I did some research and figured the best way to do that was to set up an array for all of the objects that the mouse was to interact with. After watching several explanations on youtube, I figured out how to apply what we learned about changing shapes in class to what I learned online about arrays. The result is a program that generates a bunch of squares that rotate, grow, move, and change color when the mouse is near them.

Leave a Reply