BlueGit

timfa raytracer

Files

raytracer / src / player.js

player.js

player.js 2.3 KiB Download Raw
1var Player =
2{
3 x: 0,
4 y: 0,
5 rotation: 0,
6 pitch: 0,
7 /** Screen columns per frame. 240 is sharp on ~1080p and cheap (~240 drawSprite calls). */
8 horizontalResolution: 240,
9 gunX: 0.6,
10 gunY: 0.6,
11 currentGun: 0,
12 guns: 3,
13
14 resetToSpawn: function ()
15 {
16 var spawn = World.spawnPoint();
17 this.x = spawn.x;
18 this.y = spawn.y;
19 this.rotation = spawn.yaw != null ? spawn.yaw : 0;
20 this.pitch = 0;
21 },
22
23 applyLookDelta: function (movementX, movementY)
24 {
25 this.pitch += movementY * 0.01;
26 this.rotation += movementX * 0.001;
27 if (this.pitch > Math.PI)
28 { this.pitch = Math.PI; }
29 if (this.pitch < -Math.PI)
30 { this.pitch = -Math.PI; }
31 if (this.rotation > Math.PI * 2)
32 { this.rotation -= Math.PI * 2; }
33 if (this.rotation < 0)
34 { this.rotation += Math.PI * 2; }
35 },
36
37 /** Legacy angles: 0 = +X (east), increases toward +Y. */
38 forwardVector: function (radian)
39 {
40 return { x: Math.cos(radian), y: Math.sin(radian) };
41 },
42
43 tryMove: function (rot, speed, deltaTime)
44 {
45 if (World.rayCast(this.x, this.y, rot).distance <= 5)
46 { return; }
47 var forward = this.forwardVector(rot);
48 this.x += forward.x * deltaTime * speed;
49 this.y += forward.y * deltaTime * speed;
50 },
51
52 update: function (deltaTime)
53 {
54 if (GameInput.isHeld(37) || GameInput.isHeld(65))
55 {
56 var rotL = this.rotation - Math.PI / 2;
57 if (rotL < 0) { rotL += Math.PI * 2; }
58 this.tryMove(rotL, 60, deltaTime);
59 }
60 if (GameInput.isHeld(39) || GameInput.isHeld(68))
61 {
62 var rotR = this.rotation + Math.PI / 2;
63 if (rotR > Math.PI * 2) { rotR -= Math.PI * 2; }
64 this.tryMove(rotR, 60, deltaTime);
65 }
66 if (GameInput.isHeld(38) || GameInput.isHeld(87))
67 { this.tryMove(this.rotation, 60, deltaTime); }
68 if (GameInput.isHeld(40) || GameInput.isHeld(83))
69 {
70 var rotB = this.rotation + Math.PI;
71 if (rotB > Math.PI * 2) { rotB -= Math.PI * 2; }
72 if (World.rayCast(this.x, this.y, rotB).distance > 5)
73 {
74 var forward = this.forwardVector(this.rotation);
75 this.x -= forward.x * deltaTime * 40;
76 this.y -= forward.y * deltaTime * 40;
77 }
78 }
79 if (GameInput.isHeld(188))
80 {
81 this.horizontalResolution -= this.horizontalResolution * 0.1 * deltaTime;
82 if (this.horizontalResolution < 30)
83 { this.horizontalResolution = 30; }
84 }
85 if (GameInput.isHeld(190))
86 {
87 this.horizontalResolution += this.horizontalResolution * 0.1 * deltaTime;
88 }
89 }
90};