xonecas.ioDon't click! Sean Caetano Martin Sign in
tiny-adventure / web / js / camera.js 90 lines2.5 kB Raw
1import * as THREE from '../vendor/three.module.js';
2
3export function createCamera(canvas) {
4  const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 400);
5  const target = new THREE.Vector3();
6  const goal = new THREE.Vector3();
7  let yaw = 0.35;
8  let pitch = 0.95;
9  let dist = 17;
10  let goalDist = 17;
11  let focus = null;
12  let drag = null;
13  let trauma = 0;
14  let spin = 0;
15
16  canvas.addEventListener('contextmenu', (e) => e.preventDefault());
17  canvas.addEventListener('wheel', (e) => {
18    goalDist = THREE.MathUtils.clamp(goalDist * (e.deltaY > 0 ? 1.1 : 0.9), 6, 34);
19    e.preventDefault();
20  }, { passive: false });
21  canvas.addEventListener('pointerdown', (e) => {
22    if (e.button !== 0) drag = { x: e.clientX, y: e.clientY };
23  });
24  addEventListener('pointermove', (e) => {
25    if (!drag) return;
26    yaw -= (e.clientX - drag.x) * 0.006;
27    pitch = THREE.MathUtils.clamp(pitch + (e.clientY - drag.y) * 0.004, 0.35, 1.3);
28    drag = { x: e.clientX, y: e.clientY };
29  });
30  addEventListener('pointerup', () => (drag = null));
31  addEventListener('keydown', (e) => {
32    if (e.key === 'q') yaw += 0.2;
33    if (e.key === 'e') yaw -= 0.2;
34  });
35
36  function resize(w, h) {
37    camera.aspect = w / h;
38    camera.zoom = THREE.MathUtils.clamp(camera.aspect / 1.3, 0.55, 1);
39    camera.updateProjectionMatrix();
40  }
41
42  function follow(pos) {
43    goal.copy(pos);
44  }
45
46  function setFocus(pos, d) {
47    focus = pos ? { pos, d } : null;
48  }
49
50  function shake(amount) {
51    trauma = Math.min(1, trauma + amount);
52  }
53
54  function orbit(speed) {
55    spin = speed;
56  }
57
58  function update(dt) {
59    yaw += spin * dt;
60    const k = 1 - Math.exp(-dt * 4);
61    target.lerp(focus ? focus.pos : goal, k);
62    dist += ((focus ? focus.d : goalDist) - dist) * k;
63    camera.position.set(
64      target.x + Math.sin(yaw) * Math.cos(pitch) * dist,
65      target.y + Math.sin(pitch) * dist,
66      target.z + Math.cos(yaw) * Math.cos(pitch) * dist
67    );
68    camera.lookAt(target);
69    if (trauma > 0) {
70      const a = trauma * trauma * 0.25;
71      camera.position.x += (Math.random() * 2 - 1) * a;
72      camera.position.y += (Math.random() * 2 - 1) * a;
73      trauma = Math.max(0, trauma - dt * 2.5);
74    }
75  }
76
77  function snap(pos) {
78    target.copy(pos);
79    goal.copy(pos);
80  }
81
82  function screenOf(obj, lift = 1.5) {
83    const v = obj.position.clone();
84    v.y += lift * obj.scale.y;
85    v.project(camera);
86    return [(v.x * 0.5 + 0.5) * innerWidth, (-v.y * 0.5 + 0.5) * innerHeight];
87  }
88
89  return { camera, resize, follow, setFocus, update, snap, shake, orbit, screenOf };
90}