diff --git a/src/core/environment.js b/src/core/environment.js index fb8b56c0f5..2e2c87959c 100644 --- a/src/core/environment.js +++ b/src/core/environment.js @@ -1137,6 +1137,48 @@ function exitFullscreen() { } } + +/** + * Converts 3D world coordinates to 2D screen coordinates. + * + * This function takes a 3D vector and converts its coordinates + * from the world space to screen space. This is useful for placing + * 2D elements in a 3D scene or for determining the screen position + * of 3D objects. + * + * @method worldToScreen + * @param {p5.Vector} worldPosition The 3D coordinates in the world space. + * @return {p5.Vector} A vector containing the 2D screen coordinates. + * @example + *
+ * + * + *
+ * + */ +p5.prototype.worldToScreen = function(worldPosition) { + const renderer = this._renderer; + if (renderer.drawingContext instanceof CanvasRenderingContext2D) { + // Handle 2D context + const transformMatrix = new DOMMatrix() + .scale(1 / pixelDensity()) + .multiply(renderer.drawingContext.getTransform()); + const screenCoordinates = transformMatrix.transformPoint( + new DOMPoint(worldPosition.x, worldPosition.y)); + return createVector(screenCoordinates.x, screenCoordinates.y); + } else{ + // Handle WebGL context + const cameraCoordinates = renderer.uMVMatrix.multiplyPoint(worldPosition); + const normalizedDeviceCoordinates = + renderer.uPMatrix.multiplyAndNormalizePoint(cameraCoordinates); + const screenX = (0.5 + 0.5 * normalizedDeviceCoordinates.x) * this.width; + const screenY = (0.5 - 0.5 * normalizedDeviceCoordinates.y) * this.height; + const screenZ = (0.5 + 0.5 * normalizedDeviceCoordinates.z); + return createVector(screenX, screenY, screenZ); + } +}; + + /** * Returns the sketch's current * URL