-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
314 lines (256 loc) · 7.97 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
// CUSTOM BEHAVIOUR
Physics.behavior('demo-mouse-events', function( parent ){ return {
init: function( options ){
var self = this;
this.mousePos = Physics.vector();
this.mousePosOld = Physics.vector();
this.offset = Physics.vector();
var offset = options.el.getBoundingClientRect();
this.el = options.el;
this.el.addEventListener('mousedown', function(e){
self.mousePos.set(e.pageX - offset.left, e.pageY - offset.top);
var body = self._world.findOne({ $at: self.mousePos }) ;
if ( body ){
// we're trying to grab a body
// fix the body in place
body.fixed = true;
// remember the currently grabbed body
self.body = body;
// remember the mouse offset
self.offset.clone( self.mousePos ).vsub( body.state.pos );
return;
}
self.mouseDown = true;
});
this.el.addEventListener('mousemove', function(e){
self.mousePosOld.clone( self.mousePos );
self.mousePos.set(e.pageX - offset.left, e.pageY - offset.top);
});
this.el.addEventListener('mouseup', function(e){
self.mousePosOld.clone( self.mousePos );
self.mousePos.set(e.pageX - offset.left, e.pageY - offset.top);
// release the body
if (self.body){
self.body.fixed = false;
self.body = false;
}
self.mouseDown = false;
});
},
connect: function( world ){
// subscribe the .behave() method to the position integration step
world.on('integrate:positions', this.behave, this);
},
disconnect: function( world ){
// unsubscribe when disconnected
world.off('integrate:positions', this.behave);
},
behave: function( data ){
if ( this.body ){
// if we have a body, we need to move it the the new mouse position.
// we'll also track the velocity of the mouse movement so that when it's released
// the body can be "thrown"
this.body.state.pos.clone( this.mousePos )
.vsub( this.offset );
this.body.state.vel.clone( this.body.state.pos )
.vsub( this.mousePosOld )
.vadd( this.offset )
.mult( 1 / 30 );
this.body.state.vel.clamp( { x: -1, y: -1 }, { x: 1, y: 1 } );
return;
}
if ( !this.mouseDown ) return;
// if we don't have a body, then just accelerate
// all bodies towards the current mouse position
var bodies = data.bodies,
// use a scratchpad to speed up calculations
scratch = Physics.scratchpad(),
v = scratch.vector(),
body;
// for (var i = 0, l = bodies.length; i < l; ++i) {
// body = bodies[ i ];
//
// // simple linear acceleration law towards the mouse position
// v.clone(this.mousePos)
// .vsub( body.state.pos )
// .normalize()
// .mult( 0.001 );
//
// body.accelerate( v );
// }
scratch.done();
}
}});
// CUSTOM SVG RENDERER
Physics.renderer('svg', function( proto ){ return {
/**
* Initialization
* @param {Object} options Config options passed by initializer
* @return {void}
*/
init: function( options ){
// call proto init
proto.init.call(this, options);
var containerDims = options.el.getBoundingClientRect();
this.svgCanvas = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
this.svgCanvas.setAttribute(
'style',
`width:${containerDims.width};
height: ${containerDims.height};`
);
options.el.appendChild(this.svgCanvas);
},
/**
* Create a dom element for the specified geometry
* @param {Geometry} geometry The body's geometry
* @return {HTMLElement} The element
*/
createView: function( geometry){
var aabb = geometry.aabb();
var rect = document.createElementNS('http://www.w3.org/2000/svg', "rect");
rect.setAttribute('width', 40 + 'px');
rect.setAttribute('height', 40 + 'px');
rect.setAttribute('fill', '#87ceeb');
this.svgCanvas.appendChild(rect);
return rect;
},
/**
* Connect to world. Automatically called when added to world by the setWorld method
* @param {Object} world The world to connect to
* @return {void}
*/
connect: function( world ){
world.on( 'add:body', this.attach, this );
world.on( 'remove:body', this.detach, this );
},
/**
* Disconnect from world
* @param {Object} world The world to disconnect from
* @return {void}
*/
disconnect: function( world ){
world.off( 'add:body', this.attach );
world.off( 'remove:body', this.detach );
},
/**
* Detach a node from the DOM
* @param {HTMLElement|Object} data DOM node or event data (data.body)
* @return {self}
*/
detach: function( data ){
// interpred data as either dom node or event data
var el = (data.nodeType && data) || (data.body && data.body.view),
par = el && el.parentNode;
// remove view from dom
if (el && par)
par.removeChild( el );
return this;
},
/**
* Attach a node to the viewport
* @param {HTMLElement|Object} data DOM node or event data (data.body)
* @return {self}
*/
attach: function( data ){
// interpret data as either dom node or event data
var el = (data.nodeType && data) || (data.body && data.body.view);
if (el){
// attach to viewport
this.svgCanvas.appendChild(el);
}
return this;
},
/**
* Draw the meta data
* @param {Object} meta The meta data
* @return {void}
*/
drawMeta: function( meta ){},
drawBody: function( body, view ) {
var pos = body.state.pos;
view.setAttribute('x', pos.get(0));
view.setAttribute('y', pos.get(1));
},
}});
// PREPARE AND INITIALISE WORLD
var containerDims = {
w: 800,
h: 400,
};
var svgContainer = document.querySelector('.js-svg-canvas-container');
svgContainer.setAttribute(
'style',
`border: 1px solid skyblue;
width: ${containerDims.w}px;
height: ${containerDims.h}px;
`
);
document.body.appendChild(svgContainer);
// world declaration
var world = Physics();
// creation of the renderer which will draw the world
var renderer = Physics.renderer("svg",{
el: svgContainer,
width: containerDims.w,
height: containerDims.h,
meta: false,
});
// adding the renderer to the world
world.add(renderer);
// what happens at every iteration step? We render (show the world)
world.on("step", function(){ world.render(); });
// this is the default gravity
var gravity = Physics.behavior("constant-acceleration",{
acc: {
x: 0,
y: 0.0004,
},
});
// adding gravity to the world
world.add(gravity);
world.add(Physics.behavior('demo-mouse-events', { el: svgContainer }));
// adding collision detection with canvas edges
world.add(Physics.behavior("edge-collision-detection", {
aabb: Physics.aabb(0, 0, containerDims.w, containerDims.h),
restitution: 0
}));
// bodies will react to forces such as gravity
world.add(Physics.behavior("body-impulse-response"));
// enabling collision detection among bodies
world.add(Physics.behavior("body-collision-detection"));
world.add(Physics.behavior('body-impulse-response'));
world.add(Physics.behavior('verlet-constraints'));
world.add(Physics.behavior("sweep-prune"));
svgContainer.addEventListener('click', function(e){
// checking canvas coordinates for the mouse click
var offset = this.getBoundingClientRect();
var px = e.pageX - offset.left;
var py = e.pageY - offset.top;
// this is the way physicsjs handles 2d vectors, similar at Box2D's b2Vec
var mousePos = Physics.vector();
mousePos.set(px,py);
// finding a body under mouse position
var body = world.findOne({
$at: mousePos
})
// there isn't any body under mouse position, going to create a new box
if(!body){
var bod = Physics.body('rectangle',{
x: px,
y: py,
width: 40,
height: 40,
}, {
color:'#FF0000',
});
world.add(bod);
} else {
// there is a body under mouse position, let's remove it
world.removeBody(body);
}
});
// handling timestep
Physics.util.ticker.on(function(time,dt){
world.step(time);
});
Physics.util.ticker.start();