Matheus Camargo
Matheus Camargo

Reputation: 103

Access global variable outside of anonymous function in JavaScript using require

I'm developing a HTML5 real-time multiplayer game and I have a game_core.js file that runs the game physics using the p2 library. I would like to run this file both on the client, to make prediction, and on the authoritative server. Here's the constructor and module.exports:

function gameCore() {
    this.world = new p2.World({gravity:[0, 0]});
    this.players = {};
    this.step = 1/60;
}

...

module.exports = gameCore;

Since I'm loading the p2.js file inside index.html

<script type="text/javascript" src="lib/p2.js"></script>
<script type="text/javascript" src="game_client.js"></script>
<script type="text/javascript" src="game_core.js"></script>

the constructor finds the p2 object and everything works fine. But my problem is when I try to run this file on the server, because I can't find a proper way to access the p2 object, that is a global variable on game_server.js:

var
    io              = require('socket.io'),
    express         = require('express'),
    UUID            = require('node-uuid'),
    p2              = require('p2'),
    verbose         = false,
    http            = require('http'),
    app             = express(),
    config          = require('./config.json'),
    gameCore        = require('./game_core.js'),
    server          = http.createServer(app);

var world = new gameCore();

I get this error:

this.world = new p2.World({gravity:[0, 0]});
                         ^
ReferenceError: p2 is not defined

If I create a p2 property on gameCore, leave world as null on the constructor, assign the global p2 to gameCore's p2 and then assign the correct value to world using a init function

function gameCore() {
    this.p2 = null;
    this.world = null;
    this.players = {};
    this.step = 1/60;
}

gameCore.prototype.init = function() {   
    this.world = new this.p2.World({gravity:[0, 0]});
}

it works, but since I need to do this on other classes of gameCore I get a stack overflow. And if I use

var p2 = require('p2');

on gameCore it works, but the client complains about using require.

I'm new to JavaScript, but I've looked at closure, anonymous functions and many similar doubts. Unfortunately I couldn't solve this issue yet.

Upvotes: 3

Views: 413

Answers (1)

t3dodson
t3dodson

Reputation: 4007

browserify lets you use require within your client js files.

Also you need game_core.js require p2 if you want to use p2 in the constructor.

Your client file using browserify should look like this

<script src="bundle.js"></script> <!-- browserify p2 game_core.js config.json --->
<script>
  var p2 = require('p2 ');
  var game_core= require('game_core.js');
  var config= require('config.json');
 /* ... */
</script>

Upvotes: 1

Related Questions