Why does the frame's position change rapidly?

I’m making a panning script for my node-based editor but whenever I click the frame, its position changes even when the mouse isn’t moving?

Video example:

(It changes faster, the video is quite laggy)

Script:

local RunService = game:GetService('RunService')
local panButton = script.Parent.Pan

local down = false

panButton.MouseButton1Down:Connect(function()
	down = true
end)

panButton.MouseButton1Up:Connect(function()
	down = false
end)

RunService.Heartbeat:Connect(function()
	local mouse = game.Players.LocalPlayer:GetMouse()
	if down == true then
		
		local x = script.Parent.AbsolutePosition.X
		local y = script.Parent.AbsolutePosition.Y
		script.Parent.Position = UDim2.new(0,mouse.X-x,0,mouse.Y-y)
		
	end
end)

try adding wait(0.1) or some kind of delay to prevent it from being super fast if this does not work then experiment with the number in the wait time and figure out which one works the best

I’ve wrote some dummy code you could play around with. There might be something odd going on with the absolute values.

local frame = script.Parent

local inputService = game:GetService("UserInputService")
local runService = game:GetService("RunService")

local mouseDown = false
local mouseStartPos, startFramePos;

local player = game.Players.LocalPlayer

local function mouseOnFrame()
	local mousePos = player:GetMouse() 
	local frameSize = frame.AbsoluteSize
	local framePos = frame.AbsolutePosition
	
	return (mousePos.X > framePos.X and mousePos.X < framePos.X + frameSize.X)
		and (mousePos.Y > framePos.Y and mousePos.Y < framePos.Y + frameSize.Y)
end

inputService.InputBegan:Connect(function(input, gameProcessedEvent)
	if not gameProcessedEvent and input.UserInputType == Enum.UserInputType.MouseButton1 then
		if mouseOnFrame() then
			mouseStartPos = inputService:GetMouseLocation()
			startFramePos = frame.Position
			mouseDown = true
		end
	end
end)

inputService.InputEnded:Connect(function(input)
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		mouseDown = false
	end
end)

runService.RenderStepped:Connect(function()
	if mouseDown then
		local mouseDelta = inputService:GetMouseLocation() - mouseStartPos
		
		frame.Position = startFramePos + UDim2.fromOffset(mouseDelta.X, mouseDelta.Y)
	end
end)

I implemented it to use mouse delta instead, which might work better for your case. I’m not really sure.

1 Like