Is there a better way of doing a carousel UI?

I have this rudimentary carousel UI thing going on for a character selection/purchase shop that I’m working on and am wondering if this can be improved in any way. From what I can tell so far it seems to be working alright.

This code is a segment of a bigger LocalScript, but I think all the relevant code is there:

--services
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UserInputService = game:GetService("UserInputService")
local TweenService = game:GetService("TweenService")
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")

--modules
local modulesFolder = ReplicatedStorage.modules
local playerModule = require(modulesFolder.playerModule)
local characters = require(modulesFolder.characters)

--folders
local remotesFolder = ReplicatedStorage.remotes
local uiFolder = ReplicatedStorage.clientAssets.UI
local characterTemplate = uiFolder.characterTemplate

local canvasGroup = script.Parent

--shop ui
local shopFrame = canvasGroup.ShopFrame
local shopBackButton = shopFrame.back
local charactersContainer = shopFrame.characterContainer

local selectedIndex = 1
local spinSpeed = 35 -- degrees per second

--adjust spacing and size based on device
local viewportSizeX = 0.25
local viewportSpacing = if playerModule.getPlayerDevice() == "Mobile" then 120 else 300

local characterShopTweenInfo = TweenInfo.new(0.2, Enum.EasingStyle.Quad)

local viewportFrames = {}

local dragTween = nil
local isDragging = false
local selectDebounce = false
local dragStartPos = 0
local dragDelta = 0

--helpers
function numberClamp(v) 
	return math.clamp(v, 0, 9999) 
end

function getViewportYSize(selected)
	if playerModule.getPlayerDevice() == "Mobile" then return selected and 0.3 or 0.15 end --0.3 selected size, 0.15 not selected size
	return selected and 0.5 or 0.25 --0.5 selected size, 0.25 not selected size
end

local viewMinY = getViewportYSize(false) --size when not selected
local viewMaxY = getViewportYSize(true)--size when selected

function eased(t)
	t = math.clamp(t, 0, 1)
	return t * t * (3 - 2 * t)
end

--create viewportFrames
function createViewport(characterData, index)
	local vp = characterTemplate:Clone()
	vp.Visible = true
	vp.Name = characterData.Name
	vp.Size = UDim2.new(viewportSizeX, 0, viewMinY, 0)
	vp.Position = UDim2.new(0.5, (index - 1) * viewportSpacing, 0.5, 0)
	vp.AnchorPoint = Vector2.new(0.5, 0.5)
	vp.Parent = charactersContainer

	local char = characterData.Model:Clone()
	char.CFrame = CFrame.new(0, 5.113, 0) * CFrame.Angles(0, math.rad(-180), 0)
	char:SetAttribute("BaseCFrame", char.CFrame)
	char:SetAttribute("Name", characterData.Name)
	char.Name = "Character"
	char.Parent = vp

	return vp
end
for i, data in ipairs(characters.Characters) do
	viewportFrames[i] = createViewport(data, i)
end

--viewportFrame positioning/sizing
function setSelected(index)
	dragDelta = 0
	dragTween = nil
	selectedIndex = index

	for i, vp in ipairs(viewportFrames) do
		if not vp.Character then continue end

		local selected = (i == index)
		if not selected then continue end

		local targetX = (i - index) * viewportSpacing

		TweenService:Create(vp, characterShopTweenInfo, {
			Position = UDim2.new(0.5, targetX, 0.5, 0),
			Size = UDim2.new(viewportSizeX, 0, selected and viewMaxY or viewMinY, 0)
		}):Play()

		print("Selected character: ".. vp.Character:GetAttribute("Name"))
	end

	task.wait(0.2)
	selectDebounce = false
end
function setUnSelected(index)
	for i, vp in ipairs(viewportFrames) do
		if not vp.Character then continue end
		if i == index then continue end

		local base = vp.Character:GetAttribute("BaseCFrame")
		if not base then continue end

		TweenService:Create(vp.Character, characterShopTweenInfo, {CFrame = base}):Play()
	end
end

function updateViewportPositions()
	if #viewportFrames == 0 then return end

	local centerX = camera.ViewportSize.X * 0.5

	for i, vp in ipairs(viewportFrames) do
		local targetX = (i - selectedIndex + dragDelta / viewportSpacing) * viewportSpacing
		vp.Position = UDim2.new(0.5, targetX, 0.5, 0)

		local vpCenter = vp.AbsolutePosition.X + vp.AbsoluteSize.X * 0.5
		local dist = math.abs(vpCenter - centerX)
		local ratio = eased(1 - dist / viewportSpacing)

		vp.Size = UDim2.new(viewportSizeX, 0, viewMinY + (viewMaxY - viewMinY) * ratio, 0)
	end
end

--dragging
function tweenDragToCenter(nearestIndex)
	if selectDebounce then return end
	selectDebounce = true
	
	if dragTween then
		dragTween.Completed:Wait()
	end

	nearestIndex = math.clamp(nearestIndex, 1, #viewportFrames)
	local goalDelta = (selectedIndex - nearestIndex) * viewportSpacing

	local proxy = Instance.new("NumberValue")
	proxy.Value = dragDelta
	proxy.Changed:Connect(function()
		dragDelta = proxy.Value
		updateViewportPositions()
	end)

	dragTween = TweenService:Create(proxy, characterShopTweenInfo, {Value = goalDelta})
	dragTween:Play()
	dragTween.Completed:Connect(function()
		setSelected(nearestIndex)
	end)

	setUnSelected(nearestIndex)
end

function onDragStart(input)
	if not shopFrame.Visible or selectDebounce then return end
	if input.UserInputType ~= Enum.UserInputType.Touch and input.UserInputType ~= Enum.UserInputType.MouseButton1 then return end

	isDragging = true
	dragStartPos = input.Position.X
	dragDelta = 0
end
function onDragMove(input)
	if not isDragging then return end
	if input.UserInputType ~= Enum.UserInputType.Touch and input.UserInputType ~= Enum.UserInputType.MouseMovement then return end

	dragDelta = input.Position.X - dragStartPos
	updateViewportPositions()
end
function onDragEnd(input)
	if not isDragging then return end
	if input.UserInputType ~= Enum.UserInputType.Touch and input.UserInputType ~= Enum.UserInputType.MouseButton1 then return end

	isDragging = false

	local offset = (dragDelta + viewportSpacing / 2) / viewportSpacing
	local nearest = selectedIndex - math.floor(offset)
	tweenDragToCenter(nearest)

	dragDelta = 0
end

UserInputService.InputBegan:Connect(onDragStart)
UserInputService.InputChanged:Connect(onDragMove)
UserInputService.InputEnded:Connect(onDragEnd)

UserInputService.InputBegan:Connect(function(input, gpe)
	if not shopFrame.Visible or selectDebounce or gpe then return end
	if input.UserInputType ~= Enum.UserInputType.Keyboard then return end

	local key = input.KeyCode
	if key == Enum.KeyCode.A or key == Enum.KeyCode.Left then
		tweenDragToCenter(selectedIndex - 1)
	elseif key == Enum.KeyCode.D or key == Enum.KeyCode.Right then
		tweenDragToCenter(selectedIndex + 1)
	end
end)

mouse.WheelForward:Connect(function()
	if not shopFrame.Visible or selectDebounce then return end
	tweenDragToCenter(selectedIndex + 1)
end)
mouse.WheelBackward:Connect(function()
	if not shopFrame.Visible or selectDebounce then return end
	tweenDragToCenter(selectedIndex - 1)
end)

RunService.RenderStepped:Connect(function(dt)
	if not shopFrame.Visible then return end

	local vp = viewportFrames[selectedIndex]
	if vp and vp.Character then
		vp.Character.CFrame *= CFrame.Angles(0, math.rad(spinSpeed * dt), 0)
	end

	updateViewportPositions()
end)

have you considered supporting touch devices?
i might be wrong but seems it does not handle them.
what happens if user taps on non selected item? will it become centered and selected?

I typically use UIPageLayout for creating Carousel UI. You could look into using that as well to simplify the process a bit.

Mobile support from my testing seems to work. I couldn’t get tapping to work, but I could get it working for mouse clicking:

local CLICK_THRESHOLD = 15 --how much mouse movement still counts as a click
local mouseX = nil

--create viewportFrames
function createViewport(characterData, index)
	local vp = characterTemplate:Clone()
	vp.Visible = true
	vp.Name = characterData.Name
	vp.Size = UDim2.new(viewportSizeX, 0, viewMinY, 0)
	vp.Position = UDim2.new(0.5, (index - 1) * viewportSpacing, 0.5, 0)
	vp.AnchorPoint = Vector2.new(0.5, 0.5)
	vp.Parent = charactersContainer

	local char = characterData.Model:Clone()
	char.Size = char.Size * 0.8
	char.CFrame = CFrame.new(0, 5.113, 0) * CFrame.Angles(0, math.rad(-180), 0)
	char:SetAttribute("BaseCFrame", char.CFrame)
	char:SetAttribute("Name", characterData.Name)
	char.Name = "Character"
	char.Parent = vp

	vp.InputBegan:Connect(function(input)
		if input.UserInputType ~= Enum.UserInputType.MouseButton1 then return end
		mouseX = input.Position.X
	end)
	vp.InputEnded:Connect(function(input)
		if not mouseX then return end
		if input.UserInputType ~= Enum.UserInputType.MouseButton1 then return end
		if not characterFrame.Visible or selectDebounce then return end

		local moved = math.abs(input.Position.X - mouseX)

		--if mouse barely moves then still count it as click
		if moved < CLICK_THRESHOLD then
			tweenDragToCenter(index)
		end

		mouseX = nil
	end)

	return vp
end

Alright did a bit of mining off stream and made the carousel stuff into a ModuleScript.

I think it’s looking alright?

local Players = game:GetService("Players")
local TweenService = game:GetService("TweenService")
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local modulesFolder = ReplicatedStorage.modules
local playerModule = require(modulesFolder.playerModule)

local configsFolder = ReplicatedStorage.configs
local characters = require(configsFolder.characters)

local assetsFolder = ReplicatedStorage.assets
local uiFolder = assetsFolder.UI

--viewportFrame template for each character to be added to carousel
local characterSelectTemplate = uiFolder.characterSelectTemplate

local player = Players.LocalPlayer
local mouse = player:GetMouse()

local camera = Workspace.CurrentCamera

export type initUiType = {
	CharacterFrame: Frame,
	CharacterSelectorContainer: Frame,
	SelectedCharacterText: TextLabel,
}

local ui: initUiType = {}
local viewportFrames = {}

local characterShopTweenInfo = TweenInfo.new(0.2, Enum.EasingStyle.Quad)

local initialized = false
local isDragging = false
local selectDebounce = false

local playerDevice = playerModule.getPlayerDevice()
local viewportSpacing = if playerDevice == "Mobile" then 140 else 300
local viewportSizeX = 0.25

local selectedIndex = 1
local dragDelta = 0
local dragStartPos = 0

local spinSpeed = 35
local CLICK_THRESHOLD = 15
local mouseX
local viewMinY
local viewMaxY

local carouselUiModule = {}

--private functions
local function _setViewportYSize(selected: boolean)
	if selected == nil then return end
	
	if playerDevice == "Mobile" then 
		return selected and 0.7 or 0.3 --0.7 selected size, 0.3 not selected size
	else
		return selected and 1 or 0.45 --1 selected size, 0.45 not selected size
	end
end

local function _createViewports()
	for i, data in ipairs(characters.Characters) do
		local vp = characterSelectTemplate:Clone()
		vp.Visible = true
		vp.Name = data.Name
		vp.Size = UDim2.new(viewportSizeX, 0, viewMinY, 0)
		vp.Position = UDim2.new(0.5, (i - 1) * viewportSpacing, 0.5, 0)
		vp.AnchorPoint = Vector2.new(0.5, 0.5)
		vp.Parent = ui.CharacterSelectorContainer

		local char = data.Model:Clone()
		char.Size *= 0.8
		char.CFrame = CFrame.new(0, 5.113, 0) * CFrame.Angles(0, math.rad(-180), 0)
		char:SetAttribute("BaseCFrame", char.CFrame)
		char:SetAttribute("Name", data.Name)
		char.Name = "Character"
		char.Parent = vp

		viewportFrames[i] = vp
	end
end

local function _updateNameLabel()
	if #viewportFrames == 0 then return end

	local centerX = camera.ViewportSize.X * 0.5
	local nearestIndex = selectedIndex
	local nearestDist = math.huge

	for i, vp in ipairs(viewportFrames) do
		local vpCenter = vp.AbsolutePosition.X + vp.AbsoluteSize.X * 0.5
		local dist = math.abs(vpCenter - centerX)
		if dist < nearestDist then
			nearestDist = dist
			nearestIndex = i
		end
	end

	ui.SelectedCharacterText.Text = viewportFrames[nearestIndex].Character:GetAttribute("Name") or "Error: Name not found"
end

local function _eased(t)
	t = math.clamp(t, 0, 1)
	return t * t * (3 - 2 * t)
end

local function _updateViewportPositions()
	if #viewportFrames == 0 then return end

	local centerX = camera.ViewportSize.X * 0.5

	for i, vp in ipairs(viewportFrames) do
		local targetX = (i - selectedIndex + dragDelta / viewportSpacing) * viewportSpacing
		vp.Position = UDim2.new(0.5, targetX, 0.5, 0)

		local vpCenter = vp.AbsolutePosition.X + vp.AbsoluteSize.X * 0.5
		local dist = math.abs(vpCenter - centerX)
		local ratio = _eased(1 - dist / viewportSpacing)
		vp.Size = UDim2.new(viewportSizeX, 0, viewMinY + (viewMaxY - viewMinY) * ratio, 0)
	end

	_updateNameLabel()
end

local function _setSelected(index: number, getSelected: boolean)
	for i, vp in ipairs(viewportFrames) do
		if not vp.Character then continue end

		local isSelected = (i == index)
		if isSelected ~= getSelected then continue end

		--bring selected viewport to middle of screen and enlarge
		if isSelected then
			local targetX = (i - index) * viewportSpacing

			TweenService:Create(vp, characterShopTweenInfo, {
				Position = UDim2.new(0.5, targetX, 0.5, 0),
				Size = UDim2.new(viewportSizeX, 0, viewMaxY, 0)
			}):Play()

			--fire event to select character
			print("Selected character: " .. vp.Character:GetAttribute("Name"))

			task.delay(0.2, function()
				selectDebounce = false
			end)
		else
			--reset rotation for unselected characters
			local base = vp.Character:GetAttribute("BaseCFrame")
			if not base then continue end

			TweenService:Create(vp.Character, characterShopTweenInfo, {CFrame = base}):Play()
		end
	end
end

local function _bindInputs()
	--get inputs of mouse/touch/keyboard
	UserInputService.InputBegan:Connect(function(input: InputObject, gpe: boolean)
		if not ui.CharacterFrame.Visible or selectDebounce and not gpe then return end

		--start mouse/touch drag if started within container frame
		if input.UserInputType == Enum.UserInputType.Touch or input.UserInputType == Enum.UserInputType.MouseButton1 then
			local containerPos = ui.CharacterSelectorContainer.AbsolutePosition
			local containerSize = ui.CharacterSelectorContainer.AbsoluteSize
			local dragStartPosX = input.Position.X
			local dragStartPosY = input.Position.Y

			if dragStartPosX >= containerPos.X and dragStartPosX <= containerPos.X + containerSize.X and 
				dragStartPosY >= containerPos.Y and dragStartPosY <= containerPos.Y + containerSize.Y then
				isDragging = true
				dragDelta = 0
				dragStartPos = dragStartPosX
				mouseX = dragStartPosX
			end
		end

		--scroll characters with AD/arrow keys
		if input.UserInputType == Enum.UserInputType.Keyboard then
			local key = input.KeyCode
			if key == Enum.KeyCode.A or key == Enum.KeyCode.Left then
				carouselUiModule.setIndex(selectedIndex - 1)
			elseif key == Enum.KeyCode.D or key == Enum.KeyCode.Right then
				carouselUiModule.setIndex(selectedIndex + 1)
			end
		end
	end)
	--update viewport positions during drag + mouse wheel scrolling
	UserInputService.InputChanged:Connect(function(input: InputObject)
		if input.UserInputType == Enum.UserInputType.MouseMovement or input.UserInputType == Enum.UserInputType.Touch then
			if not isDragging then return end

			dragDelta = input.Position.X - dragStartPos
			_updateViewportPositions()
		elseif input.UserInputType == Enum.UserInputType.MouseWheel then
			if not ui.CharacterFrame.Visible or selectDebounce then return end

			if input.Position.Z > 0 then
				carouselUiModule.setIndex(selectedIndex + 1)
			elseif input.Position.Z < 0 then
				carouselUiModule.setIndex(selectedIndex - 1)
			end
		end
	end)
	--drag release
	UserInputService.InputEnded:Connect(function(input: InputObject)
		if input.UserInputType ~= Enum.UserInputType.Touch and input.UserInputType ~= Enum.UserInputType.MouseButton1 then return end
		if not isDragging then return end

		isDragging = false

		local offset = (dragDelta + viewportSpacing / 2) / viewportSpacing
		local nearest = selectedIndex - math.floor(offset)

		--click detection
		if mouseX and math.abs(input.Position.X - mouseX) < CLICK_THRESHOLD then
			for i, vp in ipairs(viewportFrames) do
				local vpPos = vp.AbsolutePosition
				local vpSize = vp.AbsoluteSize
				if input.Position.X >= vpPos.X and input.Position.X <= vpPos.X + vpSize.X and 
					input.Position.Y >= vpPos.Y and input.Position.Y <= vpPos.Y + vpSize.Y then
					nearest = i
					break
				end
			end
		end

		carouselUiModule.setIndex(nearest)
		dragDelta = 0
		mouseX = nil
	end)

	--spin selected character
	RunService.RenderStepped:Connect(function(dt)
		if not ui.CharacterFrame.Visible then return end

		local vp = viewportFrames[selectedIndex]
		if vp and vp.Character then
			vp.Character.CFrame *= CFrame.Angles(0, math.rad(spinSpeed * dt), 0)
		end

		_updateViewportPositions()
	end)
end

viewMinY = _setViewportYSize(false)
viewMaxY = _setViewportYSize(true)

--public functions
function carouselUiModule.init(initUI: initUiType)
	assert(not initialized, "CarouselUI module already initialized")
	
	ui = initUI
	_createViewports()
	_bindInputs()

	initialized = true
end

function carouselUiModule.setIndex(index)
	if selectDebounce then return end
	selectDebounce = true

	index = math.clamp(index, 1, #viewportFrames)
	local goal = (selectedIndex - index) * viewportSpacing

	local proxy = Instance.new("NumberValue")
	proxy.Value = dragDelta
	proxy.Changed:Connect(function()
		dragDelta = proxy.Value
		_updateViewportPositions()
	end)

	TweenService:Create(proxy, characterShopTweenInfo, {Value = goal}):Play()
	task.delay(characterShopTweenInfo.Time, function()
		dragDelta = 0
		proxy:Destroy()
		selectedIndex = index
		_setSelected(index, true)
	end)

	_setSelected(index, false)
end

return carouselUiModule

crossy blox :rofl:

I LOVE IT

ok so when im making carousell things i just use like the “hard way” that is making image buttons and with a script if a player selects on they get centered so they get bigger the selected one and if they double tap and that…

i kinda like it its nice…