UNPKG

blaze-2d

Version:

A fast and simple WebGL 2 2D game engine written in TypeScript

69 lines 1.93 kB
import { vec2 } from "gl-matrix"; import Object2D from "../object2d"; import Viewport from "./viewport"; /** * Represents the camera in 2D world space. * * The camera's position is the centre of the viewport. */ export default class Camera extends Object2D { /** * Creates a {@link Camera} instance. */ constructor(centre, vw, vh) { super(); this.zoomLevel = 1; this.minZoom = 0.1; this.maxZoom = 10; this.lastPos = vec2.create(); this.setPosition(centre); if (typeof vw === "number") { this.viewport = new Viewport(centre, vw, vh); } else { this.viewport = vw; } } /** * Updates the camera's viewport if the camera has changed position since the last call to update. */ update() { if (vec2.exactEquals(this.getPosition(), this.lastPos)) return; this.viewport.update(this.getPosition()); vec2.copy(this.lastPos, this.getPosition()); } /** * Zooms the camera by the given amount. * * @param zoom The amount to zoom by */ zoom(zoom) { const newZoom = this.zoomLevel + zoom; this.setZoom(newZoom); } /** * Sets the zoom level of the camera. * * This will change the size of `this.viewport`. * * @param zoom The zoom level */ setZoom(zoom) { // clamp zoom this.zoomLevel = Math.max(this.minZoom, Math.min(zoom, this.maxZoom)); const w = this.viewport.getOriginalWidth() / this.zoomLevel; const h = this.viewport.getOriginalHeight() / this.zoomLevel; this.viewport.setWidth(w); this.viewport.setHeight(h); } /** * Gets the zoom level of the camera. * * @returns The zoom level of the camera */ getZoom() { return this.zoomLevel; } } //# sourceMappingURL=camera.js.map