2017-07-02 71 views
0

我正在創建一個正弦波,我希望可以通過鼠標調整振幅和頻率,所以我製作了一個可以打開和關閉此按鈕的按鈕。它似乎沒有工作。 //Button Script部分是定義按鈕的地方,它應該可以工作,但是當我在運行它時在框中單擊時,即使我已滿足if中的所有條件,它也不會執行任何操作。按鈕在處理正弦波項目時不工作

void setup(){ size(1600,900); }

//Define variables. 
float amp = 0.0; 
float freq = 0; 
int totalwavelength = 50; 
int mouse = 0; 


void draw(){ 
    background(0); 
    freq = 0; 

    while (freq < totalwavelength) { 
     //When button is not pressed, run this script: 
     if (mouse == 0) { 
      fill(255); 
      ellipse(freq * 50 + 20, sin(amp) * 100 + 450, 20, 20); 
      freq += 1; 
      amp += 0.5; 

      //Create Button 
      fill(255); 
      rect(800, 800, 200, 100); 

      //Mouse Coordinates 
      fill(255, 0, 0); 
      text("X=" + mouseX, mouseX, mouseY - 10); 
      text("Y=" + mouseY, mouseX, mouseY); 

      //Button script 
      if (mouseX >700 && mouseX < 900 && mouseY >750 && mouseY < 850 && mousePressed == true && mouse == 0) { 
       mouse = 1; 
      } 

      if (mouseX >700 && mouseX < 900 && mouseY >750 && mouseY < 850 && mousePressed == true && mouse == 1) { 
       mouse = 0; 
      } 
     } 


     //When button pressed run this script: 
     if (mouse == 1) { 
      fill(255); 
      ellipse(freq * 50 + 20, sin(amp) * 100 + 450, 20, 20); 
      freq += mouseX; 
      amp += mouseY; 

      //Create Button 
      fill(255); 
      rect(800, 800, 200, 100); 

      //Button script 
      if (mouseX >700 && mouseX < 900 && mouseY >750 && mouseY < 850 && 
     mousePressed == true && mouse == 0) { 
       mouse = 1; 
      } 

      if (mouseX >700 && mouseX < 900 && mouseY >750 && mouseY < 850 && 
       mousePressed == true && mouse == 1){ 
       mouse = 0; 
      } 

     } 
    } 
} 

回答

1

你真的需要進入debugging程序的習慣。將打印語句添加到您的代碼中,以確定它正在做什麼。例如,在每個if語句內以及每當更改mouse變量時都要添加一條打印語句。

您會發現,無論何時將mouse更改爲1,您都會立即在下一步將其更改回0。這就是發生在這裏:

if (mouseX >700 && mouseX < 900 && mouseY >750 && mouseY < 850 && 
    mousePressed == true && mouse == 0) { 
    mouse = 1; 
    println("change mouse to 1 1"); 
} 
if (mouseX >700 && mouseX < 900 && mouseY >750 && mouseY < 850 && mousePressed == true && mouse == 1) { 
    mouse = 0; 
    println("change mouseto 0 1"); 
} 

首先if語句改變mouse1,然後第二if語句檢查是否mouse1它變爲0

我不完全確定你想要用這個mouse變量做什麼,但是你還需要養成breaking your problem down into smaller pieces的習慣,並且一次只針對這些問題。換句話說,你需要隔離你的問題:當你按下一個按鈕時,得到一個草圖工作,只是向控制檯輸出一些東西。如果您遇到問題,請在新的問題帖子中發帖MCVE,我們會從那裏開始。祝你好運。

+0

非常感謝! –