diff --git a/game/Camera.js b/game/Camera.js index 17cd883..d1f25e1 100644 --- a/game/Camera.js +++ b/game/Camera.js @@ -28,27 +28,32 @@ export default class Camera { this.y += y / this.zoom } - setZoom(newzoom) { + setZoom(newzoom, centerCoordViewport) { const zoom = Math.min(Math.max(newzoom, this.minZoom), this.maxZoom) if (zoom == this.zoom) { return false } - // centered zoom - // TODO: mouse-centered-zoom - this.x -= Math.round(((this.width / this.zoom) - (this.width / zoom)) / 2) - this.y -= Math.round(((this.height / this.zoom) - (this.height / zoom)) / 2) + const zoomToCoord = center || { + x: this.width / 2, + y: this.height / 2 + } + const zoomFactor = (1 / this.zoom) - (1 / zoom) + + this.x -= Math.round(zoomToCoord.x * zoomFactor) + this.y -= Math.round(zoomToCoord.y * zoomFactor) this.zoom = zoom + return true } - zoomOut() { - return this.setZoom(this.zoom - this.zoomStep * this.zoom) + zoomOut(centerCoordViewport) { + return this.setZoom(this.zoom - this.zoomStep * this.zoom, centerCoordViewport) } - zoomIn() { - return this.setZoom(this.zoom + this.zoomStep * this.zoom) + zoomIn(centerCoordViewport) { + return this.setZoom(this.zoom + this.zoomStep * this.zoom, centerCoordViewport) } /** diff --git a/game/game.js b/game/game.js index 8b5d91b..1fc9169 100644 --- a/game/game.js +++ b/game/game.js @@ -564,14 +564,14 @@ async function main() { } else if (type === Protocol.INPUT_EV_MOUSE_UP) { _last_mouse_down = null } else if (type === Protocol.INPUT_EV_ZOOM_IN) { - if (viewport.zoomIn()) { - const pos = { x: evt[1], y: evt[2] } + const pos = { x: evt[1], y: evt[2] } + if (viewport.zoomIn(viewport.worldToViewport(pos))) { RERENDER = true Game.changePlayer(gameId, CLIENT_ID, pos) } } else if (type === Protocol.INPUT_EV_ZOOM_OUT) { - if (viewport.zoomOut()) { - const pos = { x: evt[1], y: evt[2] } + const pos = { x: evt[1], y: evt[2] } + if (viewport.zoomOut(viewport.worldToViewport(pos))) { RERENDER = true Game.changePlayer(gameId, CLIENT_ID, pos) } @@ -607,10 +607,12 @@ async function main() { } else if (type === Protocol.INPUT_EV_MOUSE_UP) { _last_mouse_down = null } else if (type === Protocol.INPUT_EV_ZOOM_IN) { - viewport.zoomIn() + const pos = { x: evt[1], y: evt[2] } + viewport.zoomIn(viewport.worldToViewport(pos)) RERENDER = true } else if (type === Protocol.INPUT_EV_ZOOM_OUT) { - viewport.zoomOut() + const pos = { x: evt[1], y: evt[2] } + viewport.zoomOut(viewport.worldToViewport(pos)) RERENDER = true } }