Code from Processing Intro

Colors, Shapes, & Interaction:

int rectX = 300;
int rectY = 100;
int rectWidth = 100;

color rectColor = color(255);
color circleColor = color(255);

color backgroundColor = color(255);


void setup() {
  size(640, 360);
}

void draw() {
  background(backgroundColor);
  

  if (mouseX > rectX // check if x is larger than our x starting point for our rectangle
    && mouseY > rectY // check if y is larger than our y starting point for our rectangle
    && (mouseX< rectX + rectWidth) // check if we're less than the horizontal boundary of our rect
    && (mouseY< rectY + rectWidth) //same as above but for the outer bound of the rect's height
    && mousePressed
    ) { 
    rectColor = color(255, 0, 0);
    circleColor = color(0, 255, 0);
  } else {
    rectColor = color(255);
    circleColor = color(255);
  }
  
  fill(rectColor);
  rect(rectX, rectY, rectWidth, rectWidth);
  
  fill(circleColor);
  ellipse(mouseX, mouseY, 50, 50);
}

void mousePressed(){
  backgroundColor= color(random(255), random(255), random(255));
}

 

Bouncing Balls:

int x, y, speedX, speedY;
float x2, y2, speedY2, gravity;

void setup(){
 size(640, 360); 
 x = width/2;
 y = 0;
 speedX = 9;
 speedY = 10;
 x2 = width/2;
 y2 = 0;
 speedY2 = 0;
 gravity = .5;
}

void draw(){
  background(255);
  //gravity bounce
  ellipse(x2, y2, 30, 30);
  y2 += speedY2;
  if (y2 > height || y2<0){
   speedY2 *= -.95; // speed = speed * -1;
  }
  speedY2 += gravity;
  y2 = constrain(y2, 0-1, height+1); // go a little outside for the constraints so that the flipping speed logci above works
  
  //whole screen bounce aaround ball
  ellipse(x, y, 30, 30);
  x += speedX;
  y += speedY; // y = y + speed;
  
  if (x > width || x<0){
   speedX *= -1; // speed = speed * -1;
  }
  
  if (y > height || y<0){
   speedY *= -1; // speed = speed * -1;
  }
}

 

Leave a Reply