Skip to content

getCursorPosition

Type: Client-side

Pair: setCursorPosition

This function gets the current position of the mouse cursor. Note that for performance reasons, the world position returned is always 300 units away. If you want the exact world point (similar to onClientClick), use processLineOfSight between the camera position and the world x/y/z result of this function. (See example below)

This example prints your cursors current world coordinates and relative screen coordinates to chatbox after using /cursorpos command.

getCursorPosition-1.lua
function cursorInfo()
-- is the cursor showing?
if isCursorShowing() then
-- get the cursor postion
local screenx, screeny, worldx, worldy, worldz = getCursorPosition()
-- make the accuracy of floats 4 decimals and print to chatbox
outputChatBox( string.format( "Cursor screen position (relative): X=%.4f Y=%.4f", screenx, screeny ) )
outputChatBox( string.format( "Cursor world position: X=%.4f Y=%.4f Z=%.4f", worldx, worldy, worldz ) )
else
outputChatBox( "Your cursor is not showing." )
end
end
addCommandHandler( "cursorpos", cursorInfo )

This (untested) example uses processLineOfSight to calculate the exact world location: Warning, this script causes high CPU usage!

getCursorPosition-2.lua
addEventHandler( "onClientRender", root,
function()
-- is cursor showing?
if isCursorShowing() then
-- get cursor position
local screenx, screeny, worldx, worldy, worldz = getCursorPosition()
-- get our camera matrix/position
local px, py, pz = getCameraMatrix()
-- calculate the exact distance between cursor and camera
local hit, x, y, z, elementHit = processLineOfSight ( px, py, pz, worldx, worldy, worldz )
-- draw the distance on screen
dxDrawText( "Cursor at X:" .. x .. " Y:" .. y .. " Z:" .. z, 200, 200 )
-- if we got a collision detected and a valid element, draw it as well
if hit and elementHit then
dxDrawText( "Hit element " .. getElementType(elementHit), 200, 220 )
end
end
end
)