PageRenderTime 47ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/js/DemoBox2D/DemoBox2DServerGame.js

http://github.com/onedayitwillmake/RealtimeMultiplayerNodeJs
JavaScript | 231 lines | 128 code | 35 blank | 68 comment | 4 complexity | a2b4aa483c455ff06dbd5651f17187fc MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, MPL-2.0-no-copyleft-exception, BSD-3-Clause
  1. /**
  2. File:
  3. DemoBox2DServerGame.js
  4. Created By:
  5. Mario Gonzalez
  6. Project:
  7. DemoBox2D
  8. Abstract:
  9. This is a demo of using Box2d.js with RealTimeMultiplayerNode.js
  10. The box2d.js world creation and other things in this demo, are shamelessly lifted from the https://github.com/HBehrens/box2d.js examples
  11. Basic Usage:
  12. demoServerGame = new DemoBox2D.DemoServerGame();
  13. demoServerGame.startGameClock();
  14. Version:
  15. 1.0
  16. */
  17. (function () {
  18. var BOX2D = require("./lib/box2d.js");
  19. DemoBox2D.DemoServerGame = function () {
  20. DemoBox2D.DemoServerGame.superclass.constructor.call(this);
  21. this.setGameDuration(DemoBox2D.Constants.GAME_DURATION);
  22. this.setupBox2d();
  23. return this;
  24. };
  25. DemoBox2D.DemoServerGame.prototype = {
  26. _world: null,
  27. _velocityIterationsPerSecond: 100,
  28. _positionIterationsPerSecond: 300,
  29. /**
  30. * Map RealtimeMultiplayerGame.Constants.CMDS to functions
  31. * If ServerNetChannel does not contain a function, it will check to see if it is a special function which the delegate wants to catch
  32. * If it is set, it will call that CMD on its delegate
  33. */
  34. setupCmdMap: function () {
  35. DemoBox2D.DemoServerGame.superclass.setupCmdMap.call(this);
  36. this.cmdMap[RealtimeMultiplayerGame.Constants.CMDS.PLAYER_UPDATE] = this.shouldUpdatePlayer;
  37. },
  38. /**
  39. * Sets up the Box2D world and creates a bunch of boxes from that fall from the sky
  40. */
  41. setupBox2d: function () {
  42. DemoBox2D.Constants.GAME_WIDTH /= DemoBox2D.Constants.PHYSICS_SCALE;
  43. DemoBox2D.Constants.GAME_HEIGHT /= DemoBox2D.Constants.PHYSICS_SCALE;
  44. DemoBox2D.Constants.ENTITY_BOX_SIZE /= DemoBox2D.Constants.PHYSICS_SCALE;
  45. this.createBox2dWorld();
  46. this._world.DestroyBody(this._wallBottom);
  47. for (var i = 0; i < DemoBox2D.Constants.MAX_OBJECTS; i++) {
  48. var x = (DemoBox2D.Constants.GAME_WIDTH / 2) + Math.sin(i / 5);
  49. var y = i * -DemoBox2D.Constants.ENTITY_BOX_SIZE * 3;
  50. // Make a square or a box
  51. if (Math.random() < 0.5) this.createBall(x, y, DemoBox2D.Constants.ENTITY_BOX_SIZE);
  52. else this.createBox(x, y, 0, DemoBox2D.Constants.ENTITY_BOX_SIZE);
  53. }
  54. },
  55. /**
  56. * Creates the Box2D world with 4 walls around the edges
  57. */
  58. createBox2dWorld: function () {
  59. var m_world = new BOX2D.b2World(new BOX2D.b2Vec2(0, 10), true);
  60. m_world.SetWarmStarting(true);
  61. // Create border of boxes
  62. var wall = new BOX2D.b2PolygonShape();
  63. var wallBd = new BOX2D.b2BodyDef();
  64. // Left
  65. wallBd.position.Set(-1.5, DemoBox2D.Constants.GAME_HEIGHT / 2);
  66. wall.SetAsBox(1, DemoBox2D.Constants.GAME_HEIGHT * 10);
  67. this._wallLeft = m_world.CreateBody(wallBd);
  68. this._wallLeft.CreateFixture2(wall);
  69. // Right
  70. wallBd.position.Set(DemoBox2D.Constants.GAME_WIDTH + 0.55, DemoBox2D.Constants.GAME_HEIGHT / 2);
  71. wall.SetAsBox(1, DemoBox2D.Constants.GAME_HEIGHT * 10);
  72. this._wallRight = m_world.CreateBody(wallBd);
  73. this._wallRight.CreateFixture2(wall);
  74. // BOTTOM
  75. wallBd.position.Set(DemoBox2D.Constants.GAME_WIDTH / 2, DemoBox2D.Constants.GAME_HEIGHT + 0.55);
  76. wall.SetAsBox(DemoBox2D.Constants.GAME_WIDTH / 2, 1);
  77. this._wallTop = m_world.CreateBody(wallBd);
  78. this._wallTop.CreateFixture2(wall);
  79. // TOP
  80. wallBd.position.Set(DemoBox2D.Constants.GAME_WIDTH / 2, 1);
  81. wall.SetAsBox(DemoBox2D.Constants.GAME_WIDTH / 2, 1);
  82. this._wallBottom = m_world.CreateBody(wallBd);
  83. this._wallBottom.CreateFixture2(wall);
  84. this._world = m_world;
  85. },
  86. /**
  87. * Creates a Box2D circular body
  88. * @param {Number} x Body position on X axis
  89. * @param {Number} y Body position on Y axis
  90. * @param {Number} radius Body radius
  91. * @return {b2Body} A Box2D body
  92. */
  93. createBall: function (x, y, radius) {
  94. var fixtureDef = new BOX2D.b2FixtureDef();
  95. fixtureDef.shape = new BOX2D.b2CircleShape(radius);
  96. fixtureDef.friction = 0.4;
  97. fixtureDef.restitution = 0.6;
  98. fixtureDef.density = 1.0;
  99. var ballBd = new BOX2D.b2BodyDef();
  100. ballBd.type = BOX2D.b2Body.b2_dynamicBody;
  101. ballBd.position.Set(x, y);
  102. var body = this._world.CreateBody(ballBd);
  103. body.CreateFixture(fixtureDef);
  104. // Create the entity for it in RealTimeMultiplayerNodeJS
  105. var aBox2DEntity = new DemoBox2D.Box2DEntity(this.getNextEntityID(), RealtimeMultiplayerGame.Constants.SERVER_SETTING.CLIENT_ID);
  106. aBox2DEntity.setBox2DBody(body);
  107. aBox2DEntity.entityType = DemoBox2D.Constants.ENTITY_TYPES.CIRCLE;
  108. this.fieldController.addEntity(aBox2DEntity);
  109. return body;
  110. },
  111. /**
  112. * Creates a Box2D square body
  113. * @param {Number} x Body position on X axis
  114. * @param {Number} y Body position on Y axis
  115. * @param {Number} rotation Body rotation
  116. * @param {Number} size Body size
  117. * @return {b2Body} A Box2D body
  118. */
  119. createBox: function (x, y, rotation, size) {
  120. var bodyDef = new BOX2D.b2BodyDef();
  121. bodyDef.type = BOX2D.b2Body.b2_dynamicBody;
  122. bodyDef.position.Set(x, y);
  123. bodyDef.angle = rotation;
  124. var body = this._world.CreateBody(bodyDef);
  125. var shape = new BOX2D.b2PolygonShape.AsBox(size, size);
  126. var fixtureDef = new BOX2D.b2FixtureDef();
  127. fixtureDef.restitution = 0.1;
  128. fixtureDef.density = 1.0;
  129. fixtureDef.friction = 1.0;
  130. fixtureDef.shape = shape;
  131. body.CreateFixture(fixtureDef);
  132. // Create the entity for it in RealTimeMultiplayerNodeJS
  133. var aBox2DEntity = new DemoBox2D.Box2DEntity(this.getNextEntityID(), RealtimeMultiplayerGame.Constants.SERVER_SETTING.CLIENT_ID);
  134. aBox2DEntity.setBox2DBody(body);
  135. aBox2DEntity.entityType = DemoBox2D.Constants.ENTITY_TYPES.BOX;
  136. this.fieldController.addEntity(aBox2DEntity);
  137. return body;
  138. },
  139. /**
  140. * Updates the game
  141. * Creates a WorldEntityDescription which it sends to NetChannel
  142. */
  143. tick: function () {
  144. var delta = 16 / 1000;
  145. this.step(delta);
  146. if (this.gameTick % 30 === 0) {
  147. this.resetRandomBody();
  148. }
  149. // Note we call superclass's implementation after we're done
  150. DemoBox2D.DemoServerGame.superclass.tick.call(this);
  151. },
  152. /**
  153. * Resets an entity and drops it from the sky
  154. */
  155. resetRandomBody: function () {
  156. // Retrieve a random key, and use it to retreive an entity
  157. var allEntities = this.fieldController.getEntities();
  158. var randomKeyIndex = Math.floor(Math.random() * allEntities._keys.length);
  159. var entity = allEntities.objectForKey(allEntities._keys[randomKeyIndex]);
  160. var x = Math.random() * DemoBox2D.Constants.GAME_WIDTH + DemoBox2D.Constants.ENTITY_BOX_SIZE;
  161. var y = Math.random() * -15;
  162. entity.getBox2DBody().SetPosition(new BOX2D.b2Vec2(x, y));
  163. },
  164. step: function (delta) {
  165. this._world.ClearForces();
  166. // var delta = (typeof delta == "undefined") ? 1/this._fps : delta;
  167. this._world.Step(delta, delta * this._velocityIterationsPerSecond, delta * this._positionIterationsPerSecond);
  168. },
  169. shouldAddPlayer: function (aClientid, data) {
  170. // this.createPlayerEntity( this.getNextEntityID(), aClientid);
  171. },
  172. /**
  173. * @inheritDoc
  174. */
  175. shouldUpdatePlayer: function (aClientid, data) {
  176. var pos = new BOX2D.b2Vec2(data.payload.x, data.payload.y);
  177. pos.x /= DemoBox2D.Constants.PHYSICS_SCALE;
  178. pos.y /= DemoBox2D.Constants.PHYSICS_SCALE;
  179. // Loop through each entity, retrieve it's Box2D body, and apply an impulse towards the mouse position a user clicked
  180. this.fieldController.getEntities().forEach(function (key, entity) {
  181. var body = entity.getBox2DBody();
  182. var bodyPosition = body.GetPosition();
  183. var angle = Math.atan2(pos.y - bodyPosition.y, pos.x - bodyPosition.x);
  184. var force = 20;
  185. var impulse = new BOX2D.b2Vec2(Math.cos(angle) * force, Math.sin(angle) * force);
  186. body.ApplyImpulse(impulse, bodyPosition);
  187. }, this);
  188. },
  189. shouldRemovePlayer: function (aClientid) {
  190. // DemoBox2D.DemoServerGame.superclass.shouldRemovePlayer.call( this, aClientid );
  191. // console.log("DEMO::REMOVEPLAYER");
  192. }
  193. };
  194. // extend RealtimeMultiplayerGame.AbstractServerGame
  195. RealtimeMultiplayerGame.extend(DemoBox2D.DemoServerGame, RealtimeMultiplayerGame.AbstractServerGame, null);
  196. })()