Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
FogNetwork
GitHub Repository: FogNetwork/Tsunami
Path: blob/main/public/games/files/garbage-collector/js/entities/camera.js
1036 views
1
/*globals define*/
2
define([
3
'entities/entity',
4
'utils'
5
], function( Entity, Utils ) {
6
'use strict';
7
8
function Camera( x, y, width, height ) {
9
Entity.call( this, x, y );
10
11
this.width = width || 64;
12
this.height = height || 48;
13
14
this.target = null;
15
this.margin = 0;
16
17
this.weight = 4;
18
}
19
20
Camera.prototype = new Entity();
21
Camera.prototype.constructor = Camera;
22
23
Camera.prototype.update = function( dt ) {
24
if ( !this.target || !this.world ) {
25
return;
26
}
27
28
var margin = this.margin;
29
30
var halfWidth = 0.5 * this.width,
31
halfHeight = 0.5 * this.height;
32
33
var left = -halfWidth,
34
top = -halfHeight,
35
right = halfWidth,
36
bottom = halfHeight;
37
38
// Target coordinates in local space.
39
var point = this.toLocal( this.target.x, this.target.y );
40
var x = point.x,
41
y = point.y;
42
43
// Recenter at a rate influenced by weight and dt.
44
var dx = this.weight * x * dt,
45
dy = this.weight * y * dt;
46
47
// Make sure the target stays within the margins.
48
if ( x < left + margin ) {
49
dx += x - ( left + margin );
50
} else if ( x > right - margin ) {
51
dx += x - ( right - margin );
52
}
53
54
if ( y < top + margin ) {
55
dy += y - ( top + margin );
56
} else if ( y > bottom - margin ) {
57
dy += y - ( bottom - margin );
58
}
59
60
var d = this.toWorld( dx, dy );
61
this.x = d.x;
62
this.y = d.y;
63
};
64
65
Camera.prototype.applyTransform = function( ctx ) {
66
ctx.translate( 0.5 * this.world.canvas.width, 0.5 * this.world.canvas.height );
67
ctx.scale( this.world.canvas.width / this.width, this.world.canvas.height / this.height );
68
ctx.rotate( this.angle );
69
ctx.translate( -this.x, -this.y );
70
};
71
72
Camera.prototype.drawPath = function( ctx ) {
73
var margin = this.margin;
74
75
var width = this.width,
76
height = this.height;
77
78
var halfWidth = 0.5 * width,
79
halfHeight = 0.5 * height;
80
81
ctx.beginPath();
82
ctx.rect( -halfWidth, -halfHeight, width, height );
83
ctx.rect( -halfWidth + margin, -halfHeight + margin, width - 2 * margin, height - 2 * margin );
84
ctx.closePath();
85
};
86
87
Camera.prototype.setHeight = function( height, options ) {
88
height = height || 1;
89
options = options || {};
90
91
var aspectRatio;
92
if ( options.maintainAspectRatio ) {
93
aspectRatio = this.width / this.height;
94
this.width = height * aspectRatio;
95
}
96
97
this.height = height;
98
};
99
100
Camera.prototype.aabb = function() {
101
var halfWidth = 0.5 * this.width,
102
halfHeight = 0.5 * this.height;
103
104
var left = -halfWidth,
105
top = -halfHeight,
106
right = halfWidth,
107
bottom = halfHeight;
108
109
return Utils.rotateAABB(
110
this.x, this.y,
111
left, top, right, bottom,
112
this.angle
113
);
114
};
115
116
return Camera;
117
});
118
119