If statement 处理-如何写&引用;在“区域”中单击鼠标;。单击按钮的效果
我想知道为什么这个代码不能按预期工作If statement 处理-如何写&引用;在“区域”中单击鼠标;。单击按钮的效果,if-statement,button,processing,If Statement,Button,Processing,我想知道为什么这个代码不能按预期工作 void mousePressed() { if (mouseX > width-50 && mouseX < width && mouseY > height-50 && mouseY < height) { img = loadImage("doraemon.png"); image(img, 0, 0, width, height
void mousePressed() {
if (mouseX > width-50 && mouseX < width && mouseY > height-50 && mouseY < height)
{
img = loadImage("doraemon.png");
image(img, 0, 0, width, height);
}
请帮忙。我真的很感激 您试图将所有逻辑塞进
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);
}
}
布尔showButton1=true;
无效设置(){
大小(200200);
}
void mousePressed(){
if(mouseX<100&&mouseY<100){
//按钮1刚刚单击,显示按钮2
showButton1=假;
}否则如果(鼠标X>100&&mouseY>100){
//按钮2刚刚单击,显示按钮1
showButton1=真;
}
}
作废提款(){
背景(0);
如果(showButton1){//绘制第一个按钮
填充(255,0,0);
rect(0,0,100,100);
}否则{//绘制第二个按钮
填充(0,255,0);
rect(100100100100);
}
}
另外,您不应该从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);
}
实际上,因为imgDraw是一个布尔表达式,并且有一个检查坐标的布尔表达式,所以可以将它折叠为一条语句
void mousePressed(){
imgDraw = (mouseX > width-50 && mouseX < width && mouseY > height-50 && mouseY < height);
}
void mousePressed(){
imgDraw=(mouseX>width-50&&mouseXheight-50&&mouseY
看起来不错,但是如果代码更难阅读,那就不值得了。
可读代码更好。非常感谢!这解决了我很多问题。你非常详细的解释真的很有帮助!这正是我想要的。非常感谢你!
if (mouseX > width-50 && mouseX < width && mouseY > height-50 && mouseY < height)
{
img = loadImage("doraemon.png");
image(img, 0, 0, width, height);
}
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;
}
}
void mousePressed(){
imgDraw = (mouseX > width-50 && mouseX < width && mouseY > height-50 && mouseY < height);
}