1 import { System
} from '@serpentity/serpentity';
2 import { Engine
, World
} from 'matter-js';
4 import PhysicalNode
from '../nodes/physical';
7 kNoEngine: 'No matter js physics engine found. Make sure you set the `engine` key in the config object when initializing.'
11 * Adds and removes objects to the physics world and calls update
13 * @extends {external:Serpentity.System}
14 * @class PhysicsWorldControlSystem
15 * @param {object} config a configuration object to extend.
17 export default class PhysicsWorldControlSystem
extends System
{
19 constructor(config
= {}) {
24 * The node collection of physics entities
26 * @property {external:Serpentity.NodeCollection} physicalEntities
28 * @memberof PhysicsWorldControlSystem
30 this.physicalEntities
= null;
33 * The matter-js engine we will use to process physics
35 * @property {external:MatterJs.Engine} engine
37 * @memberof PhysicsWorldControlSystem
39 this.engine
= config
.engine
;
42 throw new Error(internals
.kNoEngine
);
47 * Initializes system when added. Requests physics nodes and
48 * attaches to event listeners to add / remove them to pixi stage
51 * @memberof PhysicsWorldControlSystem
53 * @param {external:Serpentity.Engine} engine the serpentity engine to
54 * which we are getting added
58 this.physicalEntities
= engine
.getNodes(PhysicalNode
);
59 this.physicalEntities
.on('nodeAdded', (event
) => {
61 World
.add(this.engine
.world
, [event
.node
.body
.body
]);
63 this.physicalEntities
.on('nodeRemoved', (event
) => {
65 World
.remove(this.engine
.world
, [event
.node
.body
.body
]);
70 * Clears system resources when removed.
74 * @memberof PhysicsWorldControlSystem
78 this.physicalEntities
.removeAllListeners('nodeAdded');
79 this.physicalEntities
.removeAllListeners('nodeRemoved');
80 this.physicalEntities
= null;
84 * Runs on every update of the loop. Updates the physics
88 * @param {Number} currentFrameDuration the duration of the current
90 * @memberof PhysicsWorldControlSystem
92 update(currentFrameDuration
) {
94 Engine
.update(this.engine
, currentFrameDuration
);