Using keyPressed() for two commands
in
Programming Questions
•
1 year ago
Howdy all,
As a programming exercise, I'm attempting to use a key (in this case, a and b) to turn an animation on and off. What I want the program to do is not draw the rectangle when I press a until I press a again, and similarly for b and the ellipse. I got this to by creating separate on/off switches (a to turn off, A to turn back on, and similarly with b), but I'd really like to only have to use one letter.
Any advice would be appreciated, as this seems relatively easy yet I'm new to programming.
Code is below, and thanks for any help you can give!
- float r,e;
- boolean flagA, flagB;
- void setup() {
- size(300, 300);
- background(255);
- noStroke();
- smooth();
- frameRate(60);
- flagA=true;
- flagB=true;
- }
- void draw() {
- if (abs(r-e)<20) {
- background(255,0,0);
- //println("Woah there, y'all gettin' mighty close in x coords.");
- } else {
- background(255);
- }
- rectMode(CORNER);
- ellipseMode(CORNER);
- fill(0);
- if (flagA=true){
- rect(r, 100, 40, 40);
- r=width/2-20+width*cos(frameCount*PI/(12*20))*sin(frameCount*PI/(12*20));
- }
- if (flagB=true){
- ellipse(e, 200, 40, 40);
- e=width/2-20+width/2*sin(frameCount*PI/(12*20));
- }
- }
- void keyPressed() {
- if (key=='a'&&flagA==true) {
- flagA=false;
- r=500;
- }
- if (key=='a'&&flagA==false) {
- flagA=true;
- }
- if (key=='b'&&flagB==true) {
- flagB=false;
- e=-100;
- }
- if (key=='b'&&flagB==false) {
- flagB=true;
- }
- println(key);
- }
1