Script to find part at the center of the screen

  1. What do you want to achieve? Detect what part is on the crosshair which I centered and is using ScreenInsets = none.
function raycast()
	local camera = workspace.CurrentCamera
	local viewportPoint = camera.ViewportSize / 2
	local unitRay = camera:ViewportPointToRay(viewportPoint.X, viewportPoint.Y, 0)
	local ray = Ray.new(unitRay.Origin, unitRay.Direction * canhitblockfromdistance)
	local part = workspace:FindPartOnRay(ray)
	return part
end
  1. What is the issue? It detects the part like 1/4th down the screen and in the middle for some reason instead of the middle on both axes

  2. What solutions have you tried so far? To be honest, not much really. Google really hasn’t been helpful with this extremely specific problem. It doesn’t make it easier that the testing process is kinda complex and annoying, having to use a real phone to play (the built-in Device feature in Studio literally lets the game lock my cursor to the center of the screen (bruh))

I have no idea why this problem arose. Can anyone help me, please?

You’re using a deprecated ray casting system. You should be using

local ray = workspace:Raycast(unitRay.Origin,unitRay.Direction * canhitblockfromdistance)
if ray then
   print(ray.Instance) — this should return a part detected by a ray fired from the centre 
end

Ok, so now it’s detecting parts at the top-right corner of the screen for some reason

That’s interesting…try this perhaps?

local unitRay = camera:ScreenPointToRay(viewportpoint.X, viewportpoint.Y)
local ray = workspace:Raycast(unitRay.Origin,unitRay.Direction * canhitblockfromdistance)
if ray then
   print(ray.Instance) — this should return a part detected by a ray fired from the centre 
end
1 Like

Didn’t you say ScreenInsets = none? So viewportpointtoray should’ve worked, since it doesn’t account for gui inset…

I’m pretty sure the problem is related to bad math or incorectly using functions rather than insets

Understood. I guess we both know that screenpointtoray is better :slight_smile:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.