How to make a function execute once continually.

edited April 2018 in How To...

To elaborate, how do you make a function run once on key press, and then if the key is pressed again run again. (ex, in a top-down FPS, how to make the sprite rotate 90 degrees without it spinning out of control)

Answers

  • I suspect - because you have not posted any code that shows the problem - that the issue is that you have something like the following:

    void draw(){
      // ...
      if( keypressed && keyCode == RIGHT ){ turnRight(); }
      // ...
    }
    

    This is the wrong place for this, because it can happen several times, because the key is held down for many drawn frames.

    Instead, you want to put it in the keyPressed() function. This function only happens once per key press!

    void keyPressed(){
      // ...
      if( keyCode == RIGHT ){ turnRight(); }
      // ...
    }
    
Sign In or Register to comment.