Making a mouse click play a sound

Recently I discovered PlayCanvas, and I wanted to dive right in.
However I found that this system is much different to what I have done before.
I was going to make a game, but I needed my laser rifle to make a noise… and after reviewing tutorials, other examples, and anything I can find… It never seems to ever work.

I got the audio file in, and it is in my hierarchy attached to the gun model. All I wanted is for it to simply shoot at a left mouse click!

Any changes would be welcome… but please put it out there! Just saying “do this” helps me none (i’m still learning and the tutorials are not very explanatory for beginners)

My code:

var ShootSound = pc.createScript('ShootSound');
 
var app = this.app;

ShootSound.prototype.initialize = function() {
    if (this.app.touch) {
         this.app.mouse.on('mousedown', this.shoot, this);
    }
    
GUN.prototype.shoot = function () {
    this.entity.sound.play('PEW');
};
    
ShootSound.prototype.update = function(dt) {    
if( this.app.mouse.on('mousedown', this.shoot, this)){
    this.entity.sound.play('PEW');
    } else {
     this.entity.sound.stop('PEW');
    }
    return this.ShootSound;
};      
};

Try this tutorial https://developer.playcanvas.com/en/tutorials/basic-audio/

If you click on heirarchy under scene setup, it will take you to the project. In there, the tank fires (and plays a sound effect) on clicking on the mouse.

1 Like

I think you should change

    if (this.app.touch) {
         this.app.mouse.on('mousedown', this.shoot, this);
    }

To this

this.app.mouse.on('click', this.shoot, this);

Not sure if my code is completely correct though, you would usually use click when you look for clicks on a certain element (buttons, texts, images).

EDIT: click also works on mobile devices. It registers any touch as a click.

Surprisingly I tried that already, but integrating the coding style did not turn out pretty. I essentially took it and mashed it into a simpler version for my use… This script was different than my first. It is so weird, it does not work lol

var GUN = pc.createScript('gun');

GUN.attributes.add('gun', {
    type: 'entity'
});

// particles that we are going to fire when shooting 
GUN.attributes.add('particles', {
    type: 'asset'
});

GUN.attributes.add('sound', {
    type: 'entity'
});

// initialize code called once per entity
GUN.prototype.initialize = function() {
    // shoot when we click
    if (this.app.touch) {
         this.app.mouse.on('mousedown', this.shoot, this);
    }
};
      
// a sound and fire a particle system
GUN.prototype.shoot = function () {
    // play shooting sound
    this.entity.sound.play('PEW');
    // reset and play our particle system
    this.particles.particlesystem.play();
    this.particles.particlesystem.reset();
  
};
1 Like

Here is the editor:
https://playcanvas.com/editor/scene/918459