我有一系列随机选择的糖果图像。有糖果掉落,我想每5秒做一个新的,我知道我必须使用millis() - 但我如何将它实现到我的程序中?我试过像这样使用millis():
int time = millis();
if (time<5*1000)
{
image(goodCandy[rand], randX, goodY, randCandyW, randCandyH);
goodY = goodY + (candySpeed * yDirCandy);
time = millis();
}
但它只出现5秒然后就消失了。 我也尝试过:
int time = millis();
if (millis() - time >= 5000)
{
image(goodCandy[rand], randX, goodY, randCandyW, randCandyH);
goodY = goodY + (candySpeed * yDirCandy);
time = millis();
}
但它没有用。
以下是简化代码:
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();
//}
}
任何想法我怎么能让millis()工作,所以我可以随机糖果每5秒下降一次? 感谢
答案 0 :(得分:0)
请尽量养成breaking your problem down into smaller pieces的习惯,并且一次只能接受这些作品。例如,你应该从一个更简单的草图开始,每5秒钟只显示一个随机圆圈。
这是一个小例子,展示了如何使用millis()
函数每隔5秒绘制一些东西:
int lastCircleTime = 0;
void draw() {
if (millis() > lastCircleTime + 5*1000) {
ellipse(random(width), random(height), 20, 20);
lastCircleTime = millis();
}
}
如果您仍然遇到问题,请发布一个MCVE,告诉您确切地停留了哪一步。请注意,不应该是整个草图。它应该是一个像这样的小例子。祝你好运。