2022-06-05
P455 Example 20-2. Doorbell
这个例子中,当鼠标点击圆形时,变色并播放门铃声音。
要点:
- 判断鼠标位置是否在圆形内。使用所设计的contains()函数,求与圆心的距离。
- 播放门铃的问题处理。如:当按过一次,且播放门铃声音还未结束前,再按怎么办? 会中断当前的播放! 为避免这样的情况,提供了相应的方法。
in this program,once we press mouse, dingdong will be played.
we want another effect: if last play did't end, dingdong will only play continuously, and the press-mouse operation will not terminate the play. at this time, one of the methods can be: ask if dingdong is playing? if not, play it, if yes, do nothing. that is :
if (!dingdong.isPlaying()) {
dingdong.play();
}
the whole program is as below:
// Import the sound library
import processing.sound.*;
// A sound file object
SoundFile dingdong;
// A doorbell object (that will trigger the sound)
Doorbell doorbell;
void setup() {
size(200, 200);
// Load the sound file
dingdong = new SoundFile(this, "dingdong.mp3");
// Create a new doorbell
doorbell = new Doorbell(width/2, height/2, 64);
}
void draw() {
background(255);
// Show the doorbell
doorbell.display(mouseX, mouseY);
}
void mousePressed() {
// If the user clicks on the doorbell, play the sound!
if (doorbell.contains(mouseX, mouseY)) {
dingdong.play();
}
}
以下是设计的门铃类。
// A class to describe a "doorbell" (really a button)
class Doorbell {
// Location and size
float x;
float y;
float r;
// Create the doorbell
Doorbell(float x_, float y_, float r_) {
x = x_;
y = y_;
r = r_;
}
// Is a point inside the doorbell? (used for mouse rollover, etc.)
boolean contains(float mx, float my) {
if (dist(mx, my, x, y) < r) {
return true;
} else {
return false;
}
}
// Show the doorbell (hardcoded colors, could be improved)
void display(float mx, float my) {
if (contains(mx, my)) {
fill(100);
} else {
fill(175);
}
stroke(0);
strokeWeight(4);
ellipse(x, y, r, r);
}
}
网友评论