处理 - 如何编写; “在区域内鼠标单击”。实现按钮点击效果

5
我想知道为什么这段代码不能像预期的那样工作。
void mousePressed() {

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

我希望当我点击一个标有“下一页”的图片时,能够在背景上显示不同的图片,如果再次点击,则显示另一张背景图片,以此类推。

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

^这段代码片段说明了按钮“下一步”所在的位置。当我运行这段代码时,悬停在条件上会得到一张图片,但我希望在按下按钮后出现图片。

有人知道如何编写吗?

我需要类似于:

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

请帮忙。非常感激!

2个回答

2
你试图将所有逻辑都塞进 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() 函数中加载你的图像,并将它们存储在变量中以供后续使用。

1
这正是我正在寻找的。非常感谢! - bisuke

0

您发布的代码片段中有几个地方看起来略微不对:

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()调用或其他绘图调用,则几乎不会注意到Doraemon图像被绘制(因为它被更频繁地擦除/覆盖)

以下是我在代码中的意思:

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); 
}

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


非常感谢!这解决了我很多问题。你非常详细的解释真的帮了我很多! - bisuke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接