We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi, 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
Answers
@brianna0811 -- re:
This code says:
Instead:
This code says:
Be careful not to reset lastTime except inside your loop.
@jeremydouglass
Here's what i did:
However it only displays the random candy once after 5 seconds and doesn't do it EVERY 5 seconds. Is there something I'm missing that's preventing it from displaying every 5 secs?
Your "do this" step should not be to show the random candy, but to pick a new random candy.
@brianna0811 -- No way to know without seeing more of your code.
This sketch flashes a rectangle every 5 seconds.
Compare that to this, which constantly shows the rectangle but picks a new color every five seconds:
this really should be a FAQ by now. (ditto collision detection and a dozen other things)
and there are libraries that do exactly this. why does nobody use them?
it's already there:
https://forum.processing.org/two/discussion/8084/how-do-i-display-a-message-for-a-few-seconds