I am trying to essentially get the position in the 3D space of the center of your screen, similar to Mouse.hit.p but always locked in the center.
You’re looking for Camera:ScreenPointToRay
. Here’s the documentation:
A quick implementation (given that the current documentation is a bit dated and uses the legacy FindPartOnRay
):
local currentCamera = workspace.CurrentCamera
local raycastParams = RaycastParams.new()
-- raycastParams.FilterDescendantsInstances = { character } <-- fill this in yourself
local VIEWPORT_SIZE = currentCamera.ViewportSize -- current size of the screen -- if you're raycasting multiple times, this will have to be redefined!
local CAST_LENGTH = 1000 -- distance to raycast
local unitRay = currentCamera:ScreenPointToRay(VIEWPORT_SIZE.X / 2, VIEWPORT_SIZE.Y / 2 + game:GetService("GuiService"):GetGuiInset().Y) -- account for the 36px TopBar inset
local raycastResult = workspace:Raycast(unitRay.Origin, unitRay.Direction * CAST_LENGTH, raycastParams)
if raycastResult and raycastResult.Position then -- .Position is the Vector3 (the Hit.Position) of the center of the screen
-- example operation:
local part = Instance.new("Part")
part.Anchored = true
part.Size = Vector3.new(1, 1, 1)
part.CFrame = CFrame.new(raycastResult.Position)
part.Parent = workspace
end
Hope this solves your problem.
9 Likes
Works perfectly! Thank you so much.
I made a few edits to it because you should be accounting for the CoreGui inset and some of my math was a bit sloppily done (and, uh… incorrect). The code now should create an accurate representation of the middle of the screen not including the Topbar, but if what I created before works well enough, so be it!
I’d encourage you to take a look at it, however. Happy scripting.
1 Like