1 import { System
} from '@serpentity/serpentity';
2 import { Engine
, World
} from 'matter-js';
4 import PhysicalNode
from '../nodes/physical';
5 import GrabAreaNode
from '../nodes/grab_area';
8 kNoEngine: 'No matter js physics engine found. Make sure you set the `engine` key in the config object when initializing.'
12 * Adds and removes objects to the physics world and calls update
14 * @extends {external:Serpentity.System}
15 * @class PhysicsWorldControlSystem
16 * @param {object} config a configuration object to extend.
18 export default class PhysicsWorldControlSystem
extends System
{
20 constructor(config
= {}) {
25 * The node collection of physics entities
27 * @property {external:Serpentity.NodeCollection} physicalEntities
29 * @memberof PhysicsWorldControlSystem
31 this.physicalEntities
= null;
34 * The matter-js engine we will use to process physics
36 * @property {external:MatterJs.Engine} engine
38 * @memberof PhysicsWorldControlSystem
40 this.engine
= config
.engine
;
43 throw new Error(internals
.kNoEngine
);
48 * Initializes system when added. Requests physics nodes and
49 * attaches to event listeners to add / remove them to pixi stage
52 * @memberof PhysicsWorldControlSystem
54 * @param {external:Serpentity.Engine} engine the serpentity engine to
55 * which we are getting added
59 this.physicalEntities
= engine
.getNodes(PhysicalNode
);
60 this.grabAreaEntities
= engine
.getNodes(GrabAreaNode
);
62 this.physicalEntities
.on('nodeAdded', (event
) => {
64 World
.add(this.engine
.world
, [event
.node
.body
.body
]);
66 this.physicalEntities
.on('nodeRemoved', (event
) => {
68 World
.remove(this.engine
.world
, [event
.node
.body
.body
]);
71 this.grabAreaEntities
.on('nodeAdded', (event
) => {
73 World
.add(this.engine
.world
, [event
.node
.grabArea
.area
]);
75 this.grabAreaEntities
.on('nodeRemoved', (event
) => {
77 World
.remove(this.engine
.world
, [event
.node
.grabArea
.area
]);
82 * Clears system resources when removed.
86 * @memberof PhysicsWorldControlSystem
90 this.physicalEntities
.removeAllListeners('nodeAdded');
91 this.physicalEntities
.removeAllListeners('nodeRemoved');
92 this.physicalEntities
= null;
94 this.grabAreaEntities
.removeAllListeners('nodeAdded');
95 this.grabAreaEntities
.removeAllListeners('nodeRemoved');
96 this.grabAreaEntities
= null;
100 * Runs on every update of the loop. Updates the physics
104 * @param {Number} currentFrameDuration the duration of the current
106 * @memberof PhysicsWorldControlSystem
108 update(currentFrameDuration
) {
110 Engine
.update(this.engine
, currentFrameDuration
);