xxxxxxxxxx
126
let img;
let song;
function preload() {
img = loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Speaker_Icon.svg/500px-Speaker_Icon.svg.png');
song = loadSound('Bongo_Madness.mp3')
}
let volumeSlider = {
pos: {x:0, y:0},
radius: 12,
};
let sticking = false;
let avoid_radius = 20;
let knob_v, mouse_v;
function setup() {
createCanvas(400, 400);
volumeSlider.pos = {x:width-width/3, y:height/2};
image(img, 0, 0);
song.loop()
}
function mouseOver(radius) {
return (mouseX > volumeSlider.pos.x - radius
&& mouseX < volumeSlider.pos.x + radius
&& mouseY > volumeSlider.pos.y - radius
&& mouseY < volumeSlider.pos.y + radius)
}
function avoid() {
let v_mouse = createVector(mouseX, mouseY);
let v_knob = createVector(volumeSlider.pos.x, volumeSlider.pos.y);
let dist = v_mouse.dist(v_knob);
let move_dist = avoid_radius - dist;
let v3 = p5.Vector.sub(v_mouse, v_knob);
v3.setMag(move_dist+2);
volumeSlider.pos.x = volumeSlider.pos.x - v3.x;
volumeSlider.pos.y = volumeSlider.pos.y - v3.y;
}
function dist2(a, b) {
let abx2 = (a.x - b.x) * (a.x - b.x);
let aby2 = (a.y - b.y) * (a.y - b.y);
return abx2 + aby2;
}
function lineDistSquare(p, line_start, line_end) {
let denom = dist2(line_start, line_end);
if (denom === 0) return dist2(p,line_start);
let v = line_start;
let w = line_end;
let t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) /denom;
t = Math.max(0, Math.min(1, t));
return dist2(p,createVector(v.x + t * (w.x - v.x), v.y + t * (w.y -v.y)))
}
function lineDist(p, v, w) {
return Math.sqrt(lineDistSquare(p,v,w))
}
function draw() {
background(200);
noStroke();
//line
rectMode(CENTER)
fill(120)
if(sticking) {
fill(180);
stroke(1)
strokeWeight(4)
let length = 25;
line(width/2 - length, height/4 + length, width/2 + length, height/4 - length);
noStroke();
}
// disabled line
rect(width/2, height/2, 240, 6, 3);
fill(0)
if(mouseOver(avoid_radius)) {
avoid();
sticking = true;
}
let line_start = createVector(width/2 - 120, height/2);
let line_end = createVector(width/2 + 120, height/2);
let d = lineDist(createVector(volumeSlider.pos.x, volumeSlider.pos.y), line_start, line_end)
if (d < 1) {
sticking = false;
let volume = map(volumeSlider.pos.x, line_start.x, line_end.x, 0, 1)
song.amp(volume*volume);
}
else {
song.amp(1)
}
//knob
ellipseMode(CENTER)
//fill(0)
ellipse(volumeSlider.pos.x, volumeSlider.pos.y, volumeSlider.radius, volumeSlider.radius)
imageMode(CENTER)
image(img, width/2, height/4, 50, 50);
}