Switching scenes when player contacts an object

So, here is how I’d update your code to make the two scripts communicate a change scene event:

contact scene.js

var ContactScene = pc.createScript('contactScene');

// initiali;ze code called once per entity
ContactScene.prototype.initialize = function() {
    this.entity.collision.on('triggerenter', this.OnTriggerEnter, this);    
};

ContactScene.prototype.OnTriggerEnter = function (){

    this.app.fire('contactScene:move');
};

changing-scenes.js

var ChangingScenes = pc.createScript('changingScenes');

ChangingScenes.attributes.add("sceneId", {type: "string", default: "0", title: "Scene ID to Load"});
ChangingScenes.attributes.add('playerEntity', { type: 'entity' });

ChangingScenes.prototype.initialize = function() {

    // listen for the player:move event
    this.app.on('contactScene:move', this.changeScenes, this);
    
    this.on('destroy', function() {
        this.app.off('contactScene:move',this.changeScenes, this);
    });
};

ChangingScenes.prototype.changeScenes = function() {
    // Get a reference to the current root object
    var oldHierarchy = this.app.root.findByName ('Root');
    
    console.log(this.sceneId);
    
    // Load the new scene. The scene ID is found by loading the scene in the editor and 
    // taking the number from the URL
    // e.g. If the URL when Scene 1 is loaded is: https://playcanvas.com/editor/scene/475211
    // The ID is the number on the end (475211)
    this.loadScene (this.sceneId, function () {
        // Once the new scene has been loaded, destroy the old one
        oldHierarchy.destroy ();
    });
};

ChangingScenes.prototype.loadScene = function (id, callback) {
    // Get the path to the scene
    var url = id  + ".json";
    
    // Load the scenes entity hierarchy
    this.app.loadSceneHierarchy(url, function (err, parent) {
        if (!err) {
            callback(parent);
        } else {
            console.error (err);
        }
    });
};
3 Likes