-
Notifications
You must be signed in to change notification settings - Fork 1
/
camera.ts
92 lines (83 loc) · 2.98 KB
/
camera.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
namespace kodu {
export class Camera extends Component {
camera_movement_x: number;
camera_movement_y: number;
x: number;
y: number;
following: Character;
public get pos(): Vec2 { return mkVec2(this.x, this.y); }
public set pos(v: Vec2) { this.x = v.x; this.y = v.y; }
constructor(stage: Stage) {
super(stage, "camera");
this.x = scene.cameraProperty(CameraProperty.X);
this.y = scene.cameraProperty(CameraProperty.Y);
}
public setScreenRelativePosition(k: SpriteLike, x: number, y: number) {
const s = k as any;
s.x = scene.cameraProperty(CameraProperty.X) - scene.screenWidth() / 2 + x + this.camera_movement_x;
s.y = scene.cameraProperty(CameraProperty.Y) - scene.screenHeight() / 2 + y + this.camera_movement_y;
}
public moveTo(x: number, y: number) {
this.x = x;
this.y = y;
scene.centerCameraAt(this.x, this.y);
}
public follow(char: Character) {
this.following = char;
}
prepare() {
this.following = null;
}
update(dt: number) {
this.camera_movement_x = 0;
this.camera_movement_y = 0;
if (this.following) {
this.keepInFrame(this.following.x, this.following.y);
} else {
const interest = this.stage.get<Vec2>("point-of-interest");
if (interest) {
this.keepInFrame(interest.x, interest.y);
}
}
}
keepInFrame(x: number, y: number) {
const cameraStep = this.stage.get<number>("camera-step") || 1;
const camX = this.x;
const camY = this.y;
let nxtX = camX;
let nxtY = camY;
const dx = x - camX;
const dy = y - camY;
if (dx < -80) {
nxtX = x + 80 + cameraStep;
}
if (dx >= 80) {
nxtX = x - 80 + cameraStep;
}
if (dy < -60) {
nxtY = y + 60 + cameraStep;
}
if (dy >= 60) {
nxtY = y - 60 + cameraStep;
}
this.x = nxtX;
this.y = nxtY;
this.camera_movement_x = this.x - camX;
this.camera_movement_y = this.y - camY;
scene.centerCameraAt(this.x, this.y);
}
notify(event: string, parm: any) {
if (event === "save") {
const savedGame = parm as SavedGame;
savedGame.camera.x = this.x;
savedGame.camera.y = this.y;
} else if (event === "load") {
this.following = null;
const savedGame = parm as SavedGame;
this.x = savedGame.camera.x;
this.y = savedGame.camera.y;
scene.centerCameraAt(this.x, this.y);
}
}
}
}