aboutsummaryrefslogtreecommitdiff
path: root/lib/systems/camera_rotator.js
blob: 5cf66df656db5c2a15baa1180de6cead05546b63 (plain)
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
import { mat4, vec3 } from 'gl-matrix';
import { System } from '@serpentity/serpentity';
import Cameras from '../nodes/cameras';

/**
  * Rotates the camera around a "sphere"
  */
export default class CameraRotator extends System {

  constructor() {

    super();
  }

  added(engine){

    this.cameras = engine.getNodes(Cameras);
  }

  removed(){

    delete this.cameras;
  }

  update(dt){

    for (const camera of this.cameras) {

      let rotationMatrix = mat4.create();
      mat4.rotateY(rotationMatrix, rotationMatrix, camera.angle.yaw);
      mat4.rotateX(rotationMatrix, rotationMatrix, camera.angle.pitch);
      mat4.rotateZ(rotationMatrix, rotationMatrix, camera.angle.roll);

      let eye = vec3.fromValues(0, 0, camera.radius.radius);
      vec3.transformMat4(eye, eye, rotationMatrix);

      camera.position.x = eye[0];
      camera.position.y = eye[1];
      camera.position.z = eye[2];

      let up = vec3.fromValues(0, 1, 0);
      vec3.transformMat4(up, up, rotationMatrix);
      camera.up.x = up[0];
      camera.up.y = up[1];
      camera.up.z = up[2];

      camera.angle.pitch = (camera.angle.pitch + camera.velocity.x * dt / 500 + 2 * Math.PI) % (2 * Math.PI);
      camera.angle.yaw = (camera.angle.yaw + camera.velocity.y * dt / 500 + 2 * Math.PI) % (2 * Math.PI);
      camera.angle.roll = (camera.angle.roll + camera.velocity.z * dt / 500 + 2 * Math.PI) % (2 * Math.PI);
    }
  }
};