我已经通过一个布尔值来控制点击和锁定,例如:
class Test {
//global
float x;
float y;
float w, h;
float initialY;
boolean lock = false;
//constructors
//default
Test () {
}
Test (float _x, float _y, float _w, float _h) {
x=_x;
y=_y;
initialY = y;
w=_w;
h=_h;
}
void run() {
float lowerY = height - h - initialY;
float value = map(y, initialY, lowerY, 100, 255);
color c = color(value);
fill(c);
rect(x, initialY, 4, lowerY);
fill(200);
rect(x, y, w, h);
float my = constrain(mouseY, initialY, height - h - initialY );
if (lock) y = my;
}
boolean isOver()
{
return (x+w >= mouseX) && (mouseX >= x) && (y+h >= mouseY) && (mouseY >= y);
}
}
//end of class
Test[] instances = new Test[3];
void setup() {
size(200, 600);
noStroke();
instances[0] = new Test(20, 20, 40, 20);
instances[1] = new Test(80, 20, 40, 20);
instances[2] = new Test(140, 20, 40, 20);
}
void draw() {
background(100);
for (Test t:instances)
t.run();
}
void mousePressed() {
for (Test t:instances)
{
if (t.isOver())
t.lock = true;
}
}
void mouseReleased() {
for (Test t:instances)
{
t.lock = false;
}
}