Example 4.2: Interactivity via the keyboard
Here's another example of user input that involves both the mouse and the keyboard. This program draws a line on the screen that follows the mouse if you also hold down the "r" key or the "k" key. See the demonstration of pmouseX and pmouseY and also the variable keyPressed.
/* Move your mouse across the screen while holding down "r" or "k" key to draw a line that follows the mouse */ // set the background color color bg = color(220,220,200); // define a shade of red that I like rd = color(242,42,48); void setup() { size(200, 200); background(bg); } void draw() { strokeWeight(2); //keyPressed is a boolean variable. //That means it can either be "true" or false" //Capitals are different from lowercase. //I wrote the if test this way so in case the //user has caps lock on, it will still work if ((keyPressed == true) && (key == 'r' || key == 'R')) { stroke(rd); line(mouseX,mouseY,pmouseX,pmouseY); } if ((keyPressed == true) && (key == 'k' || key == 'K')) { stroke(0); line(mouseX,mouseY,pmouseX,pmouseY); } }
Quiz Yourself!
Example 4.3 More with the keyboard
Here's a program that combines keyboard input with moving a shape across the screen, so we are reviewing bits of Lesson 3 while adding Lesson 4 skills here:
//move a shape around the screen according to keyboard inputs int x=100; int y=100; void setup(){ size(200,200); pixelDensity(2); stroke(0); ellipse(x,y,10,10); } void draw(){ //stroke(0); //ellipse(x,y,10,10); if ((keyPressed == true) && (key == 'u' || key == 'U')){ stroke(255,0,0); y--; } else if (keyPressed == true && (key == 'd' || key =='D')){ stroke(0,255,0); y++; } else if (keyPressed == true && (key == 'r' || key == 'R')){ stroke(0,0,255); x++; } else if (keyPressed == true && (key == 'l' || key == 'L')){ stroke(255,255,0); x--; } else { ellipse(x,y,10,10); } }
The beginning position is just a black circle drawn to the middle of the display window. It doesn't do anything unless you type the u, d, l, or r keys, in which case the circle jumps up, down, left, or right, and changes color. If no key is being pressed, the circle just sits still in its most recent position with its most recent color.
Exercise
4.6 Make a virtual Etch-a-Sketch in which you use the keyboard to draw a black line on a grey background.