Skip to content

Commit

Permalink
Splashfix final
Browse files Browse the repository at this point in the history
  • Loading branch information
lewdry committed Sep 14, 2024
1 parent 6d259ee commit 3708623
Showing 1 changed file with 77 additions and 58 deletions.
135 changes: 77 additions & 58 deletions bonk.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,30 +20,45 @@ function resizeCanvas() {
// Initial canvas size
resizeCanvas();

let soundsLoaded = false;

document.addEventListener('DOMContentLoaded', async (event) => {
try {
audioContext = new (window.AudioContext || window.webkitAudioContext)();

// Load all sound files
const soundFiles = ['G2.mp3', 'B2.mp3', 'D3.mp3', 'G3.mp3', 'B3.mp3', 'D4.mp3', 'G4.mp3'];
for (const file of soundFiles) {
const response = await fetch(`sounds/${file}`);
const arrayBuffer = await response.arrayBuffer();
collisionBuffers[file] = await audioContext.decodeAudioData(arrayBuffer);
console.log(`Audio file ${file} loaded successfully`);
}

// Initialize game after sounds are loaded
// Initialize game first
initGame();

// Add visibility change listener
document.addEventListener('visibilitychange', handleVisibilityChange);
// Load sounds in the background
loadSounds().then(() => {
console.log('All sounds loaded successfully');
soundsLoaded = true;
}).catch(error => {
console.error('Failed to load some sounds:', error);
});

} catch (error) {
console.error('Failed to load audio:', error);
console.error('Failed to create audio context:', error);
}
});

async function loadSounds() {
const soundFiles = ['G2.mp3', 'B2.mp3', 'D3.mp3', 'G3.mp3', 'B3.mp3', 'D4.mp3', 'G4.mp3'];
const loadPromises = soundFiles.map(async (file) => {
try {
const response = await fetch(`sounds/${file}`);
const arrayBuffer = await response.arrayBuffer();
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
collisionBuffers[file] = audioBuffer;
console.log(`Audio file ${file} loaded successfully`);
} catch (error) {
console.error(`Failed to load audio file ${file}:`, error);
}
});

await Promise.all(loadPromises);
}

class Ball {
constructor() {
this.reset();
Expand Down Expand Up @@ -167,52 +182,52 @@ class Ball {
other.dy = v2n * normalY + (other.dx * tangentX + other.dy * tangentY) * tangentY;

const minSpeed = 0;
const maxSpeed = 30;
const minVolume = 0.2; // 20% minimum volume
const thisSpeed = this.getSpeed();
const otherSpeed = other.getSpeed();
const collisionSpeed = Math.max(thisSpeed, otherSpeed);

if (collisionSpeed > minSpeed && Object.keys(collisionBuffers).length > 0) {
try {
const soundFiles = Object.keys(collisionBuffers);
const randomIndex = Math.floor(Math.random() * soundFiles.length);
const randomSoundFile = soundFiles[randomIndex];

// Create a new buffer source and connect it to the destination
const source = audioContext.createBufferSource();
source.buffer = collisionBuffers[randomSoundFile];

// Create a gain node to control the volume
const gainNode = audioContext.createGain();

// Calculate the volume based on collision speed with a minimum volume
const normalizedSpeed = (collisionSpeed - minSpeed) / (maxSpeed - minSpeed);
const volume = minVolume + (1 - minVolume) * normalizedSpeed;
const clampedVolume = Math.min(Math.max(volume, minVolume), 1);

gainNode.gain.setValueAtTime(clampedVolume, audioContext.currentTime);

// Connect the source to the gain node, then to the destination
source.connect(gainNode);
gainNode.connect(audioContext.destination);

// Start the sound immediately
source.start();

// Add the new source to the activeSources array
activeSources.push(source);

// Cull older sources
if (activeSources.length > 20) {
activeSources.shift().stop(); // Stop the oldest source and remove it
}

console.log(`Collision speed: ${collisionSpeed.toFixed(2)}, Volume: ${clampedVolume.toFixed(2)}`);
} catch (error) {
console.error("Error playing sound:", error);
}
const maxSpeed = 30;
const minVolume = 0.2; // 20% minimum volume
const thisSpeed = this.getSpeed();
const otherSpeed = other.getSpeed();
const collisionSpeed = Math.max(thisSpeed, otherSpeed);

if (collisionSpeed > minSpeed && soundsLoaded && Object.keys(collisionBuffers).length > 0) {
try {
const soundFiles = Object.keys(collisionBuffers);
const randomIndex = Math.floor(Math.random() * soundFiles.length);
const randomSoundFile = soundFiles[randomIndex];

// Create a new buffer source and connect it to the destination
const source = audioContext.createBufferSource();
source.buffer = collisionBuffers[randomSoundFile];

// Create a gain node to control the volume
const gainNode = audioContext.createGain();

// Calculate the volume based on collision speed with a minimum volume
const normalizedSpeed = (collisionSpeed - minSpeed) / (maxSpeed - minSpeed);
const volume = minVolume + (1 - minVolume) * normalizedSpeed;
const clampedVolume = Math.min(Math.max(volume, minVolume), 1);

gainNode.gain.setValueAtTime(clampedVolume, audioContext.currentTime);

// Connect the source to the gain node, then to the destination
source.connect(gainNode);
gainNode.connect(audioContext.destination);

// Start the sound immediately
source.start();

// Add the new source to the activeSources array
activeSources.push(source);

// Cull older sources
if (activeSources.length > 20) {
activeSources.shift().stop(); // Stop the oldest source and remove it
}

console.log(`Collision speed: ${collisionSpeed.toFixed(2)}, Volume: ${clampedVolume.toFixed(2)}`);
} catch (error) {
console.error("Error playing sound:", error);
}
}
} else if (this.grabbed) {
other.x = this.x + (other.radius + this.radius + separationDistance) * Math.cos(angle);
other.y = this.y + (other.radius + this.radius + separationDistance) * Math.sin(angle);
Expand Down Expand Up @@ -282,7 +297,11 @@ function initGame() {

document.addEventListener('pointerdown', dismissSplashScreen, false);

document.addEventListener('visibilitychange', handleVisibilityChange);

showSplashScreen();
gameRunning = true;
gameState.running = true;
requestAnimationFrame(gameLoop);
}

Expand Down

0 comments on commit 3708623

Please sign in to comment.