Skip to content

Render - World to screen #97

@aglitchman

Description

@aglitchman

Describe the example you'd like
Add a good example for the world to screen conversion function.

Additional context (optional)
Just throwing out ideas before the upcoming Hacktoberfest!

Lua code to start:

--- Converts a world position to screen coordinates.
-- This function transforms a 3D world position to 2D screen coordinates using the camera's
-- view and projection matrices. The resulting coordinates are in screen space where (0,0)
-- is the bottom-left corner of the screen.
--
-- @param world_position vector3 The world position to convert.
-- @param camera_url url|string The camera component URL to use for the transformation.
-- @return number screen_x The X coordinate in screen space.
-- @return number screen_y The Y coordinate in screen space.
-- @return number screen_z Always returns 0 (depth information is not preserved).
function M.world_to_screen(world_position, camera_url)
    local proj = camera.get_projection(camera_url)
    local view = camera.get_view(camera_url)

    local view_proj = proj * view
    local scr_coord = view_proj * vmath.vector4(world_position.x, world_position.y, world_position.z, 1)
    local w, h = window.get_size()
    scr_coord.x = (scr_coord.x / scr_coord.w + 1) * 0.5 * w
    scr_coord.y = (scr_coord.y / scr_coord.w + 1) * 0.5 * h

    return scr_coord.x, scr_coord.y, 0
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions