问题描述
问题
我注意到 draw()
循环被事件阐述中断了。
在以下示例中,圆形动画将在鼠标单击时停止,直到 elaborating_function()
结束。
void setup(){
size(800,600);
background(#818B95);
frameRate(30);
}
void draw(){
background(#818B95);
//simple animation
fill(0,116,217);
circle(circle_x,200,50);
circle_x += animation_speed;
if(circle_x>800){ circle_x = 0; }
}
void mouseClicked() {
elaborating_function();
}
void elaborating_function(){
println("elaboration start");
delay(1000);
println("elaboration end");
}
当然,在不停止动画的情况下运行精化的简单解决方案可能是thread("elaborating_function");
但我的问题是:是否可以将绘制周期运行到一个独立的线程中?
解决方案
我找到了一种可能的解决方案来反转我的问题并创建一个与 draw
并行的“独立循环”。在这个周期内可以运行任何函数,它不会干扰绘制执行。用户触发的每个事件只需要设置一个特定的变量即可在周期内激活(一次或多次)功能。
int circle_x = 0;
int animation_speed = 5;
boolean call_elaborating_function = false;
void setup(){
size(800,600);
background(#818B95);
frameRate(30);
IndependentCycle independentCycle = new IndependentCycle();
independentCycle.setFrequency(1);
new Thread(independentCycle).start();
}
void draw(){
background(#818B95);
//simple animation
fill(0,50);
circle_x += animation_speed;
if(circle_x>800){ circle_x = 0; }
}
public class IndependentCycle implements Runnable{
private int frequency; //execution per seconds
public IndependentCycle(){
frequency = 0;
}
public void setFrequency(int frequency){
this.frequency = 1000/frequency;
println(this.frequency);
}
public void run(){
while(true){
print(".");
delay(this.frequency);
//DO STUFF HERE
//WITH IF EVENT == ture IN ORDER TO RUN JUST ONCE !!
if(call_elaborating_function){
call_elaborating_function = false;
elaborating_function();
}
}
}
}
void mouseClicked() {
call_elaborating_function = true;
}
void elaborating_function(){
println("elaboration start");
delay(1000);
println("elaboration end");
}
解决方法
据我所知,Processing 有它自己的 AnimationThread。
您提议的线程 elaborating_function()
解决方案很棒。
如果您需要更多控制,您可以拥有一个 implements Runnable
的基本类。当这个线程并行运行时,Processing 的主动画线程应该可以很好地并行运行而不会暂停渲染。
这个选项听起来比试图弄乱 Processing 的 AnimationThread
简单得多,而且可能不得不处理意外行为。
您尝试实现的实际目标是什么?