Skip to content

Commit

Permalink
fix(helpers): fix volumeSlider logic
Browse files Browse the repository at this point in the history
  • Loading branch information
remarkablemark committed Feb 17, 2024
1 parent d947f39 commit 9bebb41
Showing 1 changed file with 28 additions and 13 deletions.
41 changes: 28 additions & 13 deletions src/helpers/volumeSlider.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
import type { AudioPlay } from 'kaboom';

/*---------------------
Current issues to fix
- Slider still works, even when cursor is away from the bar
const x = 250;
const y = 15;
const width = 100;

Possible update:
- Add mute button
- Move volume to pause screen
----------------------*/

export function volumeSlider(music: AudioPlay) {
/**
* Current issues to fix:
* - Slider still works, even when cursor is away from the bar
*
* Possible update:
* - Add mute button
* - Move volume to pause screen
*/
export function volumeSlider(music: AudioPlay, defaultVolume = 1.0) {
// Volume level label above volume slider
const percentNumberLabel = add([
text('Volume:100', {
text(getText(Math.round(defaultVolume * 100)), {
size: 12,
width: 320,
font: 'sans-serif',
Expand All @@ -21,10 +24,14 @@ export function volumeSlider(music: AudioPlay) {
]);

// Entire volume bar in grey
const volumeBar = add([rect(100, 15), pos(250, 15), color(80, 80, 80)]);
const volumeBar = add([rect(width, y), pos(x, y), color(80, 80, 80)]);

// Volume slider
const volumeSlider = add([rect(30, 15), pos(320, 15), color(0, 125, 125)]);
const volumeSlider = add([
rect(30, y),
pos(defaultVolume === 1 ? 320 : 220 + 130 * defaultVolume, y),
color(0, 125, 125),
]);

// registers if dragging is working
let isDragging = false;
Expand All @@ -37,6 +44,7 @@ export function volumeSlider(music: AudioPlay) {
offsetX = mousePos().x - volumeSlider.pos.x;
}
});

// resets drag back, otherwise, slider will indefinitely follow mouse position
onMouseRelease(() => {
isDragging = false;
Expand All @@ -50,16 +58,23 @@ export function volumeSlider(music: AudioPlay) {
volumeBar.pos.x,
volumeBar.pos.x + volumeBar.width - volumeSlider.width,
);

// Calculates slider and bar difference
const percent = Math.round(
((volumeSlider.pos.x - volumeBar.pos.x) /
(volumeBar.width - volumeSlider.width)) *
100,
);

// sets the calculation to the text label "100"
percentNumberLabel.text = `Volume:${percent}`;
percentNumberLabel.text = getText(percent);

// Changes the song volume based on the previous calc
music.volume = percent / 100;
}
});
}

function getText(percentage: number) {
return `Volume: ${percentage}`;
}

0 comments on commit 9bebb41

Please sign in to comment.