How to get 3d position from middle of screen

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!!!

2 Likes

You can use the cameras lookvector to cast a ray, and then use the position of the result

how to use the camera’s lookvector? Oh and by the way I need the CFrame of the part, not the position

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?

the CFrame of the position the player is looking at

where exactly is said cframe meant to be facing

You can just do camera.CFrame.Position

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)
1 Like

I had the same issue with my placement module v3. I solved it using this method.

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 

Attached is an example using an image button


.