Why are viewport/world camera functions offsetting the actual position?

local camera = workspace.CurrentCamera
local position = Vector3.new(0, 1, 0)

local screenPos = camera:WorldToViewportPoint(position)
local ray = camera:ViewportPointToRay(screenPos.X, screenPos.Y)
ray = Ray.new(ray.Origin, ray.Direction * screenPos.Z)

local newPosition = ray.Origin + ray.Direction

assert(position == newPosition) -- fails

What am I doing wrong here?

1 Like

this is very slightly off, you should round them up a little

local function round(a, b, e)
    return (a - b).Magnitude < e or 1e-5 -- change for more precision
end

No, it is not. I wrote an assertion here just to demonstrate the problem. You can replace it with

print(position, newPosition) -- 0, 1, 0 0, 0.6572456359863281, -2.537040948867798

And values will be not just slightly off, they are two absolutely different positions.

then it fails because theyre not equal

Yes! That’s the problem! Why are they not equal?

after some testing it appears to me that i cant figure out why, sorry! :sad:

1 Like

That’s unfortunate. :frowning: Thank you for your time anyways!

Turns out that something is wrong with depth recognition:

print((ray.Origin - position).Magnitude, screenPos.Z)

I think that this is a bug in the engine.
UPD: I’ve submitted a bug report.