system.js 2.0 KB

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