…missing in your first function (using x,y,w,h of course)
Remark
names qasd are not so brilliant, better go for
- btn1X, btn1Y,btn1W,btn1H
- btn2X, btn2Y,btn2W,btn2H
Remark
It occurred to you that both functions are virtually the same.
You know there are data types like int and String?
You can now define your own data type and teach it to processing. Call the data type Button. Now you can use the data type and say
Button btn1;
Button btn2;
part of defining the data type would also include the function itself, so the data type knows the function as its own. You can and should also include the data x,y,w,h into it.
The concept is called as you know “object oriented programming” (OOP) and the data type is called a “class”:
- The class is the cookie maker (button maker),
- the objects are the cookies (meaning the buttons, they are individual, but all derived from the same class).
See Objects / Processing.org
Chrisir
Entire Demo for OOP
Button b1, b2;
void setup() {
size(600, 600);
background(111);
textSize(30);
b1 = new Button(40, 150, 240, 80, "Play Game!");
b2 = new Button(40, 299, 240, 80, "Game Info");
}
void draw() {
background(111);
showHeader("Button Demo", "with Object Oriented Programming (OOP)" );
b1.display();
b2.display();
}
// ---------------------------------------------------------------------------------
// Inputs
void mousePressed() {
if (b1.checkMouse()) {
println ("1");
} else if (b2.checkMouse()) {
println ("2");
}
}
// ---------------------------------------------------------------------------------
// Tools / Other functions
void showHeader(String s1_, String s2_) {
// Headline
pushStyle();
fill(#FFFFFF);
textSize(30);
text (s1_, 40, 40);
// smaller text line underneath
textSize(17);
text (s2_, 40, 69);
popStyle();
}
// ================================================================
class Button {
PVector position = new PVector();
float sizeW, sizeH;
String string1;
// constructor
Button (float x_, float y_,
float sizeW_, float sizeH_,
String s1_) {
position.set(x_, y_);
sizeW = sizeW_;
sizeH = sizeH_;
string1=s1_;
}// constr
// method
void display() {
// show button
// rect
stroke(200);
//noFill();
fill(255);
if (checkMouse())
fill(255, 0, 0);
if (checkMouse()&&mousePressed)
fill(255, 0, 120);
rect(position.x, position.y,
sizeW, sizeH);
// text
fill(0);
text(string1,
position.x+13, position.y+47);
}// method
// method
boolean checkMouse() {
// returns true when inside
return
mouseX > position.x &&
mouseX < position.x + sizeW &&
mouseY > position.y &&
mouseY < position.y + sizeH;
} // method
//
}//class
//