Loading...
Logo
Processing Forum
Hi,
 
Is it possible to use keyPressed (and then key ==) and get what happens to stay on the screen? For example:
 
  if (keyPressed)
    {
      if (key == 'o')
      {
        image(img4,x,mouseY);
        x--;
      }
 
Can I get the image to stay on the screen and to keep moving?

Replies(2)

The variable "key" always holds the last key that has been pressed. Example:
Copy code
  1. void setup(){}

    void draw(){
    if(key == 'o')
      background(255, 0, 0);
    else
      background(0, 0, 0);
    }
If you want to use other keys as well, you would have to store use a variabel to store, that a certain key has already been pressed. Here is an example where 'o' toggles the background-color:
Copy code
  1. boolean oPressed;

    void setup(){}

    void draw(){
    if(oPressed)
      background(255, 0, 0);
    else
      background(0, 0, 0);
    }

    void keyPressed(){
      if(key == 'o')
        oPressed = !oPressed;
    }

Ah! Mere seconds!

Try creating a global boolean, setting that to true, and then checking for that in draw():

Copy code
  1. boolean imageVisible; //The variable

  2. void setup() {
  3.   size(400, 400);
  4.   //Load image and do other stuff
  5. }

  6. void draw() {
  7.   if(imageVisible) { //Check the variable
  8.     image(img4, x, mouseY);
         x --;
  9.   }
  10. }

  11. void keyPressed() {
  12.   if(key == 'o') {
  13.     imageVisible = true;
  14.   }
  15. }