]> git.r.bdr.sh - rbdr/sumo/blame_incremental - lib/systems/physics_world_control.js
Draw the Arena (#7)
[rbdr/sumo] / lib / systems / physics_world_control.js
... / ...
CommitLineData
1import { System } from '@serpentity/serpentity';
2import { Engine, World } from 'matter-js';
3
4import PhysicalNode from '../nodes/physical';
5
6const internals = {
7 kNoEngine: 'No matter js physics engine found. Make sure you set the `engine` key in the config object when initializing.'
8};
9
10/**
11 * Adds and removes objects to the physics world and calls update
12 *
13 * @extends {external:Serpentity.System}
14 * @class PhysicsWorldControlSystem
15 * @param {object} config a configuration object to extend.
16 */
17export default class PhysicsWorldControlSystem extends System {
18
19 constructor(config = {}) {
20
21 super();
22
23 /**
24 * The node collection of physics entities
25 *
26 * @property {external:Serpentity.NodeCollection} physicalEntities
27 * @instance
28 * @memberof PhysicsWorldControlSystem
29 */
30 this.physicalEntities = null;
31
32 /**
33 * The matter-js engine we will use to process physics
34 *
35 * @property {external:MatterJs.Engine} engine
36 * @instance
37 * @memberof PhysicsWorldControlSystem
38 */
39 this.engine = config.engine;
40
41 if (!this.engine) {
42 throw new Error(internals.kNoEngine);
43 }
44 }
45
46 /**
47 * Initializes system when added. Requests physics nodes and
48 * attaches to event listeners to add / remove them to pixi stage
49 *
50 * @function added
51 * @memberof PhysicsWorldControlSystem
52 * @instance
53 * @param {external:Serpentity.Engine} engine the serpentity engine to
54 * which we are getting added
55 */
56 added(engine) {
57
58 this.physicalEntities = engine.getNodes(PhysicalNode);
59 this.physicalEntities.on('nodeAdded', (event) => {
60
61 World.add(this.engine.world, [event.node.body.body]);
62 });
63 this.physicalEntities.on('nodeRemoved', (event) => {
64
65 World.remove(this.engine.world, [event.node.body.body]);
66 });
67 }
68
69 /**
70 * Clears system resources when removed.
71 *
72 * @function removed
73 * @instance
74 * @memberof PhysicsWorldControlSystem
75 */
76 removed() {
77
78 this.physicalEntities.removeAllListeners('nodeAdded');
79 this.physicalEntities.removeAllListeners('nodeRemoved');
80 this.physicalEntities = null;
81 }
82
83 /**
84 * Runs on every update of the loop. Updates the physics
85 *
86 * @function update
87 * @instance
88 * @param {Number} currentFrameDuration the duration of the current
89 * frame
90 * @memberof PhysicsWorldControlSystem
91 */
92 update(currentFrameDuration) {
93
94 Engine.update(this.engine, currentFrameDuration);
95 }
96};
97
98