So, I have just start JS this year for my uni course (diploma), we have been tasked to build a simple game that includes arrays, images, sound, objects, etc. That is why the code may be all over the place, as we must incorporate all these parts into one.
I am aiming to make a simple pong game, with music on the main screen and also music while playing.
I have the first GUI screen music (bg-music.mp3), and the actual game music (aa-sega.mp3), the easiest method I can use is play music on setup(), but it plays the same music throughout the entire game.
I try to make my own function, or place it in the draw function, but of course the entire code in draw() runs every frame, how would I go about making the music change on clicking a rect button upon opening the screen?
cut non-important code out, only included necessary info.
I just don’t know how I could play sound without it playing over itself as fast as my CPU will go until the browser crashes.
Keep in mind I’ve been learning JS for 5 months now, still learning.
Code:
function preload() {
bgmusic = loadSound('assets/bg-music.mp3');
gamemusic = loadSound('assets/aa-sega.mp3');
retroFont = loadFont('assets/retro.ttf');
}
function setup() {
createCanvas(600, 400);
score = 0;
btnClick = 0; // 0 = display GUI screen 1 = play game
timer = 0;
}
function draw() {
background(220);
gameMusic();
if(btnClick == 0) {
// on open, display game info screen
openGUI();
}
else if(btnClick == 1) {
// GAME SCREEN ------------------------------------------------------
} //end game screen
else if(btnClick == 2) {
textAlign(CENTER);
text('GAME OVER', width/2, 100);
text(`You scored ${score}`, width/2, height/2);
noLoop();
}
} // end draw
function openGUI() {
background(180,180,180);
textFont(retroFont);
//Title
fill(0,0,0);
textSize(48);
text('Pong', 130, 50);
//Mouseover Button check
if (mouseX > 250 && mouseX < 330 && mouseY > 250 && mouseY < 300) {
fill(100, 0, 100);
} else {
fill(0, 100, 150);
}
// Play Button
rect(250, 250, 80, 50);
fill(220);
textSize(20);
text('Play!', 260, 285);
//Button Click > Begin game
if (mouseIsPressed && mouseX > 250 && mouseX < 330 && mouseY > 250 && mouseY < 300) {
btnClick = 1; //true - begin animation
background(100);
}
} // end openGUI()
function gameMusic() {
if(btnClick == 0) {
bgmusic.loop();
}
else if(btnClick == 1) {
bgmusic.stop();
gamemusic.play();
noLoop();
}
}