-
Notifications
You must be signed in to change notification settings - Fork 0
/
camera.js
66 lines (57 loc) · 2.13 KB
/
camera.js
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
function setupCamera (opts) {
var currentAngle = opts.initialAngle * (Math.PI / 180);
var dtheta = opts.turnRate * (Math.PI / 180); // degrees per turn
var dist = opts.speed; // distance per step
var camera = {
pos: opts.initialPos || vec3.fromValues(0, 0, 0), // position of the camera
look: vec3.fromValues(0, 0, 1), // position its looking at
};
function getLookDir () {
// update the direction we're looking based on currentAngle
var lookX = Math.cos(currentAngle) * dist;
var lookY = Math.sin(currentAngle) * dist;
return vec3.fromValues(lookX, 0, lookY);
}
function updateCamera (lookDir) {
// set the camera position to 1 unit ahead of where we're looking
vec3.add(camera.look, camera.pos, lookDir);
}
window.addEventListener('keydown', function (event) {
if (opts.disableMovement)
return;
var keyCode = event.keyCode;
// first handle changes to the currentAngle
switch (keyCode) {
case 68: //d
currentAngle += dtheta;
break;
case 65: //a
currentAngle -= dtheta;
break;
}
var lookDir = getLookDir();
// move forward or backward based on the current lookDir. if strafing,
// move in the direction of lookDir rotated 90 degrees left/right
switch (keyCode) {
case 87: //w
vec3.add(camera.pos, camera.pos, lookDir);
break;
case 83: //s
var invLookDir = vec3.create();
vec3.negate(invLookDir, lookDir);
vec3.add(camera.pos, camera.pos, invLookDir);
break;
case 81: //q
var rotLeftLookDir = vec3.fromValues(lookDir[2], 0, -lookDir[0]);
vec3.add(camera.pos, camera.pos, rotLeftLookDir);
break;
case 69: //e
var rotRightLookDir = vec3.fromValues(-lookDir[2], 0, lookDir[0]);
vec3.add(camera.pos, camera.pos, rotRightLookDir);
break;
}
updateCamera(lookDir);
}, false);
updateCamera(getLookDir());
return camera;
}