Unwanted ScreenPointToRay vertical offset

Hello, working on a tycoon placement system!
Sorry but I don’t know the exact words to explain this(bad english issue), so if you have an idea then tell me and I’ll change the title!

This is a piece of my code:

local function DoRaycast()
	local mPos = UserInputService:GetMouseLocation()
	local ray = camera:ScreenPointToRay(mPos.X, mPos.Y)
	raycast = workspace:Raycast(ray.Origin, ray.Direction.Unit * 128)
	
	if raycast ~= nil then
		mouseHit = CFrame.new(raycast.Position, raycast.Position + ray.Direction)
	else
		mouseHit = CFrame.new(ray.Origin + ray.Direction*129)
	end
	p.CFrame = mouseHit
end

Any help would be appreciated!

ScreenPointToRay accounts for topbar inset and is offseted

While ViewportPointToRay does not account for topbar inset

Replace ScreenPointToRay to ViewportPointToRay

1 Like

local ray = camera:ScreenPointToRay(mPos.X, mPos.Y)

I often find that the offset of Y is due to the GUI offset.

local ray = camera:ScreenPointToRay(mPos.X, mPos.Y-50)

Or

local ray = camera:ScreenPointToRay(mPos.X, mPos.Y-36)

Often fixes this, just can’t remember if it’s negative or positive offset.

1 Like

UserInputService:GetMouseLocation() is calculated relative to top-left corner of the screen meaning negative Y is up while positive Y is down

1 Like

Probably because of the topbar like @SuperBlockUAlt said, his solution might work, I don’t know much about those functions, but I do know that there’s a difference between UIS:GetMousePosition() and (mouse.X, mouse.Y), so you can try using the mouse instead of UIS

1 Like

Aha I got it. It seems I mistook ViewportToRay for the Screen thing.
i can’t test right now, so I’ll do it tomorrow and mark it as solution if it works. Thank you everyone for helping!

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