Working with Instant Games API and PlayCanvas Editor

Works, here’s my version of the loading.js for future reference

        FBInstant.initializeAsync().then( function()
        {
            pc.script.createLoadingScreen(function (app) 
            {
                app.on('preload:end', function () 
                {
                    app.off('preload:progress');
                });

                app.on('preload:progress', function (value)
                {
                    FBInstant.setLoadingProgress( value*100 )
                });

                app.on('start', function()
                {
                    FBInstant.startGameAsync().then(function(){})
                });
            });
        });
            
1 Like

@Yohami_Zerpa glad to know, and thanks for your improved and concise code!

1 Like

@Grayson_Ewing extra question - how do I hide the Playcanvas canvas while the app is loading? it’s rendering the screen black and covering the FBInstant loader after some point

@Yohami_Zerpa does the problem still occur if you copy and paste my code exactly? I also had some problems when i completely removed certain function like the createCss() or showSplash(). Try experimenting and including/excluding different functions to see i you can get your desired result

Nevermind it works, I had uploaded the wrong code X-)

1 Like

@Grayson_Ewing Thank you for your new contributions, I have tried this for a long time. I added fbapp-config.json and edited loading.js before recompressing as you suggested. However, I still can’t get the game to start. Did I forget something?

    var setProgress = function (value) {
        try {
             FBInstant.setLoadingProgress(value*100);
            if(value*100>=100) {
                    setTimeout(()=>{
                        FBInstant.startGameAsync().then(function() {
                            console.log('started');    
                        },this);
                    },1000);
                }
                } catch(ex) {
                    
                }

        
        let setLoad = new CustomEvent("setLoad", {detail:{loadValue:value}});
        window.dispatchEvent(setLoad);

    };

Heres mine

Dont forget to edit the index html of the published build.

This is obviously not a copy paste situation, think about setting that loading progress bar and other functions and how everything loads.

I had the same issue with the workflow. From the Facebook dev website, I found their github with examples on the usage of the SDK for Instant Games:

In one of the examples, they use a mock SDK script, to simulate the original one.

I simply attached it to the root of my project. The benefit is that now I can make proper SDK calls and I don’t need to upload the project to Facebook for checking if the changes are correct, or using a localhost, as described here - it still requires me to download my project first and place it to the http-server folder, which is cumbersome. The only thing - I comment out the section, where the real SDK is inserted in this tutorial:

(function () {
    var _fb = false;
    var _pc = false;
    var _inst = null;
    var app = null;
    
    app = pc.Application.getApplication();
    app.on("initialize", function () {
        if (_fb) {
            app.fire("fb:init");
        }        
    });

    app.on('preload:end', function() {
        
        FBInstant.initializeAsync().then(function() {
            FBInstant.setLoadingProgress(100);
            FBInstant.startGameAsync().then(onStart);
        });
    });
    
    function onStart() {
        _fb = true;
        if (app) {
            app.fire('fb:init');
        } 
    }
    
    // (function(d, s, id){
    //     var js, fjs = d.getElementsByTagName(s)[0];
    //     if (d.getElementById(id)) {return;}
    //     js = d.createElement(s); js.id = id;
    //     js.src = "//connect.facebook.net/en_US/fbinstant.6.3.js";
    //     fjs.parentNode.insertBefore(js, fjs);
    // }(document, 'script', 'facebook-jssdk'));  
}());

The downside is that the mock SDK will return some random data (which you can actually change yourself to simulate the conditions you need), instead of real data. At least, you can be sure your function calls are correct and you have handlers in place, then you can test in Facebook environment, by disabling the mock SDK and uncommenting the lines responsible for fetching the real SDK.

Edit:
Posted my setup script.

1 Like

Finally the game is ready to go to Facebook. Thk @yqu

1 Like

How are you enabling the real SDK and disabling the mock when you create a build?

Are you manually editing every build code, did you create a build script for it or is there an easier way using PlayFab tools?

I’ve been playing around with the FB Instant Games SDK myself. I’ve considered different ways to set up the SDK from a PlayCanvas app exported from the Editor. Editing __start__.js seemed to work pretty well. I just modified the end:

    var configure = function () {
        app.configure(CONFIG_FILENAME, function (err) {
            if (err) {
                console.error(err);
            }

            configureCss(app._fillMode, app._width, app._height);

            // do the first reflow after a timeout because of
            // iOS showing a squished iframe sometimes
            setTimeout(function () {
                reflow();

                window.addEventListener('resize', reflow, false);
                window.addEventListener('orientationchange', reflow, false);

                app.preload(function (err) {
                    if (err) {
                        console.error(err);
                    }

                    app.loadScene(SCENE_PATH, function (err, scene) {
                        if (err) {
                            console.error(err);
                        }

                        FBInstant.startGameAsync().then(function () {
                            app.start();
                        });
                    });
                });
            });
        });
    };

    FBInstant.initializeAsync().then(function() {

        app.once('preload:end', function () {
            FBInstant.setLoadingProgress(100);
        });

        app.on('preload:progress', function (value) {
            value = Math.min(1, Math.max(0, value));
            FBInstant.setLoadingProgress(value * 100);
        });

        if (PRELOAD_MODULES.length > 0) {
            loadModules(PRELOAD_MODULES, ASSET_PREFIX, configure);
        } else {
            configure();
        }
    });

I also delete the loading screen script from the index.html (since it’s not needed because FBIG shows a native loading screen).

It should be pretty easy to write a little Node.js tool that downloads a build and makes these modifications automatically.

2 Likes

Hi Will, thanks for your response.

Indeed, a couple of days a go I created a Node script that downloads the build through the REST API and then performs the required changes to make the generated project IG compatible.

My steps work like this:

1 - Request build, download and unzip it
2 - Inject a reference to the official FB IG SDK inside the index.html
3 - Replace “__loading__.js” with a version that handles loading through FBInstant (instead of __start__.js)
4 - Add the fbapp-config.json file
5 - On the mock SDK that LeXXiK mentioned, I replace then “FBInstant” with “Mock” to make sure it doesn’t override the official one.

Step 5 is a little tricky since it leaves some unused code in the final build, so what’s why I wanted to know if there’s an easy way to have the mock SDK used on the editor but not exported into the build.

Alright, well the time has passed since then, so did my build setup :slight_smile: Modifying the loading.js or start.js as showed by Will and others is a good way. This is for the downloaded build, though. Mock SDK can help you with editing stuff live, inside the Playcanvas Editor. For example, getting a mock response with list of friends and creating a UI for it, all without downloading, etc.

Once you downloaded the build, though, you may and should use the real SDK.

Nevertheless, in your particular setup, I would recommend creating separate tasks - one for setting up the files for local development (lets call it “local”), and another for the release (“release”). So your “release” task could have all the tasks from “local”, plus extra, like substituting loading scripts, removing unneeded files, minifying, zipping, etc. This goes a bit beyond the purpose of this forum, so I will PM you.

Hi, i have followed your steps above. I have edited loading and start scripts. No errors. But when i upload my build on web storage on facebook it gives me this msg ‘"Games must use the Instant Games SDK properly and should not call private methods directly.’ In my game I have one call to get sdk version and in console log it prints 6.3. Anyone know what’s going on here? I have implemented the Facebook SDK like mentioned here [SOLVED] Adding the Facebook Instant Game SDK to my PlayCanvas project . Also this documentation is a little outdated https://developer.playcanvas.com/en/user-manual/publishing/web/facebook/ can anyone help with that? Can anybody share one simple project just to get me started? this is my project if anyone is willing to see if i did something wrong… https://playcanvas.com/project/666638/overview/realrealreal

Does it mention what functions you shouldn’t be calling?

FYI, that documentation is for the Facebook Canvas games, not Instant Games so I wouldn’t follow that :grimacing:

2 Likes

Fb instant games is a big market, looking forward for documentation regarding making IG games using Playcanvas and the possible work flows etc. :slight_smile:

1 Like

No unfortunately. That’s why i came here to check if anyone else got this response while uploading build.
I have account and one Construct3 game up and running, I’m trying to do the same with playcanvas. Can we agree that there would be nice to have build options (Html5, Facebook Instant Games,… ). So this post build process can be done only if needed. I’ve looked for answer all over the web but no one did a proper tutorial on this with building and deploying.

Facebook should have documentation around their SDK, have you tried using that as your starting point?

@Aetrix right, so, you are adding it correctly. The issue you have is that the Playcanvas application starts first, which then calls the Facebook IG SDK method, that has not yet been initialized.

You want to modify the Loading Screen in the project settings:
image

Your goal is to make the Facebook SDK to load first, initialize, and once it is ready, start the Playcanvas application. The example of the loading screen script changes you can find this thread, for example from Yohami.

Edit: be advised, if you change the loading screen from the Edtior, you app will stop launching and would only be usable on Facebook servers. The way I did it, was the editor having a mock SDK, which would avoid the app to throw errors, since real SDK cannot be reached from outside their own domain. When I would need to use the real values, I would then download the build and a node based build tool would replace the needed files, like the loading screen, remove the mock SDK, etc. I would then launch the localhost server that is connected to Facebook directly and use the actual SDK. Its a bit of a hassle to set it up, to be honest, but once it is set, its alright I guess. An option for building the app for FB instant games could probably help a little, but only in changing the loading screen script for you. The rest of the process would still be on your shoulders anyway.

1 Like