ScrollingFrame automatically scrolling based on cursor position

I am working on a small coding game where you can control a little robot using a basic programming language. I’ve had a bit of trouble with making the GUI react to cursor changes properly.

I’ve tried a few methods using string.gsub to get the line the cursor is currently located at, and then ajust the canvas accodingly. But this is giving me alignment issues

local codeLabel = script.Parent.Code
local label = script.Parent

codeLabel:GetPropertyChangedSignal("CursorPosition"):Connect(function()
	local _, lineNum = codeLabel.Text:sub(1, codeLabel.CursorPosition):gsub("\n", "")
	local _, lineCount = codeLabel.Text:gsub("\n", "")
	
	local cursorPosition = lineNum/lineCount
	local canvasPositionTop = label.CanvasPosition.Y/label.AbsoluteCanvasSize.Y
	local canvasPositionBottom = (label.CanvasPosition.Y + label.AbsoluteSize.Y) / label.AbsoluteCanvasSize.Y
	
	if cursorPosition < canvasPositionTop then
		label.CanvasPosition = Vector2.new(0, lineNum * (label.AbsoluteCanvasSize.Y / lineCount))
	elseif cursorPosition >= canvasPositionBottom then
		label.CanvasPosition = Vector2.new(0, lineNum * (label.AbsoluteCanvasSize.Y / lineCount)) 
	end
end)


It is a bit hard to show on video, but when scrolling down there will always be one line invisible, same with scrolling up, it will stop at the second line instead of the first. i think this might be because of some rounding issues, but i’ve already tried a lot of tweaking and it never works.

I hope someone with a bit more coding experience would be able to help me out!

1 Like