]> git.r.bdr.sh - rbdr/sumo/blob - lib/systems/elastic.js
Fix positioning and lessen friction (#8)
[rbdr/sumo] / lib / systems / elastic.js
1 import { System } from '@serpentity/serpentity';
2
3 const internals = {
4 kTightStiffness: 0.001,
5 kBaseStiffness: 0.0008,
6 kLooseStiffness: 0.0000001
7 };
8
9 import ElasticNode from '../nodes/elastic';
10
11 /**
12 Changes the stiffness on the node when it's less extended
13 *
14 * @extends {external:Serpentity.System}
15 * @class ElasticSystem
16 * @param {object} config a configuration object to extend.
17 */
18 export default class ElasticSystem extends System {
19
20 constructor(config = {}) {
21
22 super();
23
24 /**
25 * The node collection of entities that have external force
26 *
27 * @property {external:Serpentity.NodeCollection} elastics
28 * @instance
29 * @memberof ElasticSystem
30 */
31 this.elastics = null;
32 }
33
34 /**
35 * Initializes system when added. Requests elastic nodes
36 *
37 * @function added
38 * @memberof ElasticSystem
39 * @instance
40 * @param {external:Serpentity.Engine} engine the serpentity engine to
41 * which we are getting added
42 */
43 added(engine) {
44
45 this.elastics = engine.getNodes(ElasticNode);
46 }
47
48 /**
49 * Clears system resources when removed.
50 *
51 * @function removed
52 * @instance
53 * @memberof ElasticSystem
54 */
55 removed() {
56
57 this.elastics = null;
58 }
59
60 /**
61 * Runs on every update of the loop. Checks length of elastic and adjusts
62 * stiffness
63 *
64 * @function update
65 * @instance
66 * @param {Number} currentFrameDuration the duration of the current
67 * frame
68 * @memberof ElasticSystem
69 */
70 update(currentFrameDuration) {
71
72 for (const elastic of this.elastics) {
73 const constraint = elastic.body.body;
74
75 const currentDistance = Math.abs(
76 Math.sqrt(
77 Math.pow(constraint.bodyA.position.x - constraint.bodyB.position.x, 2) +
78 Math.pow(constraint.bodyA.position.y - constraint.bodyB.position.y, 2)));
79
80 if (currentDistance <= constraint.length) {
81 constraint.stiffness = internals.kLooseStiffness;
82 continue;
83 }
84
85 if (currentDistance >= 2.6 * constraint.length) {
86 constraint.stiffness = internals.kTightStiffness;
87 continue;
88 }
89
90 constraint.stiffness = internals.kBaseStiffness;
91 }
92 }
93 };