-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcam.py
90 lines (73 loc) · 2.65 KB
/
cam.py
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
TILE_W = 32
TILE_H = 32
SCR_W, SCR_H = 640, 360
SCROLL_SPEED = 4
SCROLL_ACCEL = 0.5
SCROLL_DECEL = 0.25
CAMERA_RADIUS_X = SCR_W / 4
CAMERA_RADIUS_Y = SCR_H / 4
class Cam:
def __init__(self):
self.pos_x = 0
self.pos_y = 0
self.dir_x = 0
self.dir_y = 0
def reset(self):
self.pos_x = 0
self.pos_y = 0
def gridToScreen(self, x, y):
return int(x * TILE_W - self.pos_x), int(y * TILE_H - self.pos_y)
def screenToGrid(self,x, y):
return int((x + self.pos_x) // TILE_W), int((y + self.pos_y) // TILE_H)
def worldToGrid(self,x, y):
return int(x // TILE_W), int(y // TILE_H)
def gridToWorld_tileCenter(self,x, y):
return int(x * TILE_W - self.pos_x + .5 * TILE_W), int(y * TILE_H - self.pos_y + .5 * TILE_H)
def worldToScreen(self, x, y):
return int(x - self.pos_x), int(y - self.pos_y)
def scroll(self, bounds, scroll_directions):
self.pos_x += scroll_directions[0] * SCROLL_SPEED
self.pos_y += scroll_directions[1] * SCROLL_SPEED
if self.pos_x < 0:
self.pos_x = 0
if self.pos_x > bounds[0] * TILE_W - SCR_W:
self.pos_x = bounds[0] * TILE_W - SCR_W
if self.pos_y < 0:
self.pos_y = 0
if self.pos_y > bounds[1] * TILE_H - SCR_H:
self.pos_y = bounds[1] * TILE_H - SCR_H
def followPos(self, x, y):
if self.pos_x + SCR_W / 2 + CAMERA_RADIUS_X < x:
self.dir_x += SCROLL_ACCEL
elif self.pos_x + SCR_W / 2 - CAMERA_RADIUS_X > x:
self.dir_x -= SCROLL_ACCEL
else:
# decelerate
if self.dir_x >= SCROLL_DECEL:
self.dir_x -= SCROLL_DECEL
elif self.dir_x <= -SCROLL_DECEL:
self.dir_x += SCROLL_DECEL
else:
self.dir_x = 0
if self.pos_y + SCR_H / 2 + CAMERA_RADIUS_Y < y:
self.dir_y += SCROLL_ACCEL
elif self.pos_y + SCR_H / 2 - CAMERA_RADIUS_Y > y:
self.dir_y -= SCROLL_ACCEL
else:
# decelerate
if self.dir_y >= SCROLL_DECEL:
self.dir_y -= SCROLL_DECEL
elif self.dir_y <= -SCROLL_DECEL:
self.dir_y += SCROLL_DECEL
else:
self.dir_y = 0
if self.dir_x > SCROLL_SPEED:
self.dir_x = SCROLL_SPEED
elif self.dir_x < -SCROLL_SPEED:
self.dir_x = -SCROLL_SPEED
if self.dir_y > SCROLL_SPEED:
self.dir_y = SCROLL_SPEED
elif self.dir_y < -SCROLL_SPEED:
self.dir_y = -SCROLL_SPEED
self.pos_x += self.dir_x
self.pos_y += self.dir_y