-
Notifications
You must be signed in to change notification settings - Fork 0
/
VRHelper.js
94 lines (77 loc) · 2.93 KB
/
VRHelper.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
/*jshint esversion: 11 */
// @ts-check
/**
* CS559 3D World Framework Code
*
* Enables entering VR in a GrWorld by clicking the "Enter VR" button.
* Includes basic flight mechanics using the VR controller.
*
* @module VRHelper
* */
import { XRControllerModelFactory } from '../CS559-Three/examples/jsm/webxr/XRControllerModelFactory.js';
import { VRButton } from '../CS559-Three/examples/jsm/webxr/VRButton.js';
import * as T from "../CS559-Three/build/three.module.js";
/** @class VRHelper
*
* Enables entering VR in a GrWorld by clicking the "Enter VR" button.
* Includes basic flight mechanics using the VR controller.
*
*/
export class VRHelper {
/**
* @param {Object} params
* @property params.renderer
* @property params.scene
* @property params.camera
* @property {Number} params.flightSpeed
*
*/
constructor(params = {}) {
this.renderer = params.renderer;
this.scene = params.scene;
this.camera = params.camera;
this.speed = params.flightSpeed ?? 10;
this.clock = new T.Clock();
this.flightDir = null;
this.renderer.xr.enabled = true;
document.body.appendChild(VRButton.createButton(this.renderer))
// right controller
this.controller = this.renderer.xr.getControllerGrip(0);
// add controller model to the scene
// const controllerModelFactory = new XRControllerModelFactory();
// const model1 = controllerModelFactory.createControllerModel(this.controller1);
// this.controller1.add(model1);
this.cameraGroup = new T.Group()
this.cameraGroup.add(this.camera)
this.cameraGroup.add(this.controller)
this.scene.add(this.cameraGroup)
// squeeze button is used to fly forwards
this.controller.addEventListener('squeezestart', () => {
// direction the camera is facing
const dir = this.renderer.xr.getCamera(this.camera).getWorldDirection(new T.Vector3(0,0,0));
this.flightDir = dir.normalize();
})
this.controller.addEventListener('squeezeend', () => {
this.flightDir = null;
})
// select button is used to fly backwards
this.controller.addEventListener('selectstart', () => {
// opposite of the direction the camera is facing
const dir = this.renderer.xr.getCamera(this.camera).getWorldDirection(new T.Vector3(0,0,0)).multiplyScalar(-1);
this.flightDir = dir.normalize();
})
this.controller.addEventListener('selectend', () => {
this.flightDir = null;
})
}
/**
* Updates and adds flight vector to current position
*/
update() {
const delta = this.clock.getDelta();
// don't fly if flight direction is null
if (this.flightDir) {
this.cameraGroup.position.addScaledVector(this.flightDir, this.speed * delta);
}
}
}