2011-06-20 57 views
0

我似乎无法得到正确的后续代码。用于处理的开/关按钮

这是我用于Processing的基本程序。当我点击它时,我改变了方块的颜色,但是当我第二次点击时,我似乎无法让它再次改变。

它基本上是一个切换按钮,当我点击正方形而不是当我释放鼠标按钮时。我试图将它与Arduino集成,这就是为什么有端口写入。

boolean A = true; 
int x = 50; 
int y = 50; 
int w = 100; 
int h = 100; 
import processing.serial.*; 
Serial port; 
int val; 

void setup() { 
    size(200, 200); 
    noStroke(); 
    fill(255, 0, 0); 
    rect(x, y, w, h); 
    port = new Serial(this, 9600); 
} 

void draw() { 
    background(255); 
    if ((A) && (mousePressed) && ((mouseX > x) && (mouseX < x + w) && 
     (mouseY > y) && (mouseY < y + h))) { // If mouse is pressed, 

     fill(40, 80, 90); 
     A = !A;// change color and 
     port.write("H"); // Send an H to indicate mouse is over square. 
    } 
    rect(50, 50, 100, 100); // Draw a square. 
} 

回答

1

下面是一些应该做你想做的示例代码。需要注意的几点:

draw()函数只能用于实际绘制草图,其他代码应该位于其他地方。它被称为连续循环来重画屏幕,所以任何额外的代码都会减慢甚至阻止重画,这是不可取的。

您在A变量的正确轨道上。我已将其重命名为squareVisible。它是一个布尔变量,表示是否绘制正方形。 draw()函数检查它的状态,如果squareVisible为真,则更改填充以仅绘制方块。

当您在草图中单击某处时,mousePressed()函数被Processing调用。它正在切换squareVisible变量。

mouseMoved()函数被Processing调用,当你移动鼠标而不点击时,发送串口输出比draw()函数更好。

boolean squareVisible = true; 
int x = 50; 
int y = 50; 
int w = 100; 
int h = 100; 
import processing.serial.*; 
Serial port; 
int val; 

void setup() { 
    size(200, 200); 
    noStroke(); 
    fill(255, 0, 0); 
    rect(x, y, w, h); 

    port = new Serial(this, 9600); 
} 

void draw() { 
    background(255); 
    if (squareVisible) { 
     fill(40, 80, 90); 
    } else { 
     fill(255, 0, 0); 
    } 
    rect(x, y, w, h); // Draw a square 
} 


void mousePressed() { 
    if (((mouseX > x) && (mouseX < x + w) && 
      (mouseY > y) && (mouseY < y + h))) { 
     // if mouse clicked inside square 
     squareVisible = !squareVisible; // toggle square visibility 
    } 
} 

void mouseMoved() { 
    if (((mouseX > x) && (mouseX < x + w) && 
      (mouseY > y) && (mouseY < y + h))) { 
     port.write("H");     // send an H to indicate mouse is over square 
    } 
} 
+0

工作就像一个魅力,感谢您的帮助! –