Moving block, not centered with mouse

Trying to make it so the part moves with the mouse, which works. But I just cant for the life of me get it centered on the mouse:

Code:

local gridSize = 2
local TweenService = game:GetService("TweenService")
local moveTween

runService.RenderStepped:Connect(function()
	if placementPart then
		local camera = workspace.CurrentCamera
		local mousePos = Vector2.new(mouse.X, mouse.Y)
		local ray = camera:ViewportPointToRay(mousePos.X, mousePos.Y)

		local raycastResult = workspace:Raycast(ray.Origin, ray.Direction * 500, rayParams)

		if raycastResult then
			local hitPos = raycastResult.Position

			-- Snap to 2 stud grid, centered
			local snappedX = math.floor(hitPos.X / gridSize + 0.5) * gridSize + gridSize/2
			local snappedY = math.floor(hitPos.Y / gridSize + 0.5) * gridSize
			local snappedZ = math.floor(hitPos.Z / gridSize + 0.5) * gridSize + gridSize/2

			local targetPosition = Vector3.new(snappedX, snappedY + 1, snappedZ)

			if moveTween then
				moveTween:Cancel()
			end

			local tweenInfo = TweenInfo.new(0.1, Enum.EasingStyle.Sine, Enum.EasingDirection.Out)
			moveTween = TweenService:Create(placementPart, tweenInfo, {Position = targetPosition})
			moveTween:Play()
		end
	end
end)
5 Likes

The way you set it up you are using studs. The mouse will never be center when using studs. There will always be an offset.

2 Likes

Yes that seems to be issue, I’m just trying to ensure that the ‘block’ is moved every 2 studs.

1 Like

Do you have to use studs, or do you just want to use studs?

1 Like

Well I don’t have to. I just wanted it so that the ‘block’ can only be moved and placed every 2 blocks.

1 Like

Its probably due to the mouse position being offset by the gui inset, which would get a value 58 pixels off, so the cast is being done by the wrong point. It looks like you’re using the legacy mouse X and Y properties - I don’t know if this one accounts for the gui inset. ViewPortToRay doesn’t account for gui inset, so if it is paired with something that does account for the offset, things can be off. Try replacing with ScreenPointToRay

3 Likes

Check first if the distance change from the mouse is greater than 2 studs in world.

2 Likes

Wait no nevermind i didn’t really see the whole problem

2 Likes

That was the issue! Thank you very much!

camera:ScreenPointToRay(mousePos.X, mousePos.Y) is used instead of camera:ViewportPointToRay(mousePos.X, mousePos.Y)

2 Likes