Mouse Position to Pixel position is inaccurate

Hey,
im trying to work with EdibleImages and coloring the exact pixel that I’m clicking on. However it is pretty inaccurate, the pixel appears a bit below where I actually clicked. Does anyone see an issue with this code?

local function screenToPixelPosition(screenPosition, buttonSize, imageSize)
	local buttonX, buttonY = buttonSize.X, buttonSize.Y --AbsoluteSize in pixels
	local imageX, imageY = imageSize.X, imageSize.Y 

	-- Calculating the normalized position (0 to 1) within the button
	local normX = (screenPosition.X - script.Parent.AbsolutePosition.X) / buttonX
	local normY = (screenPosition.Y - script.Parent.AbsolutePosition.Y) / buttonY

	-- Converting to pixel coordinates in the image
	local pixelX = math.floor(normX * imageX)
	local pixelY = math.floor(normY * imageY)

	
	pixelX = math.clamp(pixelX, 0, imageX - 1)
	pixelY = math.clamp(pixelY, 0, imageY - 1)

	return Vector2.new(pixelX, pixelY)
end```

Are you accounting for topbar inset?

1 Like

No, how would I do that? That might be the issue

GuiInset occupies 36 pixels at the top of the screen, where the Roblox exit game icon is located. However, the Mouse:GetMouseLocation() function also takes these 36 pixels into account, which can lead to incorrect calculations. To fix this, you can simply subtract 36 pixels from the screen height when working with mouse coordinates

1 Like

Also use:

GuiService:GetGuiInset()
1 Like

Yeah, we used to hardcode that value of 36, but since the topbar changed, it is no longer 36, it might be 44 or 48 (or both, for mobile and desktop? idk)

:GetGuiInset() will give you the right value

2 Likes

Thank you, works perfectly now!

2 Likes

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