PageRenderTime 137ms CodeModel.GetById 41ms app.highlight 46ms RepoModel.GetById 34ms 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
  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
 22        this.setGameDuration(DemoBox2D.Constants.GAME_DURATION);
 23        this.setupBox2d();
 24        return this;
 25    };
 26
 27    DemoBox2D.DemoServerGame.prototype = {
 28        _world: null,
 29        _velocityIterationsPerSecond: 100,
 30        _positionIterationsPerSecond: 300,
 31
 32        /**
 33         * Map RealtimeMultiplayerGame.Constants.CMDS to functions
 34         * If ServerNetChannel does not contain a function, it will check to see if it is a special function which the delegate wants to catch
 35         * If it is set, it will call that CMD on its delegate
 36         */
 37        setupCmdMap: function () {
 38            DemoBox2D.DemoServerGame.superclass.setupCmdMap.call(this);
 39            this.cmdMap[RealtimeMultiplayerGame.Constants.CMDS.PLAYER_UPDATE] = this.shouldUpdatePlayer;
 40        },
 41
 42        /**
 43         * Sets up the Box2D world and creates a bunch of boxes from that fall from the sky
 44         */
 45        setupBox2d: function () {
 46
 47            DemoBox2D.Constants.GAME_WIDTH /= DemoBox2D.Constants.PHYSICS_SCALE;
 48            DemoBox2D.Constants.GAME_HEIGHT /= DemoBox2D.Constants.PHYSICS_SCALE;
 49            DemoBox2D.Constants.ENTITY_BOX_SIZE /= DemoBox2D.Constants.PHYSICS_SCALE;
 50
 51
 52            this.createBox2dWorld();
 53            this._world.DestroyBody(this._wallBottom);
 54
 55            for (var i = 0; i < DemoBox2D.Constants.MAX_OBJECTS; i++) {
 56                var x = (DemoBox2D.Constants.GAME_WIDTH / 2) + Math.sin(i / 5);
 57                var y = i * -DemoBox2D.Constants.ENTITY_BOX_SIZE * 3;
 58
 59                // Make a square or a box
 60                if (Math.random() < 0.5) this.createBall(x, y, DemoBox2D.Constants.ENTITY_BOX_SIZE);
 61                else this.createBox(x, y, 0, DemoBox2D.Constants.ENTITY_BOX_SIZE);
 62            }
 63        },
 64
 65        /**
 66         * Creates the Box2D world with 4 walls around the edges
 67         */
 68        createBox2dWorld: function () {
 69            var m_world = new BOX2D.b2World(new BOX2D.b2Vec2(0, 10), true);
 70            m_world.SetWarmStarting(true);
 71
 72            // Create border of boxes
 73            var wall = new BOX2D.b2PolygonShape();
 74            var wallBd = new BOX2D.b2BodyDef();
 75
 76            // Left
 77            wallBd.position.Set(-1.5, DemoBox2D.Constants.GAME_HEIGHT / 2);
 78            wall.SetAsBox(1, DemoBox2D.Constants.GAME_HEIGHT * 10);
 79            this._wallLeft = m_world.CreateBody(wallBd);
 80            this._wallLeft.CreateFixture2(wall);
 81            // Right
 82            wallBd.position.Set(DemoBox2D.Constants.GAME_WIDTH + 0.55, DemoBox2D.Constants.GAME_HEIGHT / 2);
 83            wall.SetAsBox(1, DemoBox2D.Constants.GAME_HEIGHT * 10);
 84            this._wallRight = m_world.CreateBody(wallBd);
 85            this._wallRight.CreateFixture2(wall);
 86            // BOTTOM
 87            wallBd.position.Set(DemoBox2D.Constants.GAME_WIDTH / 2, DemoBox2D.Constants.GAME_HEIGHT + 0.55);
 88            wall.SetAsBox(DemoBox2D.Constants.GAME_WIDTH / 2, 1);
 89            this._wallTop = m_world.CreateBody(wallBd);
 90            this._wallTop.CreateFixture2(wall);
 91            // TOP
 92            wallBd.position.Set(DemoBox2D.Constants.GAME_WIDTH / 2, 1);
 93            wall.SetAsBox(DemoBox2D.Constants.GAME_WIDTH / 2, 1);
 94            this._wallBottom = m_world.CreateBody(wallBd);
 95            this._wallBottom.CreateFixture2(wall);
 96
 97            this._world = m_world;
 98        },
 99
100        /**
101         * Creates a Box2D circular body
102         * @param {Number} x    Body position on X axis
103         * @param {Number} y    Body position on Y axis
104         * @param {Number} radius Body radius
105         * @return {b2Body}    A Box2D body
106         */
107        createBall: function (x, y, radius) {
108            var fixtureDef = new BOX2D.b2FixtureDef();
109            fixtureDef.shape = new BOX2D.b2CircleShape(radius);
110            fixtureDef.friction = 0.4;
111            fixtureDef.restitution = 0.6;
112            fixtureDef.density = 1.0;
113
114            var ballBd = new BOX2D.b2BodyDef();
115            ballBd.type = BOX2D.b2Body.b2_dynamicBody;
116            ballBd.position.Set(x, y);
117            var body = this._world.CreateBody(ballBd);
118            body.CreateFixture(fixtureDef);
119
120            // Create the entity for it in RealTimeMultiplayerNodeJS
121            var aBox2DEntity = new DemoBox2D.Box2DEntity(this.getNextEntityID(), RealtimeMultiplayerGame.Constants.SERVER_SETTING.CLIENT_ID);
122            aBox2DEntity.setBox2DBody(body);
123            aBox2DEntity.entityType = DemoBox2D.Constants.ENTITY_TYPES.CIRCLE;
124
125            this.fieldController.addEntity(aBox2DEntity);
126
127            return body;
128        },
129
130        /**
131         * Creates a Box2D square body
132         * @param {Number} x    Body position on X axis
133         * @param {Number} y    Body position on Y axis
134         * @param {Number} rotation    Body rotation
135         * @param {Number} size Body size
136         * @return {b2Body}    A Box2D body
137         */
138        createBox: function (x, y, rotation, size) {
139            var bodyDef = new BOX2D.b2BodyDef();
140            bodyDef.type = BOX2D.b2Body.b2_dynamicBody;
141            bodyDef.position.Set(x, y);
142            bodyDef.angle = rotation;
143
144            var body = this._world.CreateBody(bodyDef);
145            var shape = new BOX2D.b2PolygonShape.AsBox(size, size);
146            var fixtureDef = new BOX2D.b2FixtureDef();
147            fixtureDef.restitution = 0.1;
148            fixtureDef.density = 1.0;
149            fixtureDef.friction = 1.0;
150            fixtureDef.shape = shape;
151            body.CreateFixture(fixtureDef);
152
153            // Create the entity for it in RealTimeMultiplayerNodeJS
154            var aBox2DEntity = new DemoBox2D.Box2DEntity(this.getNextEntityID(), RealtimeMultiplayerGame.Constants.SERVER_SETTING.CLIENT_ID);
155            aBox2DEntity.setBox2DBody(body);
156            aBox2DEntity.entityType = DemoBox2D.Constants.ENTITY_TYPES.BOX;
157
158
159            this.fieldController.addEntity(aBox2DEntity);
160
161            return body;
162        },
163
164
165        /**
166         * Updates the game
167         * Creates a WorldEntityDescription which it sends to NetChannel
168         */
169        tick: function () {
170            var delta = 16 / 1000;
171            this.step(delta);
172
173            if (this.gameTick % 30 === 0) {
174                this.resetRandomBody();
175            }
176            // Note we call superclass's implementation after we're done
177            DemoBox2D.DemoServerGame.superclass.tick.call(this);
178        },
179
180        /**
181         * Resets an entity and drops it from the sky
182         */
183        resetRandomBody: function () {
184            // Retrieve a random key, and use it to retreive an entity
185            var allEntities = this.fieldController.getEntities();
186            var randomKeyIndex = Math.floor(Math.random() * allEntities._keys.length);
187            var entity = allEntities.objectForKey(allEntities._keys[randomKeyIndex]);
188
189            var x = Math.random() * DemoBox2D.Constants.GAME_WIDTH + DemoBox2D.Constants.ENTITY_BOX_SIZE;
190            var y = Math.random() * -15;
191            entity.getBox2DBody().SetPosition(new BOX2D.b2Vec2(x, y));
192        },
193
194        step: function (delta) {
195            this._world.ClearForces();
196//			var delta = (typeof delta == "undefined") ? 1/this._fps : delta;
197            this._world.Step(delta, delta * this._velocityIterationsPerSecond, delta * this._positionIterationsPerSecond);
198        },
199
200        shouldAddPlayer: function (aClientid, data) {
201//			this.createPlayerEntity( this.getNextEntityID(), aClientid);
202        },
203
204        /**
205         * @inheritDoc
206         */
207        shouldUpdatePlayer: function (aClientid, data) {
208            var pos = new BOX2D.b2Vec2(data.payload.x, data.payload.y);
209            pos.x /= DemoBox2D.Constants.PHYSICS_SCALE;
210            pos.y /= DemoBox2D.Constants.PHYSICS_SCALE;
211
212            // Loop through each entity, retrieve it's Box2D body, and apply an impulse towards the mouse position a user clicked
213            this.fieldController.getEntities().forEach(function (key, entity) {
214                var body = entity.getBox2DBody();
215                var bodyPosition = body.GetPosition();
216                var angle = Math.atan2(pos.y - bodyPosition.y, pos.x - bodyPosition.x);
217                var force = 20;
218                var impulse = new BOX2D.b2Vec2(Math.cos(angle) * force, Math.sin(angle) * force);
219                body.ApplyImpulse(impulse, bodyPosition);
220            }, this);
221        },
222
223        shouldRemovePlayer: function (aClientid) {
224//			DemoBox2D.DemoServerGame.superclass.shouldRemovePlayer.call( this, aClientid );
225//			console.log("DEMO::REMOVEPLAYER");
226        }
227    };
228
229    // extend RealtimeMultiplayerGame.AbstractServerGame
230    RealtimeMultiplayerGame.extend(DemoBox2D.DemoServerGame, RealtimeMultiplayerGame.AbstractServerGame, null);
231})()