-
Notifications
You must be signed in to change notification settings - Fork 36
/
camera.py
89 lines (58 loc) · 2.18 KB
/
camera.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
import glm
import pygame as pg
FOV = 50 # deg
NEAR = 0.1
FAR = 100
SPEED = 0.005
SENSITIVITY = 0.04
class Camera:
def __init__(self, app, position=(0, 0, 4), yaw=-90, pitch=0):
self.app = app
self.aspect_ratio = app.WIN_SIZE[0] / app.WIN_SIZE[1]
self.position = glm.vec3(position)
self.up = glm.vec3(0, 1, 0)
self.right = glm.vec3(1, 0, 0)
self.forward = glm.vec3(0, 0, -1)
self.yaw = yaw
self.pitch = pitch
# view matrix
self.m_view = self.get_view_matrix()
# projection matrix
self.m_proj = self.get_projection_matrix()
def rotate(self):
rel_x, rel_y = pg.mouse.get_rel()
self.yaw += rel_x * SENSITIVITY
self.pitch -= rel_y * SENSITIVITY
self.pitch = max(-89, min(89, self.pitch))
def update_camera_vectors(self):
yaw, pitch = glm.radians(self.yaw), glm.radians(self.pitch)
self.forward.x = glm.cos(yaw) * glm.cos(pitch)
self.forward.y = glm.sin(pitch)
self.forward.z = glm.sin(yaw) * glm.cos(pitch)
self.forward = glm.normalize(self.forward)
self.right = glm.normalize(glm.cross(self.forward, glm.vec3(0, 1, 0)))
self.up = glm.normalize(glm.cross(self.right, self.forward))
def update(self):
self.move()
self.rotate()
self.update_camera_vectors()
self.m_view = self.get_view_matrix()
def move(self):
velocity = SPEED * self.app.delta_time
keys = pg.key.get_pressed()
if keys[pg.K_w]:
self.position += self.forward * velocity
if keys[pg.K_s]:
self.position -= self.forward * velocity
if keys[pg.K_a]:
self.position -= self.right * velocity
if keys[pg.K_d]:
self.position += self.right * velocity
if keys[pg.K_q]:
self.position += self.up * velocity
if keys[pg.K_e]:
self.position -= self.up * velocity
def get_view_matrix(self):
return glm.lookAt(self.position, self.position + self.forward, self.up)
def get_projection_matrix(self):
return glm.perspective(glm.radians(FOV), self.aspect_ratio, NEAR, FAR)