2011-06-20 16 views
0

私は次のコードを正しく取得できないようです。処理のON/OFFボタン

これは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が真の場合にのみ四角形を描画するように塗りを変更します。

スケッチのどこかをクリックすると、関数がProcessingによって呼び出されます。これは、squareVisible変数をトグルします。

mouseMoved()機能は、クリックしないでマウスを動かすと処理されます。これは、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

チャームのように働いてくれてありがとう! –

関連する問題