【发布时间】:2021-06-02 13:58:24
【问题描述】:
问题
我正在尝试在 Processing 中创建一个简单的对象“汽车”动画。 我的代码是:
Car car;
void setup(){
size(800, 600);
background(#818B95);
frameRate(30);
car = new Car(10,10);
}
void draw(){
//refresh background
background(#818B95);
print("-");
car.drawCar();
}
void mouseClicked() {
car.run();
}
public class Car implements Runnable{
private int pos_x, pos_y;
public Car(int pos_x, int pos_y){
this.pos_x = pos_x;
this.pos_y = pos_y;
}
public void drawCar(){
rect(pos_x,pos_y,10,10);
}
public void run(){
while(true){
pos_x += 10;
print("*");
delay(200);
}
}
}
我希望在单击鼠标按钮时看到汽车/矩形向右移动,但没有任何反应。
我添加了两个 print 以查看 draw 方法和我的 car.run 是否并行执行,显示一些 * 和 - 交替打印。
我看到的是- 的序列,直到我单击然后才打印*。
是否有可能启动一个新的对象线程会停止主绘制周期?
解决方案
这只是建议的解决方案(Mady Daby)的变体,不使用线程。
Car car;
void setup(){
size(800, 600);
background(#818B95);
frameRate(30);
car = new Car(10,10);
}
void draw(){
//refresh background
background(#818B95);
print("-");
car.drawCar();
}
void mouseClicked() {
car.moving = true;
}
public class Car{
private int pos_x, pos_y;
boolean moving = false;
public Car(int pos_x, int pos_y){
this.pos_x = pos_x;
this.pos_y = pos_y;
}
public void drawCar(){
rect(pos_x,pos_y,10,10);
//animation
if(moving){
pos_x += 10;
print("*");
}
}
}
【问题讨论】:
-
程序正在进入一个无限循环,其中
pos_x不断增加10