问题描述
请原谅我的无知,但我遇到了一个问题,尽管这个想法很简单,但对我目前在使用 Processing 编程方面的知识来说是个挑战.你看,我需要每 10 秒向变量添加 1 个单位.这是代码:
Excuse my ignorance, but I ran into a problem that turned out to be challenging for my current knowledge in programming with Processing, even though the idea is quite simple. You see, I need to add 1 unit to a variable every 10 seconds. This is the code:
int i = 0;
void setup()
{
frameRate(60);
}
void draw()
{
int time = (millis() % 10000) / 1000;
if (time == 9)
{
i++;
} else {}
System.out.println("-------------------------------\n" +
"Timer: " + time + "\n"
+ "Adding 1 every 10 seconds: : " + i + "\n"
+ "-------------------------------");
}
问题是因为 draw()
每秒循环 60 次,一旦 time
达到 9 秒,它就会使 if
语句执行 60 次,它结束每 10 秒向 i
添加 60,我只需要添加 1.
The problem is that because draw()
loops 60 times per second, as soon as time
reaches 9 the second it last makes the if
statement to be executed 60 times and it ends adding 60 to i
every 10 seconds and I just need to be adding 1.
我尝试应用某种算法来减去不必要的数字,就像这样:
I tried to apply some kind of algorithm that subtracts the unnecessary numbers as they increase like so:
int i = 1;
int toSubstract = 0; //Variable for algorithm
void setup()
{
frameRate(60);
}
void draw()
{
int time = (millis() % 10000) / 1000;
if (time == 9)
{
i++;
algToSubstract();
} else {}
System.out.println("-------------------------------\n" +
"Timer: " + time + "\n"
+ "Adding 1 every 10 seconds: : " + i + "\n"
+ "-------------------------------");
}
void algToSubstract() //<--- This is the algorithm
{
i = i - toSubstract;
toSubstract++;
if (toSubstract > 59)
{
toSubstract = 0;
} else {}
}
...但我无法让它工作.这个想法是这样的:
...but I couldn't make it work. The idea was something like this:
time
达到 9,if
语句执行,i
= 1 and toSubstract
= 0.
time
reaches 9, if
statement executes, i
= 1 and toSubstract
= 0.
i
增加 1 所以 i
= 2.
i
increases 1 so i
= 2.
i = i - toSusbract
(i
= 2 - 0 所以 i
= 2).
i = i - toSusbract
(i
= 2 - 0 so i
= 2).
toSusbract
增加 1,所以 toSusbract
= 1.
toSusbract
increases 1 so toSusbract
= 1.
i
增加 1 所以 i
= 3.
i
increases 1 so i
= 3.
i = i - toSusbract
(i
= 3 - 1 所以 i
= 2).
i = i - toSusbract
(i
= 3 - 1 so i
= 2).
toSusbract
增加 1 所以 toSusbract
= 2.
toSusbract
increases 1 so toSusbract
= 2.
...过程继续...
toSubstract
大于 59,因此重新启动为 0.
toSubstract
gets bigger than 59 so it is restarted to 0.
time
不再是 9.
推荐答案
Ringo 有一个非常好的解决方案.
Ringo has a solution that's perfectly fine.
另一种可以轻松做到这一点的方法是:
Another way you can do this easily is:
bool addOnce = false;
void draw()
{
int time = (millis() % 10000) / 1000;
if (time == 9)
{
if(!addOnce) {
addOnce = true;
i++;
}
} else { addOnce = false; }
}
只要time == 9
,我们只会通过一次if(!addOnce)
.
As long as time == 9
, we'll only get through if(!addOnce)
one time.
更改后,我们重置标志.
After it changes, we reset the flag.
这篇关于如何在Processing中每10秒向变量添加+1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!