How to Play a Sound when an Object is Clicked

 In this Phaser3 tutorial we will take our Hello World program and make it play a sound effect when you use the mouse to click on the words, "Hello World."

Let's start with our basic Hello World program again.

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8" />
    <title>Sound Example</title>
    <script src="phaser.min.js"></script>
    <style type="text/css">
        body {
            margin: 0;
        }
    </style>
</head>
<body>

<script type="text/javascript">

var config = {
  type: Phaser.AUTO,
  scene: {
    preload: preload,
create: create,
update: update
}
  };
  
var text; 
var game = new Phaser.Game(config);

function preload() {
}

function create() {
  
  text = this.add.text(200,200,'Hello World',
    {fontSize: '50px', fill: '#9999ff' });

}

function update() {
}

</script>
</body>
</html>


Next, in the preload function we will load a sound file.


function preload() {
  this.load.audio('clickedsound', 'mySoundFile.ogg'); //Does not have to be an ogg file
}


Last we will add a variable to store our sound file and then make the text respond to a mouse click.
In the create function, add these.


function create() {
  
  text = this.add.text(200,200,'Hello World',
    {fontSize: '50px', fill: '#9999ff' });

  var clickedsound = this.sound.add('clickedsound');
  clickedsound.loop = false;
  
text.setInteractive();
    text.on('pointerup', function() {
  clickedsound.play(); 
    }, this);
}


And that should be it. Now try running your program and clicking on the text.

Comments

Popular Posts