game.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
  2. import { WEBGL } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/WebGL.js';
  3. import { OrbitControls } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/controls/OrbitControls.js';
  4. import {graphics} from './graphics.js';
  5. export const game = (function() {
  6. return {
  7. Game: class {
  8. constructor() {
  9. this._Initialize();
  10. }
  11. _Initialize() {
  12. this._graphics = new graphics.Graphics(this);
  13. if (!this._graphics.Initialize()) {
  14. this._DisplayError('WebGL2 is not available.');
  15. return;
  16. }
  17. this._controls = this._CreateControls();
  18. this._previousRAF = null;
  19. this._OnInitialize();
  20. this._RAF();
  21. }
  22. _CreateControls() {
  23. const controls = new OrbitControls(
  24. this._graphics._camera, this._graphics._threejs.domElement);
  25. controls.target.set(0, 0, 0);
  26. controls.update();
  27. return controls;
  28. }
  29. _DisplayError(errorText) {
  30. const error = document.getElementById('error');
  31. error.innerText = errorText;
  32. }
  33. _RAF() {
  34. requestAnimationFrame((t) => {
  35. if (this._previousRAF === null) {
  36. this._previousRAF = t;
  37. }
  38. this._Render(t - this._previousRAF);
  39. this._previousRAF = t;
  40. });
  41. }
  42. _Render(timeInMS) {
  43. const timeInSeconds = timeInMS * 0.001;
  44. this._OnStep(timeInSeconds);
  45. this._graphics.Render(timeInSeconds);
  46. this._RAF();
  47. }
  48. }
  49. };
  50. })();