处理-怎么写; "On mouse click in region"。点击按钮的效果

Processing- how to write; "On mouse click in region". For effect of clicking a button

我想知道为什么这段代码不能按预期工作。

void mousePressed() {

    if (mouseX > width-50 && mouseX < width && mouseY > height-50 && mouseY < height)
    { 
        img = loadImage("doraemon.png");
        image(img, 0, 0, width, height);
    }

我想要这样当我点击一张显示 'next' 的图片时,我可以在背景上显示不同的图片,如果再次点击,显示另一张背景图片等等。

if (mouseX > width-50 && mouseX < width && mouseY > height-50 && mouseY < height)

^此代码片段说明了按钮 'next' 的位置。 当我 运行 这段代码时,我将鼠标悬停在条件上时得到了一张图片,但我希望在按下按钮后显示图片。

有人知道怎么写吗?

我需要类似的东西

 if (mousePressed == condition)
     { 
      then change image
     }

请帮忙。我真的很感激!

您正试图将所有逻辑塞进 mousePressed() 函数中。相反,您需要在 mousePressed() 函数和 draw() 函数之间拆分您的逻辑。使用变量来跟踪应该绘制的内容。在 mousePressed() 函数中调整这些变量。使用这些变量来确定要在 draw() 函数中绘制的内容。

一个简单的示例可能如下所示:

boolean showButton1 = true;

void setup() {
  size(200, 200);
}

void mousePressed() {
  if (mouseX < 100 && mouseY < 100) {
    //button 1 was just clicked, show button 2 instead
    showButton1 = false;
  } else if (mouseX > 100 && mouseY > 100) {
    //button 2 was just clicked, show button 1 instead
    showButton1 = true;
  }
}

void draw() {

  background(0);

  if (showButton1) { //draw the first button
    fill(255, 0, 0);
    rect(0, 0, 100, 100);
  } else { //draw the second button
    fill(0, 255, 0);
    rect(100, 100, 100, 100);
  }
}

此外,您不应从 mousePressed()draw() 函数中调用 loadImage()。相反,从 setup() 函数加载图像,并将它们存储在稍后可以使用的变量中。

您发布的代码片段中有几处看起来有点不对劲:

if (mouseX > width-50 && mouseX < width && mouseY > height-50 && mouseY < height)
    { 
        img = loadImage("doraemon.png");
        image(img, 0, 0, width, height);
    }

一个是次要的:每次鼠标单击草图右下角的 50x50 框时,您都会加载图像。您应该在设置中加载一次图像,然后在需要时通过草图重新使用它。

第二个可能是您的主要问题:如果按下鼠标(在草图的右下角),您只会调用 image() 一次。这意味着如果你在 draw() 函数中有一个 background() 调用或其他绘图调用,你几乎不会注意到正在绘制机器猫图像(因为它 erased/painted 更频繁)

这是我在代码中的意思:

PImage img;//reference to the image
boolean imgDraw;//keep track if the image should be drawn or not

void setup(){
  //load the image only once, at setup
  img = loadImage("doraemon.png");
  size(img.width,img.height);
}
void draw(){
  background(0);//clear each frame
  if(imgDraw){//draw the image only if it needs to be drawn
    image(img, 0, 0, width, height);
  }
}
void mousePressed() {
    //check if the cursor is at the bottom right, and if so, set the image draw flag to true
    if (mouseX > width-50 && mouseX < width && mouseY > height-50 && mouseY < height)
    { 

        imgDraw = true;
    }
    else
    {
      imgDraw = false;
    }  
}

实际上,因为 imgDraw 是一个布尔值,而您有一个检查坐标的布尔表达式,您可以将它折叠成一个语句。

void mousePressed(){
  imgDraw = (mouseX > width-50 && mouseX < width && mouseY > height-50 && mouseY < height); 
}

看起来不错,但如果代码难以阅读,就不值得了。 可读代码更好。