For this week’s assignment, I combined our in-class and homework assignment. As you can see, whenever I moved the keys, the box would move around the screen and, at the same time, it would expand and contract while changing colors. [Sent you a video of it]
- In order to do this, I first had to establish the variables that we would use before void setup. So, you can see that I defined “x,y,c” which related to the size and placement of the rectangle and also told Processing that we would be incorporating speed and an expanding/contracting element with the boolean function.
- The next step was to set the parameters of our sketch: the size of the screen was 600 units by 600 units, “x and y” told us where the rectangle is on the screen and c is the initial size of the rectangle.
- In void draw (), this function allowed us to run the lines of code in a loop. The first thing we established was we wanted the border of the rectangle to change colors randomly, so we used the float function in order to do this. Also, within the draw function, we wanted to tell processing that the rectangle should contract and expand, so we used an “if else” statement and the symbols “–” and “++” to do this. This part also relates with the part of code because void setup(), because the boolean statement is where we established what statement will be true or false; You have to do this because in order for the rectangle to expand and contract, processing needs to know what to do when the statement is true, and if is it not, have a condition for that as well.
- Lastly, in order to make the rectangle move around the screen, we used the keyPressed() code. As you can see, in order to make the box go up, for example, I connected the keyboard upper key with going up, hence keyCode=UP, and then in order to make the box itself go up, I used the syntax “y-speed”.
CODE
int x;
int y;
int c;
int Speed;
boolean rectIsShrinking = false;
void setup (){
size(600,600);
x = width/2;
y= height/2;
c= 100;
Speed = 15;
}
void draw() { // draw() loops forever, until stopped
background(0);
float r= random(255);
float g= random(255);
float b= random(255);
stroke(r,g,b); //random color of border
strokeWeight(5); //width of border
noFill();//no color inside of rect
rect(x,y,c,c); //size of rect and position
if (rectIsShrinking) c–;
else c++ ;
if (c == 0 || c == 150) rectIsShrinking = !rectIsShrinking;
}
void keyPressed() {
if (keyCode==UP) {
y= y-Speed;
}
if (keyCode==DOWN){
y= y+Speed;
}
if(keyCode==LEFT){
x= x+Speed;
}
if(keyCode==RIGHT){
x=x-Speed;
}
}