Processing 如何在处理中创建简单的对象动画
问题 我试图在处理中创建一个简单的对象“汽车”动画。 我的代码是:Processing 如何在处理中创建简单的对象动画,processing,java-threads,Processing,Java Threads,问题 我试图在处理中创建一个简单的对象“汽车”动画。 我的代码是: Car car; void setup(){ size(800, 600); background(#818B95); frameRate(30); car = new Car(10,10); } void draw(){ //refresh background background(#818B95); print("-");
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);
}
}
}
我希望在单击鼠标按钮时看到汽车/矩形向右移动,但什么也没有发生
我添加了两个打印,以查看draw方法和my car.run是否并行执行,显示一些交替打印的*
和-
。
我看到的是一系列的-
,直到我单击,然后只打印*
启动新对象线程是否可能会停止主绘制循环
解决方案
这只是不使用线程的建议解决方案(by)的一个变体
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("*");
}
}
}
您可以通过引入一个布尔变量来跟踪汽车是否应该向右移动
移动
,然后在移动
为真时增加位置x
,从而使汽车向右移动。您还可以使用单击在移动和不移动之间切换
Car;
无效设置(){
尺寸(800600);
背景(818B95);
帧率(30);
汽车=新车(10,10);
}
void draw(){
//刷新背景
背景(818B95);
打印(“-”);
汽车。牵引车();
}
void mouseClicked(){
汽车。开关移动();
}
公共级轿车可运行{
私人内部位置x,位置y;
私有布尔移动=假;
公共汽车(内部位置x,内部位置y){
this.pos_x=pos_x;
this.pos_y=pos_y;
}
public void toggleMoving(){
移动=!移动;
}
公共无效牵引车(){
如果(移动){
这个。run();
}
rect(pos_x,pos_y,10,10);
}
公开募捐{
pos_x+=10;
打印(“*”);
延迟(200);
}
}
程序正在进入无限while循环,其中pos\u x
不断递增10
是的,谢谢。在不涉及线程的情况下也可以获得类似的结果。仅在car.draw方法中包含动画移动,并使用布尔(移动)变量将其激活。