Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
FogNetwork
GitHub Repository: FogNetwork/Tsunami
Path: blob/main/public/games/files/garbage-collector/js/effects/shake.js
1036 views
1
/*globals define*/
2
define([
3
'utils'
4
], function( Utils ) {
5
'use strict';
6
7
function Shake() {
8
this.magnitude = 0;
9
this.duration = 0;
10
11
this.time = 0;
12
13
// Variables pertaining to the current shake cycle.
14
// Change shake angle at frequency (20 fps).
15
this.shakePeriod = 1 / 20;
16
this.shakeTime = 0;
17
this.shakeMagnitude = 0;
18
this.shakeAngle = 0;
19
}
20
21
Shake.prototype.applyTransform = function( ctx ) {
22
if ( !this.magnitude ) {
23
return;
24
}
25
26
ctx.translate(
27
Math.cos( this.shakeAngle ) * this.shakeMagnitude,
28
Math.sin( this.shakeAngle ) * this.shakeMagnitude
29
);
30
};
31
32
Shake.prototype.update = function( dt ) {
33
if ( !this.magnitude ) {
34
return;
35
}
36
37
this.time += dt;
38
if ( this.time > this.duration ) {
39
this.magnitude = 0;
40
this.time = 0;
41
return;
42
}
43
44
this.shakeTime += dt;
45
// A new oscillation!
46
if ( this.shakeTime > this.shakePeriod ) {
47
this.shakeTime = 0;
48
this.shakeAngle = Math.random() * Utils.PI2;
49
50
// Lerp scale magnitude down to zero.
51
var scale = ( this.duration - this.time ) / this.duration;
52
this.shakeMagnitude = this.magnitude * scale;
53
}
54
};
55
56
Shake.prototype.shake = function( magnitude, duration ) {
57
this.magnitude = magnitude || 0;
58
this.duration = duration || 0;
59
60
this.update(0);
61
};
62
63
Object.defineProperty( Shake.prototype, 'frequency', {
64
get: function() {
65
return 1 / this.shakePeriod;
66
},
67
68
set: function( frequency ) {
69
this.shakePeriod = 1 / frequency;
70
}
71
});
72
73
return Shake;
74
});
75
76