From 2daf7712c22db4e3f3d0a040cec28d8a40fbaca9 Mon Sep 17 00:00:00 2001 From: vtxe02023274 <344562942+vtxe02023274@users.noreply.github.com> Date: Wed, 21 Oct 2026 11:21:18 +0800 Subject: [PATCH] Fix Camera worldView when the origin isn't 0.5 --- src/cameras/2d/Camera.js | 6 ++-- tests/cameras/2d/Camera.test.js | 49 +++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/cameras/2d/Camera.js b/src/cameras/2d/Camera.js index b38251d62d..28614e841a 100644 --- a/src/cameras/2d/Camera.js +++ b/src/cameras/2d/Camera.js @@ -606,8 +606,10 @@ var Camera = new Class({ var displayWidth = width / zoomX; var displayHeight = height / zoomY; - var vwx = midX - (displayWidth / 2); - var vwy = midY - (displayHeight / 2); + // Zoom is applied around the camera origin, so the top-left of the view + // only lines up with the middle of the camera when the origin is 0.5 + var vwx = sx + originX - (originX / zoomX); + var vwy = sy + originY - (originY / zoomY); this.worldView.setTo(vwx, vwy, displayWidth, displayHeight); diff --git a/tests/cameras/2d/Camera.test.js b/tests/cameras/2d/Camera.test.js index 1a02370319..7425b72463 100644 --- a/tests/cameras/2d/Camera.test.js +++ b/tests/cameras/2d/Camera.test.js @@ -6,4 +6,53 @@ describe('Camera', function () { expect(Camera).toBeDefined(); }); + + describe('worldView', function () + { + function makeCamera (originX, originY, zoom) + { + var camera = new Camera(0, 0, 800, 600); + + camera.setOrigin(originX, originY); + camera.setZoom(zoom); + camera.setScroll(100, 50); + camera.preRender(); + + return camera; + } + + function screenToWorld (camera, x, y) + { + var point = camera.matrix.applyInverse(x, y); + + return { x: point.x, y: point.y }; + } + + it('should be centered on the camera with the default origin', function () + { + var camera = makeCamera(0.5, 0.5, 2); + + expect(camera.worldView.x).toBe(300); + expect(camera.worldView.y).toBe(200); + expect(camera.worldView.width).toBe(400); + expect(camera.worldView.height).toBe(300); + }); + + it('should match the area the camera renders when the origin is not centered', function () + { + var origins = [ [ 0, 0 ], [ 1, 1 ], [ 0.25, 0.75 ] ]; + + for (var i = 0; i < origins.length; i++) + { + var camera = makeCamera(origins[i][0], origins[i][1], 3); + var topLeft = screenToWorld(camera, 0, 0); + var bottomRight = screenToWorld(camera, 800, 600); + + expect(camera.worldView.x).toBeCloseTo(topLeft.x); + expect(camera.worldView.y).toBeCloseTo(topLeft.y); + expect(camera.worldView.right).toBeCloseTo(bottomRight.x); + expect(camera.worldView.bottom).toBeCloseTo(bottomRight.y); + } + }); + }); });