按钮在处理正弦波项目时不工作

问题描述:

我正在创建一个正弦波,我希望可以通过鼠标调整振幅和频率,所以我制作了一个可以打开和关闭此按钮的按钮。它似乎没有工作。 //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; 
      } 

     } 
    } 
} 

你真的需要进入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

非常感谢! –