2016-03-04 91 views
-1

這是我在處理過程中寫的一段代碼。簡單寫入處理

{ import processing.serial.*; 
    Serial myPort; 
    // Create object from Serial class int val; 
    // Data received from the serial port 
    void setup() { size(860, 860); 
    // I know that the first port in the serial list on my mac 
    // is always my FTDI adaptor, so I open Serial.list()[0]. 
    // On Windows machines, this generally opens COM1. 
    // Open whatever port is the one you're using. String portName = Serial.list()[1]; 

    myPort = new Serial(this, portName, 9600); 

} 

void draw() { 
    background(255);  
    if ((mouseX >100)&&(mouseY>50)&&(mousePressed)) 
    { 
     // If mouse is over square,  fill(204);      
     // change color and  myPort.write('U'); 
     // send an H to indicate mouse is over square  println("U");   } rect(100, 50, 100, 100);   // UP  if ((mousePressed)&&(mouseX>50)&&(mouseY>200)) { // If mouse is over square,  fill(204); 
       // change color and  myPort.write('L');  // send an H to indicate mouse is over square  println("L");   } rect(50, 200, 100, 100);//LEFT  
    if ((mousePressed)&&(mouseX>180)&&(mouseY>200)){ // If mouse is over square,  fill(204);    
     // change color and  myPort.write('R'); 
     // send an H to indicate mouse is over square  println("R"); 
    } 
    rect(180, 200, 100, 100); 
    //RIGHT  
    if ((mousePressed)&&(mouseX>100)&&(mouseY>350)) { // If mouse is over square,  fill(204);  
     // change color and  myPort.write('B'); 
     // send an H to indicate mouse is over square  println("B"); 
    } 
    rect(100, 350, 100, 100);//BACK 
} 
} 

我想發送的輸出U,L,R,跨串行端口B每當鼠標懸停是在任何的4盒等。頂盒U,底盒D,左盒L等。但我得到的是ULD而不是D,LUL而不是L和其他各種雜亂無章的輸出。請幫忙。並且請忽略我的代碼中的評論。謝謝

+0

請以有組織和易讀的方式呈現您的代碼 –

+0

如何?對不起,我剛加入SO。 – Mahip

+0

您的代碼難以辨認。請重新格式化並從左側4個空格處開始縮進,以便在此處正確顯示。 – ThisClark

回答

0

讓我們看看你的代碼的一部分。這是第一個if語句在draw()功能:

if ((mouseX >100)&&(mouseY>50)&&(mousePressed)) 
    {  
    println("U"); 
    } 

請把這段代碼,仔細一看,並試着描述一下邏輯就行了。您檢查mouseX > 100mouseY > 50。但即使鼠標位於窗口的右下角,情況也是如此!大概你不希望當你點擊窗口右下角時按下「向上」按鈕。

您的邏輯中的這個缺陷是什麼導致多個消息被髮送。你沒有足夠的限制你的鼠標位置。您只是針對頂部左側按鈕的邊緣進行檢查。您還必須檢查右側底部按鈕的邊緣。這個if語句可能會是這個樣子:

if(mousePressed && mouseX > 100 && mouseX < 200 && mouseY > 50 && mouseY < 150){ 
    println("U"); 
} 

有自帶的編輯器處理一個Button example。只需去File>Examples,然後查找Button示例。

此外,您可能想要開始使用mouseClicked()和相關功能,而不是完成draw()功能中的所有功能。大概你不想在按下鼠標的時候每秒發送60次「U」。使用mouseClicked()將幫助您隔離單個鼠標事件。