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">
function preload() {
var config = {
type: Phaser.AUTO,
scene: {
preload: preload,
create: create,
update: update
}
};
var text;
var game = new Phaser.Game(config);
}
function create() {
text = this.add.text(200,200,'Hello World',
{fontSize: '50px', fill: '#9999ff' });
}
function update() {
}
</script>
</body>
</html>
this.load.audio('clickedsound', 'mySoundFile.ogg'); //Does not have to be an ogg file
}
In the create function, add these.
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);
}
Comments
Post a Comment