image.png
Reply chain from #49
local function projectToScreen(x, y, z, userPos, lookVector)
local dx = x - userPos[1]
local dy = -(y - userPos[2])
local dz = z - userPos[3]
local lx, ly, lz = lookVector[1], lookVector[2], lookVector[3]
local playerYaw = math.deg(math.atan2(lz, lx))
local playerPitch = math.deg(math.asin(-ly))
playerYaw = playerYaw + 90
if playerYaw < 0 then
playerYaw = playerYaw + 360
end
-- Calculate yaw difference
local targetYaw = math.deg(math.atan2(dz, dx)) + 90
if targetYaw < 0 then
targetYaw = targetYaw + 360
end
local yawDiff = targetYaw - playerYaw
if yawDiff > 180 then
yawDiff = yawDiff - 360
elseif yawDiff < -180 then
yawDiff = yawDiff + 360
end
if math.abs(yawDiff) > 90 then
return nil, nil
end
-- Calculate pitch difference
local distXY = math.sqrt(dx * dx + dz * dz)
local targetPitch = math.deg(math.atan2(dy, distXY))
local pitchDiff = targetPitch - playerPitch
local screenDepth = screenWidth / 2 * math.tan(math.rad(fov / 1.125 / 2))
local verticalScreenDepth = screenHeight * math.tan(math.rad(fov / 2))
local projectedX, projectedY
if yawDiff > 0 then
projectedX = screenWidth / 2 + screenDepth * math.tan(math.rad(math.abs(yawDiff)))
else
projectedX = screenWidth / 2 - screenDepth * math.tan(math.rad(math.abs(yawDiff)))
end
if pitchDiff > 0 then
projectedY = screenHeight / 2 + screenHeight * math.tan(math.rad(fov / 0.95 / 2)) * math.tan(math.rad(math.abs(pitchDiff)))
else
projectedY = screenHeight / 2 - screenHeight * math.tan(math.rad(fov / 1.05 / 2)) * math.tan(math.rad(math.abs(pitchDiff)))
end
projectedX = math.floor(projectedX / magicNumber)
projectedY = math.floor(projectedY / magicNumber) + 20
return projectedX, projectedY
end
This conversation is on Discord · Reply there