Skip to content

screenToWorld & worldToScreen camera rect #7816

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 3, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions src/scene/camera.js
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,7 @@ class Camera {
}

/**
* Convert a point from 3D world space to 2D canvas pixel space.
* Convert a point from 3D world space to 2D canvas pixel space based on the camera's rect.
*
* @param {Vec3} worldCoord - The world space coordinate to transform.
* @param {number} cw - The width of PlayCanvas' canvas element.
Expand All @@ -550,14 +550,20 @@ class Camera {
worldCoord.z * vpm[11] +
1 * vpm[15];

screenCoord.x = (screenCoord.x / w + 1) * 0.5 * cw;
screenCoord.y = (1 - screenCoord.y / w) * 0.5 * ch;
// convert normalized clip space to screen space [0, 1]
screenCoord.x = (screenCoord.x / w + 1) * 0.5;
screenCoord.y = (1 - screenCoord.y / w) * 0.5;

// convert screen space [0, 1] to pixel space based on camera rect
const { x: rx, y: ry, z: rw, w: rh } = this._rect;
screenCoord.x = screenCoord.x * rw * cw + rx * cw;
screenCoord.y = screenCoord.y * rh * ch + (1 - ry - rh) * ch;

return screenCoord;
}

/**
* Convert a point from 2D canvas pixel space to 3D world space.
* Convert a point from 2D canvas pixel space to 3D world space based on the camera's rect.
*
* @param {number} x - X coordinate on PlayCanvas' canvas element.
* @param {number} y - Y coordinate on PlayCanvas' canvas element.
Expand All @@ -568,10 +574,14 @@ class Camera {
* @returns {Vec3} The world space coordinate.
*/
screenToWorld(x, y, z, cw, ch, worldCoord = new Vec3()) {

// Calculate the screen click as a point on the far plane of the normalized device coordinate 'box' (z=1)
const { x: rx, y: ry, z: rw, w: rh } = this._rect;
const range = this.farClip - this.nearClip;
_deviceCoord.set(x / cw, (ch - y) / ch, z / range);
_deviceCoord.set(
(x - rx * cw) / (rw * cw),
1 - (y - (1 - ry - rh) * ch) / (rh * ch),
z / range
);
_deviceCoord.mulScalar(2);
_deviceCoord.sub(Vec3.ONE);

Expand Down