我有以下两个文件,第一个是Physics / world.js:
var p2 = require('p2');
var pkg_world = require('../redis_pkgs/pkg_world.js');
var redisObjectMap = new Array(); // redis_id - world_id
var world = new p2.World({
gravity:[0,-9.82]
});
//el piso
var groundShape = new p2.Plane();
var groundBody = new p2.Body({
mass:0
});
groundBody.addShape(groundShape);
world.addBody(groundBody);
initWorld = pkg_world.initWorld(); //traigo el estado inicial de redis
initWorld.done(function(){
redisObjectMap = initWorld.valueOf();
});
var timeStep = 1/60;
setInterval(function(){
world.step(timeStep);
pkg_world.setWorld(world,redisObjectMap);
/* console.log(world.bodies[0].id);
console.log(world.bodies.length);*/
},1000 * timeStep);
module.exports = world;
和redis_pkgs / pkg_world.js:
var client = require('../redisClient.js');
var p2 = require('p2');
var world = require('../Physics/world.js');
var q = require('q');
var D_object = require('../schemas/d_object_schema.js');
module.exports = {
initWorld: function(){
return q.Promise(function(resolve,reject){
var result = Array();
client.hvals('d_object',function(err,obj){
if(err){
reject(err);
}else{
var tmp;
obj.forEach(function(o){
tmp = JSON.parse(o);
var circleBody = new p2.Body({
mass:5,
position:[tmp.position.x,tmp.position.y]
});
var circleShape = new p2.Circle({radius:1});
circleBody.addShape(circleShape);
world.addBody(circleBody);
result[tmp.id] = world.bodies.length; // Mapeo al id del mundo asi despues acutualizo
});
resolve(result);
}
});
});
},
setWorld: function(redisObjectMap){
return q.Promise(function(resolve,reject){
redisObjectMap.forEach(function(world_id){
var object = new D_object({
id:redisObjectMap.indexOf(world_id),
position:{
x:world.bodies[world_id].position[0],
y:world.bodies[world_id].position[1]
}
});
console.log(JSON.stringify(object));
client.hset("d_object",object.id,JSON.stringify(object));
});
resolve();
});
}
}
问题是,在第二个文件中,它告诉我world.addBody不是一个函数,但是我从第一个文件导出世界,那里是一个函数,所以我不明白我做错了什么或者它是什么我不理解来自module.exports
答案 0 :(得分:0)
这个问题既存在于循环依赖关系中,也因为module.exports
未及早设置以便在其他模块中使用。一个简单的解决方法是在module.exports
之前移动world
和world.js
声明 require()
之前的pkg_world.js
:< / p>
var p2 = require('p2');
var world = module.exports = new p2.World({
gravity:[0,-9.82]
});
var pkg_world = require('../redis_pkgs/pkg_world.js');
// ...
另一个选择是修改pkg_world.js
以将其require()
的{{1}}推迟到world.js
和initWorld()
个功能中。