Button
Button(Topics->GUI->Button)
画面内の図形でボタンを作るサンプルです。
マウスを図形の上に持ってくるとグレーになり、黒い四角をクリックすると背景が黒に、白い円をクリックすると背景が白になります。
/**
* Button.
*
* Click on one of the colored squares in the
* center of the image to change the color of
* the background.
*/
int rectX, rectY; // Position of square button
int circleX, circleY; // Position of circle button
int rectSize = 50; // Diameter of rect
int circleSize = 53; // Diameter of circle
color rectColor, circleColor, baseColor;
color rectHighlight, circleHighlight;
color currentColor;
boolean rectOver = false;
boolean circleOver = false;
void setup()
{
size(200, 200);
smooth();
rectColor = color(0);
rectHighlight = color(51);
circleColor = color(255);
circleHighlight = color(204);
baseColor = color(102);
currentColor = baseColor;
circleX = width/2+circleSize/2+10;
circleY = height/2;
rectX = width/2-rectSize-10;
rectY = height/2-rectSize/2;
ellipseMode(CENTER);
}
void draw()
{
update(mouseX, mouseY); //自前の更新関数update()を呼んでいます
background(currentColor);
if(rectOver) {
fill(rectHighlight);
} else {
fill(rectColor);
}
stroke(255);
rect(rectX, rectY, rectSize, rectSize);
if(circleOver) {
fill(circleHighlight);
} else {
fill(circleColor);
}
stroke(0);
ellipse(circleX, circleY, circleSize, circleSize);
}
//マウス位置から当たり判定を更新する関数
void update(int x, int y)
{
if( overCircle(circleX, circleY, circleSize) ) { //ここでさらに判定関数を呼び、boolを変更しています
circleOver = true; //円の上にマウスがいるとtrue(真)
rectOver = false;
} else if ( overRect(rectX, rectY, rectSize, rectSize) ) { //円の上にいないなら、四角の上?
rectOver = true; //四角の上にマウスがいるとtrue(真)
circleOver = false;
} else {
circleOver = rectOver = false; //どちらでもないなら、どちらもfalse(偽)
}
}
//マウスのボタンが押されたときの処理。これは予約された名前の関数です。
void mousePressed()
{
if(circleOver) {
currentColor = circleColor; //円の上なら背景を円の色に
}
if(rectOver) {
currentColor = rectColor; //四角の上なら背景を四角の色に
}
}
//四角の判定関数。与えられた四角の座標と幅・高さから現在のマウスのXYが領域内ならtrueそれ以外ならfalseを返します。
boolean overRect(int x, int y, int width, int height)
{
if (mouseX >= x && mouseX <= x+width &&
mouseY >= y && mouseY <= y+height) {
return true;
} else {
return false;
}
}
//円の判定関数。円の座標と直径を与えると、現在のマウスのXYが円の内側にいるかどうかを判定します。
boolean overCircle(int x, int y, int diameter)
{
float disX = x - mouseX;
float disY = y - mouseY;
if(sqrt(sq(disX) + sq(disY)) < diameter/2 ) { // ( X * X + Y * Y )が(半径*半径)よりも小さければ内側です。dist()でもいいかも。
return true;
} else {
return false;
}
}