System.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. require('KeyboardInput');
  2. class System {
  3. constructor() {
  4. this.container = null;
  5. this.canvas = null;
  6. this.contextType = '2d';
  7. this.contextAttributes = {};
  8. this.context = null;
  9. this.system = null;
  10. this.theater = null;
  11. this.backgroundColor = "#D3D3D3";
  12. this.framerate = 60;
  13. this.lastTime = 0;
  14. this.keyboard = null;
  15. }
  16. create(elementName, gameObject, defaultBackgroundColor) {
  17. this.theater = gameObject;
  18. this.backgroundColor = defaultBackgroundColor || this.backgroundColor;
  19. this.keyboard = new KeyboardInput();
  20. this.keyboard.attach();
  21. this.container = document.getElementById(elementName);
  22. this.canvas = document.createElement("canvas");
  23. this.container.appendChild(this.canvas);
  24. window.addEventListener('resize', (event) => this.handleResize(event));
  25. this.theater.init(this, this.container, this.canvas);
  26. this.handleResize(null);
  27. window.requestAnimationFrame(() => this.handleRequestAnimationFrame());
  28. }
  29. handleResize(event) {
  30. this.canvas.width = this.container.offsetWidth;
  31. this.canvas.height = this.container.offsetHeight;
  32. this.context = this.canvas.getContext(this.contextType, this.contextAttributes);
  33. this.context.translate(0.5, 0.5);
  34. this.theater.handleResize(() => this.canvas());
  35. }
  36. handleRequestAnimationFrame(event) {
  37. var currentTime = new Date().getTime();
  38. var delta = (currentTime - this.lastTime) / (1000 / this.framerate);
  39. if (delta > 100) {
  40. delta = (1000 / this.framerate);
  41. }
  42. this.theater.updateDelta(delta, this.canvas);
  43. this.lastTime = currentTime;
  44. this.context.fillStyle = this.backgroundColor;
  45. this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
  46. this.theater.draw(this.context);
  47. window.requestAnimationFrame(() => this.handleRequestAnimationFrame());
  48. }
  49. formatFloat(val) {
  50. if (Number.isNaN(parseFloat(val))) {
  51. return 0;
  52. }
  53. return parseFloat(val.toFixed(6));
  54. }
  55. distanceTo(source, target) {
  56. return this.formatFloat(Math.sqrt(Math.pow(target.x - source.x, 2) + Math.pow(target.y - source.y, 2)));
  57. }
  58. angleTo(source, target) {
  59. return this.formatFloat(Math.atan2(target.y - source.y, target.x - source.x));
  60. }
  61. }