run a function continuously keyPressed once

edited June 2014 in How To...

I need to build various text animations but am having trouble figuring out how to run a function continuously after only hitting a key once. In this code, I have the text moving diagonally across the screen. Currently it does this only when the key is pressed but I'd like it to run across the screen after hitting the key just once. I've tried various 'if' statements (one of which is still here in the code) but I'm assuming there is a simple way to do this that I'm not seeing.

PFont myFont;
int rad = 60;        
float xpos, ypos;        

float xspeed = 2.8;  
float yspeed = 2.2;  

int xdirection = 1;  
int ydirection = 1;

void setup() 
{
  myFont = createFont("Arial", 48);
  textFont(myFont, 72);
  size(640, 360);
  noStroke();
  frameRate(30);
  xpos = 10;
  ypos = 10;
}

void draw() {
  background(102);
  if(keyPressed){
    move();
     if(ypos<640){
      move();
    }    
    }
  }

void move() { 
  xpos = xpos + ( xspeed * xdirection );
  ypos = ypos + ( yspeed * ydirection );

  fill(0);
  text("Move", xpos, ypos);
}
Tagged:

Answers

  • Answer ✓

    Use a boolean that keeps track of whether the key has been pressed. Refer to that boolean from the draw() function.

  • Ah yes. Thank you. I had tried that but put the boolean within the initial if statement. Just separated them and it works perfectly.

Sign In or Register to comment.