1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- require('KeyboardInput');
- class System {
- constructor() {
- this.container = null;
- this.canvas = null;
- this.contextType = '2d';
- this.contextAttributes = {};
- this.context = null;
- this.system = null;
- this.theater = null;
- this.backgroundColor = "#D3D3D3";
- this.framerate = 60;
- this.lastTime = 0;
- this.keyboard = null;
- }
- create(elementName, gameObject, defaultBackgroundColor) {
- this.theater = gameObject;
- this.backgroundColor = defaultBackgroundColor || this.backgroundColor;
- this.keyboard = new KeyboardInput();
- this.keyboard.attach();
- this.container = document.getElementById(elementName);
- this.canvas = document.createElement("canvas");
- this.container.appendChild(this.canvas);
- window.addEventListener('resize', (event) => this.handleResize(event));
- this.theater.init(this, this.container, this.canvas);
- this.handleResize(null);
- window.requestAnimationFrame(() => this.handleRequestAnimationFrame());
- }
- handleResize(event) {
- this.canvas.width = this.container.offsetWidth;
- this.canvas.height = this.container.offsetHeight;
- this.context = this.canvas.getContext(this.contextType, this.contextAttributes);
- this.context.translate(0.5, 0.5);
- this.theater.handleResize(() => this.canvas());
- }
- handleRequestAnimationFrame(event) {
- var currentTime = new Date().getTime();
- var delta = (currentTime - this.lastTime) / (1000 / this.framerate);
- if (delta > 100) {
- delta = (1000 / this.framerate);
- }
- this.theater.updateDelta(delta, this.canvas);
- this.lastTime = currentTime;
- this.context.fillStyle = this.backgroundColor;
- this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
- this.theater.draw(this.context);
- window.requestAnimationFrame(() => this.handleRequestAnimationFrame());
- }
- formatFloat(val) {
- if (Number.isNaN(parseFloat(val))) {
- return 0;
- }
- return parseFloat(val.toFixed(6));
- }
- distanceTo(source, target) {
- return this.formatFloat(Math.sqrt(Math.pow(target.x - source.x, 2) + Math.pow(target.y - source.y, 2)));
- }
- angleTo(source, target) {
- return this.formatFloat(Math.atan2(target.y - source.y, target.x - source.x));
- }
- }
|