[Solved] How to call an event correctly?

I try fire “Start” event. when an Annyang voice command is listened, but something is wrong.

if (annyang) {
    
    var app= this.app;
  // Let's define a command.
  var commands = {
    'show': function() { this.app.fire("Start"); }
  };
  annyang.debug(true);
  // Add our commands to annyang
  annyang.addCommands(commands);
 

  // Start listening.
  annyang.start();
}

_thanks :slight_smile: _

You are defining a closure as the callback so the this reference is not correct.

Try this:

if (annyang) {
    
    var app= this.app;
  // Let's define a command.
  var commands = {
    'show': function() { app.fire("Start"); }
  };
  annyang.debug(true);
  // Add our commands to annyang
  annyang.addCommands(commands);

  // Start listening.
  annyang.start();
}

:frowning_face: there are still mistakes. “Cannot read property fire of undefined”

Going to need to see more of the code that you have shown here.

This is my Code now. The goal is set rigid body when ‘start’ event is listened There arent console errors, but not work :fearful:

Script to fire event

// initialize code called once per e
// update code called every frame

var Voice1 = pc.createScript('voice1');
 Voice1.prototype.initialize = function(){
     var app = this.app;
 };

Voice1.prototype.update = function(){
  // Add our commands to annyang
if (annyang) {
    
    var app= this.app;
  // Let's define a command.
  var commands = {
    'show': function() { app.fire("start"); }
  };
  annyang.debug(true);
  // Add our commands to annyang
  annyang.addCommands(commands);

  // Start listening.
  annyang.start();
}
};```
///////////// And the event listener

var Manager = pc.createScript(‘manager’);

// initialize code called once per entity
Manager.prototype.initialize = function(dt) {
var app=this.app;

this.app.on('start', function () {
        this.entity.rigidbody.type=pc.BODYTYPE_DYNAMC;});

};

Try changing the code like this:

var Manager = pc.createScript('manager');

Manager.prototype.initialize = function() {
    var self = this;
    this.app.on('start', function() {
        self.entity.rigidbody.type = pc.BODYTYPE_DYNAMIC;
    });
};

You have several issues here. Currently you are creating a new command for annyang every frame as you have the setup in the update loop. Generally, you only want to do this once so the initalize function is a better choice.

There’s a typo in the use of BODYTYPE_DYNAMIC. (missing i in your case: BODYTYPE_DYNAMC).

And I think there is a couple of scope issues as well.

Here’s a working version: https://playcanvas.com/project/605830/overview/test-voice-recognition

1 Like

Hi i try forked your project. https://playcanvas.com/editor/scene/723082 But not work now. Did you make some change?

Nope, my project still works fine for me. Looking at your project, the speech recognition library doesn’t recognise the word ‘play’. Try a two word or two syllable phrase.