Path: blob/main/public/games/files/garbage-collector/js/entities/camera.js
1036 views
/*globals define*/1define([2'entities/entity',3'utils'4], function( Entity, Utils ) {5'use strict';67function Camera( x, y, width, height ) {8Entity.call( this, x, y );910this.width = width || 64;11this.height = height || 48;1213this.target = null;14this.margin = 0;1516this.weight = 4;17}1819Camera.prototype = new Entity();20Camera.prototype.constructor = Camera;2122Camera.prototype.update = function( dt ) {23if ( !this.target || !this.world ) {24return;25}2627var margin = this.margin;2829var halfWidth = 0.5 * this.width,30halfHeight = 0.5 * this.height;3132var left = -halfWidth,33top = -halfHeight,34right = halfWidth,35bottom = halfHeight;3637// Target coordinates in local space.38var point = this.toLocal( this.target.x, this.target.y );39var x = point.x,40y = point.y;4142// Recenter at a rate influenced by weight and dt.43var dx = this.weight * x * dt,44dy = this.weight * y * dt;4546// Make sure the target stays within the margins.47if ( x < left + margin ) {48dx += x - ( left + margin );49} else if ( x > right - margin ) {50dx += x - ( right - margin );51}5253if ( y < top + margin ) {54dy += y - ( top + margin );55} else if ( y > bottom - margin ) {56dy += y - ( bottom - margin );57}5859var d = this.toWorld( dx, dy );60this.x = d.x;61this.y = d.y;62};6364Camera.prototype.applyTransform = function( ctx ) {65ctx.translate( 0.5 * this.world.canvas.width, 0.5 * this.world.canvas.height );66ctx.scale( this.world.canvas.width / this.width, this.world.canvas.height / this.height );67ctx.rotate( this.angle );68ctx.translate( -this.x, -this.y );69};7071Camera.prototype.drawPath = function( ctx ) {72var margin = this.margin;7374var width = this.width,75height = this.height;7677var halfWidth = 0.5 * width,78halfHeight = 0.5 * height;7980ctx.beginPath();81ctx.rect( -halfWidth, -halfHeight, width, height );82ctx.rect( -halfWidth + margin, -halfHeight + margin, width - 2 * margin, height - 2 * margin );83ctx.closePath();84};8586Camera.prototype.setHeight = function( height, options ) {87height = height || 1;88options = options || {};8990var aspectRatio;91if ( options.maintainAspectRatio ) {92aspectRatio = this.width / this.height;93this.width = height * aspectRatio;94}9596this.height = height;97};9899Camera.prototype.aabb = function() {100var halfWidth = 0.5 * this.width,101halfHeight = 0.5 * this.height;102103var left = -halfWidth,104top = -halfHeight,105right = halfWidth,106bottom = halfHeight;107108return Utils.rotateAABB(109this.x, this.y,110left, top, right, bottom,111this.angle112);113};114115return Camera;116});117118119