Hello! I am making a shooting game. On pc if you click on your screen something will shoot towards your mouse position. But on mobile i must use a button to fire it. But the bullet will fire towards the button instead of the middle because the mouse is on the button of course. I’ve tried to make it mouse locked but it doesn’t work. I also read this post but idk how to convert that into the middle of the screen.
Summarize: I want to know the CFrame of the world that the middle of a user’s screen is pointing at. THanks!!!
workspace.CurrentCamera.CFrame.LookVector will get you the lookvector
are you trying to get the part the player is looking at or the position the player is looking at?
A more complicated way is to get the camera screen size, get the middle by multiplying by 0.5 then using camera:ScreenPointToRay then use Ray.Origin. It’s the same which is pretty interesting.
local camera = workspace.CurrentCamera
local screenSize = camera.ViewportSize
local screenRay = camera:ScreenPointToRay(screenSize.X*0.5, screenSize.Y*0.5)
print(screenRay.Origin) --Both similar
--Or simply just
print(camera.CFrame.Position)
I had this same issue and was able to find a work around building off @ [dthecoolest] example using a “WorldToScreenPoint” and “ScreenPointToRay” methods.
local LEN_IN_STUDS = 100 --#how far we want to raycast from the center of the player's screen
-- getting pivot position
--_returning the screen location of camera's position (with a slight offset in-front)
local worldPoint = camera:WorldToScreenPoint(camera.CFrame.Position + camera.CFrame.LookVector * 2)
--_creating a ray object that points from the center of the screen outward
local unitRay = camera:ScreenPointToRay(worldPoint.X, worldPoint.Y)
-- raycasting from the center of the screen
local rayParams = RaycastParams.new()
rayParams.FilterType = Enum.RaycastFilterType.Exclude
rayParams.FilterDescendantsInstances = {camera, player.Character} -- #ignore the camera and the player's character
local rayRes = workspace:Raycast(unitRay.Origin, unitRay.Direction * LEN_IN_STUDS, rayParams)
-- final position
local posFromCenter = rayRes and rayRes.Position or unitRay.Origin + unitRay.Direction * LEN_IN_STUDS