Loading...
Logo
Processing Forum
I need to move a rectangle by pressing a key, but i need it to happen twice using the same key.

So i say use something like:

void keyPressed(){
      if (key == '  '){
            rect(pos_x, pos_y--, rect_width, rect_height); 
}

How can i call this more than once using the same key?

Replies(6)

The code is called each time the key is pressed. So I don't see what is the problem, exactly.
OK i see I can accept from the same key more than once. What I really meant was how can I get an event to happen twice if it uses the same variables.

void keyPressed(){
      if (key == '  '){
            rect(pos_x, pos_y--, rect_width, rect_height); 
}

Here I'm using the space key to move a rect up the screen, but what I want to happen is to move another rect the same way when I press space again. Do I have to use seperate values to do this (ie. pos_x for the first rect, pos_x2 for the second) or is there an easier way?

Yes, you have to have separate values, if their positions are independent. If the number of rect grows, you can use an array.
I am having this same issue myself what I'd like to do is have it so once the 'm' key is pressed = something happens, once the 'm' key is pressed a second time = something else happens
If you want to something really fancy such as ordered state transitions it might be worth looking at building a state machine see example http://www.javacodegeeks.com/2011/07/java-secret-using-enum-to-build-state.html . Unfortunately it is not very processing ide friendly (you will need to create the enums in *.java files instead of *.pde files).
Have another variable keep track of the number of times the 'm' key is pressed and use that variable to determine what happens e.g.

Copy code
  1. int m_count = 0;

  2. void keyPressed(){
  3.   if (key == 'm '){
  4.       m_count++;
  5.       if(m_count == 1){
  6.           rect(pos_x, pos_y--, rect_width, rect_height);
  7.       }
  8.       else if(m_count == 2){
  9.            // do something different
  10.       }
  11.       else {      // for all values > 2
  12.             // do something else
  13.       }
  14.    }
  15. }
Changing the basic logic will enable you to flip between actions or repeat a series of actions for the same key.