Question

I'm creating a RPG. I would like to dynamically load NPC dialog js files depending on the current level.

Originally, I was doing <script type="text/javascript" src="js/npc_dialog_level_1.js"></script> at the top of my game.js file... but don't want to keep doing that for each npc_dialog.js file.

I would rather do something like:

if (map == 1) {
   require(js/npc_dialog_level_1.js);
if (map == 2) {
   require(js/npc_dialog_level_2.js);

I was following requireJS's tutorial, but I'm not clear on:

a) The download requireJS doesn't include the helper/utils.js folder and file specified in the example:

 project-directory/
    project.html
    scripts/
        main.js
        require.js
        helper/
          util.js

b) How to use the require function: require(["helper/util"], function(util) { On map change, I'd like to just place the path to the associated npc_dialog_level.js file. Where do I put the Require code, and what do I pass into it to load the correct js file?


Each npc_dialog_level file contains js object. I am using that in my game to read dialog

var dialog = {

quests : {
    Lee : {
        "1 - Introductions" :

Update:

I tried:

//load NPC dialog given the map
loadNpcDialog : function (dialogNumber) {
    require("npc_dialog_level_" + dialogNumber + ".js", function(dialog) {
    //  log(dialog);
    });     
},

Gives:

Uncaught Error: Invalid require call
http://requirejs.org/docs/errors.html#requireargs require.js:166
Était-ce utile?

La solution

You have to use brackets for your dependency list when you call require, like this:

//load NPC dialog given the map
loadNpcDialog : function (dialogNumber) {
    require(["npc_dialog_level_" + dialogNumber + ".js"], function(dialog) {
    //  log(dialog);
    });     
},

If you don't use brackets, then you're using the pseudo-synchronous form of require, which would be used like this: var dialog = require("npc_dialog_level_" + dialogNumber + ".js"). However, this pseudo-synchronous form would not work in your case.

If eventually you want to make these files into JSON files or XML you can use the text! plugin to load them.

Autres conseils

IFF your dialog stuff is all actually JavaScript, then doing a late-loading is fairly easy.

function runNpcDialog(number) {
    require(["npc-dialog-" + number + ".js"], function(dialog) {
      // Run your dialog here.
    });
}

Otherwise, if your information is more of a JSON/XML format, then using ajax would be a better option.

EDIT: Fixed syntax

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top