Firing event on collision

Hi!
I’m trying to fire pc.app event on collision to catch it in another script. As I see in the console log, the event is firing but I don’t catch it second script.

script1

var Collide = pc.createScript('collide');

// initialize code called once per entity
Collide.prototype.initialize = function() {
    this.entity.collision.on('triggerenter', this.onTriggerEnter, this);
};

Collide.prototype.update = function(dt) {
    
};

Collide.prototype.onTriggerEnter = function() {
    var app = this.app;

    app.fire('gameover');
    console.log('GAME OVER');
    
};

script2

var Scroll = pc.createScript('scroll');
    
Scroll.attributes.add('cycleEvent', { type: 'string' });
Scroll.attributes.add('stopEvent', { type: 'string' });
Scroll.attributes.add('speed', { type: 'number' });
Scroll.attributes.add('start', { type: 'number' });
Scroll.attributes.add('end', { type: 'number' });
Scroll.attributes.add('frozen', { type: 'boolean' });

Scroll.prototype.initialize = function() {
    var app = this.app;

    app.on('gameover', function() {
        this.frozen = true;
    });
};

// update code called every frame
Scroll.prototype.update = function(dt) {
    var app = this.app;
    
    if (!this.frozen) {
        this.entity.translate(0, 0, this.speed*dt / (1/60));
        var pos = this.entity.getPosition();
        if (pos.z > this.end) {
            this.entity.translate(0,0,this.start);
            app.fire(this.cycleEvent);
        } 
    }
};

The issue here is the scope of this reference. As it’s in a function, the this is referencing to the instance of the function not the script.

Change it to:

    app.on('gameover', function() {
        this.frozen = true;
    }, this);

This makes the script instance the scope for the this reference.

1 Like

Thanks!
That’s worked. Didn’t understand well the scope precision of “this” here.