Skip to content

Instantly share code, notes, and snippets.

@Necktrox
Last active July 20, 2018 22:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Necktrox/248033c7e1ffaa2387b2 to your computer and use it in GitHub Desktop.
Save Necktrox/248033c7e1ffaa2387b2 to your computer and use it in GitHub Desktop.
-- Camera state
local cameraEnabled = false
-- Camera radius
local sphereRadius = 5
-- Cursor sensitivity
local sensitivity = 100
-- Field of view
local fov = 90
-- Horizontal angle in degree
local angleH = 85
-- Vertical angle in degree
local angleV = 90
function getCameraPositionOffset(h, v)
-- Transform degrees to radians
local radV = math.rad(v)
local radH = math.rad(h)
-- Calculate these values only once
local sinH = math.sin(radH)
local sphereRadiusXY = sphereRadius * sinH
-- Calculate camera position on sphere around the local player
local x = math.sin(radV) * sphereRadiusXY
local y = math.cos(radV) * sphereRadiusXY
local z = math.cos(radH) * sphereRadius + 1.0
-- Create the vector for the position offset
return Vector3(x, y, z)
end
local cameraPositionOffset = getCameraPositionOffset(angleH, angleV)
function setCameraEnabled(enabled)
enabled = enabled and true or false
if cameraEnabled == enabled then
return false
end
if cameraEnabled then
removeEventHandler("onClientCursorMove", root, onClientCursorMove)
removeEventHandler("onClientPreRender", root, onClientPreRender)
else
addEventHandler("onClientCursorMove", root, onClientCursorMove)
addEventHandler("onClientPreRender", root, onClientPreRender)
end
cameraEnabled = enabled
return true
end
function isCameraEnabled()
return cameraEnabled
end
function onClientCursorMove(cursorX, cursorY)
-- Calculate the cursor distance
local cursorDistanceX = (cursorX - 0.5) * sensitivity
local cursorDistanceY = (0.5 - cursorY) * sensitivity
-- Calculate the new vertical angle
angleV = (angleV + cursorDistanceX) % 360
-- Calculate the new horizontal angle
angleH = math.min(179, math.max(1, angleH + cursorDistanceY))
-- Update the position offset vector
cameraPositionOffset = getCameraPositionOffset(angleH, angleV)
end
function onClientPreRender()
-- Get the current position of the local player
local position = localPlayer:getPosition()
-- Calculate the camera positions
local cameraLookAt = position + Vector3(0, 0, 0.75)
local cameraPosition = position + cameraPositionOffset
-- Apply the camera matrix
Camera.setMatrix(cameraPosition, cameraLookAt, 0, fov)
end
addCommandHandler("togglecamera",
function ()
-- Toggle the current camera state
setCameraEnabled(not isCameraEnabled())
end
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment