-1

I have an array of candy images which are randomly chosen. There are candies falling and I want to make a new one fall every 5 seconds, and I know I have to use millis() - but how would I implement it into my program? I tried using millis() like so:

int time = millis();
  if (time<5*1000)
  {
    image(goodCandy[rand], randX, goodY, randCandyW, randCandyH);
    goodY = goodY + (candySpeed * yDirCandy);
    time = millis();
  }

But it only appears for 5 seconds then goes away. I also tried:

 int time = millis();
  if (millis() - time >= 5000)
  {
    image(goodCandy[rand], randX, goodY, randCandyW, randCandyH);
    goodY = goodY + (candySpeed * yDirCandy);
    time = millis();
  }

But it didn't work.

Here's the simplified code:

    PImage [] goodCandy = new PImage [3];
    int candySpeed = 20;
    int yDirCandy = 1;
    int candyY = 10;
    int candyX = 200;
    int candyW = 187;
    int candyH = 121;
    int randCandyW = 100;
    int randCandyH = 100;

    int goodY = -200;

    int rand=(int) (2*Math.random()) +1;
    int randX = (int) (1500*Math.random())+20;

    void setup() {
    for (int i=0; i<goodCandy.length; i++) {
      goodCandy[i] = loadImage("goodCandy" + i + ".png");
    }

    void draw() {
    if (current=="play") {
    loadStuff();
    }
    }

    void loadStuff() {

      image(candy, candyX, candyY, candyW, candyH);  //original candy
      candyY = candyY + (candySpeed * yDirCandy);

      int time = millis();
      if (millis() - time >= 5000)
      {
        image(goodCandy[rand], randX, goodY, randCandyW, randCandyH);
        goodY = goodY + (candySpeed * yDirCandy);
        time = millis();
      }

      //for (int i=0; i<time; i++) {
      //  image(goodCandy[rand], randX, goodY, randCandyW, randCandyH);
      //  goodY = goodY + (candySpeed * yDirCandy);
      //  time = millis();
      //}
    }

Any ideas how I could make millis() work so I can have a random candy falling every 5 seconds? Thanks

Brianna
  • 107
  • 2
  • 11

1 Answers1

0

Please try to get into the habit of breaking your problem down into smaller pieces and only taking on those pieces one at a time. For example, you should probably start with a simpler sketch that just shows a random circle every 5 seconds.

Here's a small example that shows how you would use the millis() function to draw something every 5 seconds:

int lastCircleTime = 0;

void draw() {

  if (millis() > lastCircleTime + 5*1000) {
    ellipse(random(width), random(height), 20, 20); 
    lastCircleTime = millis();
  }
}

If you're still having trouble, please post a MCVE showing exactly which step you're stuck on. Note that this should not be your whole sketch. It should be a small example like this one. Good luck.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107