2011-06-20 60 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

工作就像一個魅力,感謝您的幫助! –