-
Notifications
You must be signed in to change notification settings - Fork 0
/
controls.js
117 lines (94 loc) · 2.47 KB
/
controls.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
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
var mouse_down = false;
var mouse_left = false;
var last_cursor_x = 0;
var last_cursor_y = 0;
function onMouseWheel(evt)
{
evt.preventDefault();
var delta = 0;
if(evt.detail){ //support for Firefox
delta = -evt.detail/3;
} else if(evt.wheelDelta){ //support for chrome,safari and opera
delta = evt.wheelDelta/120;
}
}
function getMousePos(evt)
{
// returns mouse position relative to the Canvas
rect = canvas.getBoundingClientRect();
var x = evt.clientX - rect.left;
var y = evt.clientY - rect.top;
y = canvas.height - y; //invert the value of y
return {x:x,y:y};
}
function onMouseClick(evt)
{
var cursor_pos = getMousePos(evt);
last_cursor_x = cursor_pos.x;
last_cursor_y = cursor_pos.y;
mouse_down = true;
if(evt.button == 0){
mouse_left = true;
}
}
function onMouseRelease(evt)
{
mouse_down = false;
}
function onMouseMove(evt)
{
//if(!in_game)
//else
if(!mouse_down)
return;
if(mouse_left)
{
var cursor_pos = getMousePos(evt);
var dx = (last_cursor_x - cursor_pos.x);
var dy = (last_cursor_y - cursor_pos.y);
//TODO move camera
var rot_angle;
rot_angle = dx*(180.0/canvas.width);
renderHub.camera.rotate((rot_angle*3.14)/180.0,[0.0,1.0,0.0]);
rot_angle = -dy*(90.0/canvas.height);
renderHub.camera.rotate((rot_angle*3.14)/180.0,renderHub.camera.getRightVector());
last_cursor_x = cursor_pos.x;
last_cursor_y = cursor_pos.y;
}
}
function onKeyDown(evt)
{
console.log("Key pressed");
var tVec = vec3.create();
switch (evt.keyCode) {
case 65: // a
tVec = renderHub.camera.getRightVector();
vec3.scale(tVec,tVec,-0.1);
renderHub.camera.translate(tVec);
break;
case 87: // w
tVec = renderHub.camera.getFrontVector();
vec3.scale(tVec,tVec,0.1);
renderHub.camera.translate(tVec);
break;
case 68: // d
tVec = renderHub.camera.getRightVector();
vec3.scale(tVec,tVec,0.1);
renderHub.camera.translate(tVec);
break;
case 83: // s
tVec = renderHub.camera.getFrontVector();
vec3.scale(tVec,tVec,-0.1);
renderHub.camera.translate(tVec);
break;
}
}
function registerEvents(){
canvas.addEventListener('mousedown',onMouseClick,false);
canvas.addEventListener('mouseup',onMouseRelease,false);
canvas.addEventListener('mousemove',onMouseMove,false);
canvas.addEventListener('DOMMouseScroll',onMouseWheel,false);
canvas.addEventListener('mousewheel',onMouseWheel,false);
//TODO add event listener for keyboard
canvas.addEventListener('keydown',onKeyDown,false);
}