Dare I ask about the 'delay' function!?

Hello, I am trying to complete a very simple operation. From a quick google I know that the 'delay' function is something that is to generally be avoided, but my scenario is so simple, but I don't get why it isn't working. (All within draw function)

          if (//goal event occurs)
           {
             reset();
             Score ++;
             text("goal",500,500);
             delay(2000);     
           }

As you can see, all I want is for the word 'goal' to flash up for 2s prior to the game resetting. However, running it this way(or with reset() after the delay, seems to just get it stuck displaying goal for eternity. Could anyone suggest an easy fix?

Tagged:

Answers

  • edited May 2017

    As you have already determined, the delay() function is not doing what you think it's doing. It does cause a delay, but the delay also causes draw() to stop running until the delay is up (and this is bad because your sketch looks like it locks up, since the screen freezes)!

    Instead, you should use the millis() function to determine a time that something should happen until:

    int display_until_time = -1;
    
    void setup(){
      size(400,400);
    }
    
    void draw(){
      background(0);
      if( millis() < display_until_time ){
        rect(100,100,200,200);
      }
    ellipse(mouseX,mouseY,20,20);
    }
    
    void mousePressed(){
      display_until_time = millis() + 3000; // display the thing for three seconds.
    }
    
  • Thank you for the response, while I can get that work on it's own, it doesn't seem to when I incorporate the equivalent. Could you please explain the logic? Why the initial -1. And how does the if function work, as in surely millis() will never be less than -1?

    Using my previous example, the way I tried to recreate it is by setting a P1Goal variable as -1 and then:

    if (//goal event occurs)
     {
       reset();
       Score ++;
    
       if(millis() < p1Goal)
       {
       text("goal",500,500);
       }
    
     P1Goal = millis() + 3000;      
     }
    
  • display_until_time = -1; just initializes the variable. The trick is the moyuse event as it sets the next time the event is trigger. In this casem if you generate a mousePressed, the next trigger time is timed_mousePressed + 3secs

    Kf

  • Ah okay I understand now why it isn't working. Is there a simple way to make this operate within the loop such that the 'trigger' is the fact that this goal event has occurred though??

    So the aim of the whole function is that once a goal has been scored, the positions reset, the score goes up by one, and 'Goal' is displayed for 3 seconds.

    Currently with just the text function it will just flash up for parts of a second which is sometimes not noticeable as I'm running it at 200fps to maintain smoothness.

Sign In or Register to comment.