Accessing a global variable outside of an anonymous function in JavaScript using require
I am developing an HTML5 real-time multiplayer game and I have a game_core.js file that runs the physics of the game using the p2 library. I would like to run this file on both client and prediction and 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 am loading 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 cannot find the correct way to access the p2 object, which 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 am getting this error:
this.world = new p2.World({gravity:[0, 0]});
^
ReferenceError: p2 is not defined
If I create p2 property in gameCore leave world as null in constructor, assign global p2 to gameCore p2 and then assign correct value to world using 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 it on other gameCore classes, I get a stack overflow. And if I use
var p2 = require('p2');
on gameCore it works, but the client complains about the need to use.
I'm new to JavaScript, but I've looked at closures, anonymous functions and many similar doubts. Unfortunately, I have not been able to resolve this issue yet.
source to share
browserify allows you to use query in your client js files.
Also you need game_core.js to require p2 if you want to use p2 in the constructor.
Your client file using a browser 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>
source to share