GuiObject
*Este conteúdo é traduzido por IA (Beta) e pode conter erros. Para ver a página em inglês, clique aqui.
GuiObject é uma classe abstrata (muito como BasePart ) para um Objetode interface de usuário 2D.Define todas as propriedades relacionadas à exibição de um objeto de interface gráfica do usuário (Interface gráfica do usuário), como Size e Position.Também tem algumas propriedades úteis de leitura apenas como AbsolutePosition , AbsoluteSize e AbsoluteRotation .
Para manipular o layout de objetos GUI de maneiras especiais, você pode usar uma estrutura de layout, como lista/flexo ou grade, e você pode estilizá-los além de suas propriedades principais através de modificadores de aparência .
Embora seja possível detectar eventos de botão do mouse em qualquer objeto GUI usando InputBegan e InputEnded, apenas ImageButton e TextButton têm eventos convenientes dedicados, como Activated para detectar clique/pressão.
Resumo
Propriedades
Determina se este elemento de UI afunda a entrada.
Determina o ponto de origem de um GuiObject , em relação ao seu tamanho absoluto.
Determina se o redimensionamento ocorre com base no conteúdo da criança.
Determina a cor de fundo GuiObject .
Determina a transparência do plano de fundo e da borda GuiObject.
Determina a cor da borda GuiObject .
Determina de que maneira a borda GuiObject é disposta em relação às suas dimensões.
Determina a largura do pixel da borda GuiObject .
Determina se descendente GuiObjects fora dos limites de um elemento GUI pai deve renderizar.
Determina se o mouse do jogador está sendo pressionado ativamente no GuiObject ou não.
Determina se o GuiButton pode ser interagido ou não, ou se o GuiState do GuiObject está mudando ou não.
Controla a ordem de classificação do GuiObject quando usado com um UIGridStyleLayout .
Define o GuiObject que será selecionado quando o seletor de gamepad for movido para baixo.
Define o GuiObject que será selecionado quando o seletor de gamepad for movido para a esquerda.
Define o GuiObject que será selecionado quando o seletor de gamepad for movido para a direita.
Define o GuiObject que será selecionado quando o seletor de gamepad for movido para cima.
Determina a posição do pixel e escalar da GuiObject .
Determina o número de graus em que o GuiObject é girado.
Determine se o GuiObject pode ser selecionado por um controle / controle de jogo.
Substitui o adorno de seleção padrão usado para gamepads.
A ordem de GuiObjects selecionada pela seleção da interface do gamepad.
Determina o tamanho do pixel e escalar do GuiObject .
Define os eixos Size que o GuiObject será baseado, em relação ao tamanho de seu pai.
Uma propriedade mista de BackgroundTransparency e TextTransparency.
Determina se o GuiObject e seus descendentes serão renderizados.
Determina a ordem em que um GuiObject renderiza em relação aos outros.
Propriedades
Descreve a posição real da tela de um elemento GuiBase2d , em pixels.
Descreve a rotação real da tela de um elemento GuiBase2d em graus.
Descreve o tamanho real da tela de um elemento GuiBase2d , em pixels.
Quando definido para true , a localização será aplicada a este GuiBase2d e seus descendentes.
Uma referência a um LocalizationTable para ser usado para aplicar localização automatizada a este GuiBase2d e seus descendentes.
Personaliza o comportamento de seleção de gamepad na direção de baixo.
Personaliza o comportamento de seleção do gamepad na direção esquerda.
Personaliza o comportamento de seleção do gamepad na direção certa.
Personaliza o comportamento de seleção do gamepad na direção de cima.
Permite a personalização do movimento de seleção do gamepad.
Métodos
- TweenPosition(endPosition : UDim2,easingDirection : Enum.EasingDirection,easingStyle : Enum.EasingStyle,time : number,override : boolean,callback : function):boolean
Mova suavemente uma GUI para um novo UDim2.
- TweenSize(endSize : UDim2,easingDirection : Enum.EasingDirection,easingStyle : Enum.EasingStyle,time : number,override : boolean,callback : function):boolean
- TweenSizeAndPosition(endSize : UDim2,endPosition : UDim2,easingDirection : Enum.EasingDirection,easingStyle : Enum.EasingStyle,time : number,override : boolean,callback : function):boolean
Mova suavemente uma GUI para um novo tamanho e posição.
Eventos
Dispedido quando um usuário começa a interagir através de um dispositivo de Interface Humano-Computador (botão do mouse para baixo, toque começa, botão do teclado para baixo, etc).
Dispedido quando um usuário muda como está interagindo através de um dispositivo de Interface Humano-Computador (botão do mouse para baixo, toque começa, botão da tecla para baixo, etc).
Dispedido quando um usuário para de interagir através de um dispositivo de Interface Humano-Computador (botão do mouse para baixo, toque começar, botão da tecla para baixo, etc).
Dispara quando um usuário move o mouse para um elemento de GUI.
Dispara quando um usuário move o mouse para fora de um elemento de GUI.
Incêndios sempre que um usuário move o mouse enquanto ele está dentro de um elemento de GUI.
Dispara quando um usuário rola a roda do mouse de volta quando o mouse está sobre um elemento de GUI.
Dispara quando um usuário rola a roda do mouse para a frente quando o mouse está sobre um elemento de GUI.
Disparado quando o GuiObject está sendo focado no seletor Gamepad.
Dispedido quando o seletor de Gamepad para de se concentrar no GuiObject.
Incêndios quando o jogador começa, continua e para de apertar a tecla da interface de usuário por muito tempo.
- TouchPan(touchPositions : Array,totalTranslation : Vector2,velocity : Vector2,state : Enum.UserInputState):RBXScriptSignal
Dispara quando o jogador move o dedo sobre o elemento da interface.
- TouchPinch(touchPositions : Array,scale : number,velocity : number,state : Enum.UserInputState):RBXScriptSignal
Incêndios quando o jogador executa um gesto de pinça ou puxão usando dois dedos no elemento da interface.
- TouchRotate(touchPositions : Array,rotation : number,velocity : number,state : Enum.UserInputState):RBXScriptSignal
Incêndios quando o jogador executa um gesto de rotação usando dois dedos no elemento da interface.
Incêndios quando o jogador executa um gesto de deslize no elemento da interface.
Dispara quando o jogador executa um gesto de toque no elemento da interface.
Eventos
- SelectionChanged(amISelected : boolean,previousSelection : GuiObject,newSelection : GuiObject):RBXScriptSignal
Incêndios quando a seleção do gamepad se move para, deixa ou muda dentro do conectado GuiBase2d ou qualquer descendente GuiObjects.
Propriedades
Active
Amostras de código
-- Place this LocalScript within a TextButton (or ImageButton)
local textButton = script.Parent
textButton.Text = "Click me"
textButton.Active = true
local function onActivated()
-- This acts like a debounce
textButton.Active = false
-- Count backwards from 5
for i = 5, 1, -1 do
textButton.Text = "Time: " .. i
task.wait(1)
end
textButton.Text = "Click me"
textButton.Active = true
end
textButton.Activated:Connect(onActivated)
AnchorPoint
Amostras de código
local guiObject = script.Parent
while true do
-- Topo-esquerda
guiObject.AnchorPoint = Vector2.new(0, 0)
guiObject.Position = UDim2.new(0, 0, 0, 0)
task.wait(1)
-- Primeiro
guiObject.AnchorPoint = Vector2.new(0.5, 0)
guiObject.Position = UDim2.new(0.5, 0, 0, 0)
task.wait(1)
-- Direita superior
guiObject.AnchorPoint = Vector2.new(1, 0)
guiObject.Position = UDim2.new(1, 0, 0, 0)
task.wait(1)
-- Esquerda
guiObject.AnchorPoint = Vector2.new(0, 0.5)
guiObject.Position = UDim2.new(0, 0, 0.5, 0)
task.wait(1)
-- Centro morta
guiObject.AnchorPoint = Vector2.new(0.5, 0.5)
guiObject.Position = UDim2.new(0.5, 0, 0.5, 0)
task.wait(1)
-- Direita
guiObject.AnchorPoint = Vector2.new(1, 0.5)
guiObject.Position = UDim2.new(1, 0, 0.5, 0)
task.wait(1)
-- Inferior-esquerda
guiObject.AnchorPoint = Vector2.new(0, 1)
guiObject.Position = UDim2.new(0, 0, 1, 0)
task.wait(1)
-- Inferior
guiObject.AnchorPoint = Vector2.new(0.5, 1)
guiObject.Position = UDim2.new(0.5, 0, 1, 0)
task.wait(1)
-- Inferior direita
guiObject.AnchorPoint = Vector2.new(1, 1)
guiObject.Position = UDim2.new(1, 0, 1, 0)
task.wait(1)
end
AutomaticSize
Amostras de código
-- Array de rótulos de texto/fontes/tamanhos para saída
local labelArray = {
{ text = "Lorem", font = Enum.Font.Creepster, size = 50 },
{ text = "ipsum", font = Enum.Font.IndieFlower, size = 35 },
{ text = "dolor", font = Enum.Font.Antique, size = 55 },
{ text = "sit", font = Enum.Font.SpecialElite, size = 65 },
{ text = "amet", font = Enum.Font.FredokaOne, size = 40 },
}
-- Criar uma janela pai de tamanho automático
local parentFrame = Instance.new("Frame")
parentFrame.AutomaticSize = Enum.AutomaticSize.XY
parentFrame.BackgroundColor3 = Color3.fromRGB(90, 90, 90)
parentFrame.Size = UDim2.fromOffset(25, 100)
parentFrame.Position = UDim2.fromScale(0.1, 0.1)
parentFrame.Parent = script.Parent
-- Adicione um layout de lista
local listLayout = Instance.new("UIListLayout")
listLayout.Padding = UDim.new(0, 5)
listLayout.Parent = parentFrame
-- Defina cantos arredondados e espaçamento para estética visual
local roundedCornerParent = Instance.new("UICorner")
roundedCornerParent.Parent = parentFrame
local uiPaddingParent = Instance.new("UIPadding")
uiPaddingParent.PaddingTop = UDim.new(0, 5)
uiPaddingParent.PaddingLeft = UDim.new(0, 5)
uiPaddingParent.PaddingRight = UDim.new(0, 5)
uiPaddingParent.PaddingBottom = UDim.new(0, 5)
uiPaddingParent.Parent = parentFrame
for i = 1, #labelArray do
-- Crie uma etiqueta de texto de tamanho automático a partir de um array
local childLabel = Instance.new("TextLabel")
childLabel.AutomaticSize = Enum.AutomaticSize.XY
childLabel.Size = UDim2.fromOffset(75, 15)
childLabel.Text = labelArray[i]["text"]
childLabel.Font = labelArray[i]["font"]
childLabel.TextSize = labelArray[i]["size"]
childLabel.TextColor3 = Color3.new(1, 1, 1)
childLabel.Parent = parentFrame
-- Estética visual
local roundedCorner = Instance.new("UICorner")
roundedCorner.Parent = childLabel
local uiPadding = Instance.new("UIPadding")
uiPadding.PaddingTop = UDim.new(0, 5)
uiPadding.PaddingLeft = UDim.new(0, 5)
uiPadding.PaddingRight = UDim.new(0, 5)
uiPadding.PaddingBottom = UDim.new(0, 5)
uiPadding.Parent = childLabel
task.wait(2)
end
BackgroundColor3
Amostras de código
-- Put this code in a LocalScript in a Frame
local frame = script.Parent
while true do
for hue = 0, 255, 4 do
-- HSV = hue, saturation, value
-- If we loop from 0 to 1 repeatedly, we get a rainbow!
frame.BorderColor3 = Color3.fromHSV(hue / 256, 1, 1)
frame.BackgroundColor3 = Color3.fromHSV(hue / 256, 0.5, 0.8)
task.wait()
end
end
BackgroundTransparency
BorderColor3
Amostras de código
-- Coloque-me dentro de algum GuiObject, preferivelmente um ImageButton/TextButton
local button = script.Parent
local function onEnter()
button.BorderSizePixel = 2
button.BorderColor3 = Color3.new(1, 1, 0) -- Amarelo
end
local function onLeave()
button.BorderSizePixel = 1
button.BorderColor3 = Color3.new(0, 0, 0) -- Preto
end
-- Conectar eventos
button.MouseEnter:Connect(onEnter)
button.MouseLeave:Connect(onLeave)
-- Nosso estado padrão é "não pairado"
onLeave()
BorderMode
BorderSizePixel
Amostras de código
-- Coloque-me dentro de algum GuiObject, preferivelmente um ImageButton/TextButton
local button = script.Parent
local function onEnter()
button.BorderSizePixel = 2
button.BorderColor3 = Color3.new(1, 1, 0) -- Amarelo
end
local function onLeave()
button.BorderSizePixel = 1
button.BorderColor3 = Color3.new(0, 0, 0) -- Preto
end
-- Conectar eventos
button.MouseEnter:Connect(onEnter)
button.MouseLeave:Connect(onLeave)
-- Nosso estado padrão é "não pairado"
onLeave()
ClipsDescendants
GuiState
Interactable
LayoutOrder
NextSelectionDown
Amostras de código
-- Configure a grade de seleção do Gamepad usando o código abaixo
local container = script.Parent:FindFirstChild("Container")
local grid = container:GetChildren()
local rowSize = container:FindFirstChild("UIGridLayout").FillDirectionMaxCells
for _, gui in pairs(grid) do
if gui:IsA("GuiObject") then
local pos = gui.Name
-- Borda esquerda
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Borda direita
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Acima
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- Abaixo
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Teste a grade de seleção do Gamepad usando o código abaixo
local GuiService = game:GetService("GuiService")
local UserInputService = game:GetService("UserInputService")
GuiService.SelectedObject = container:FindFirstChild("1")
function updateSelection(input)
if input.UserInputType == Enum.UserInputType.Keyboard then
local key = input.KeyCode
local selectedObject = GuiService.SelectedObject
if not selectedObject then
return
end
if key == Enum.KeyCode.Up then
if not selectedObject.NextSelectionUp then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Down then
if not selectedObject.NextSelectionDown then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Left then
if not selectedObject.NextSelectionLeft then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Right then
if not selectedObject.NextSelectionRight then
GuiService.SelectedObject = selectedObject
end
end
end
end
UserInputService.InputBegan:Connect(updateSelection)
NextSelectionLeft
Amostras de código
-- Configure a grade de seleção do Gamepad usando o código abaixo
local container = script.Parent:FindFirstChild("Container")
local grid = container:GetChildren()
local rowSize = container:FindFirstChild("UIGridLayout").FillDirectionMaxCells
for _, gui in pairs(grid) do
if gui:IsA("GuiObject") then
local pos = gui.Name
-- Borda esquerda
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Borda direita
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Acima
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- Abaixo
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Teste a grade de seleção do Gamepad usando o código abaixo
local GuiService = game:GetService("GuiService")
local UserInputService = game:GetService("UserInputService")
GuiService.SelectedObject = container:FindFirstChild("1")
function updateSelection(input)
if input.UserInputType == Enum.UserInputType.Keyboard then
local key = input.KeyCode
local selectedObject = GuiService.SelectedObject
if not selectedObject then
return
end
if key == Enum.KeyCode.Up then
if not selectedObject.NextSelectionUp then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Down then
if not selectedObject.NextSelectionDown then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Left then
if not selectedObject.NextSelectionLeft then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Right then
if not selectedObject.NextSelectionRight then
GuiService.SelectedObject = selectedObject
end
end
end
end
UserInputService.InputBegan:Connect(updateSelection)
NextSelectionRight
Amostras de código
-- Configure a grade de seleção do Gamepad usando o código abaixo
local container = script.Parent:FindFirstChild("Container")
local grid = container:GetChildren()
local rowSize = container:FindFirstChild("UIGridLayout").FillDirectionMaxCells
for _, gui in pairs(grid) do
if gui:IsA("GuiObject") then
local pos = gui.Name
-- Borda esquerda
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Borda direita
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Acima
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- Abaixo
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Teste a grade de seleção do Gamepad usando o código abaixo
local GuiService = game:GetService("GuiService")
local UserInputService = game:GetService("UserInputService")
GuiService.SelectedObject = container:FindFirstChild("1")
function updateSelection(input)
if input.UserInputType == Enum.UserInputType.Keyboard then
local key = input.KeyCode
local selectedObject = GuiService.SelectedObject
if not selectedObject then
return
end
if key == Enum.KeyCode.Up then
if not selectedObject.NextSelectionUp then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Down then
if not selectedObject.NextSelectionDown then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Left then
if not selectedObject.NextSelectionLeft then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Right then
if not selectedObject.NextSelectionRight then
GuiService.SelectedObject = selectedObject
end
end
end
end
UserInputService.InputBegan:Connect(updateSelection)
NextSelectionUp
Amostras de código
-- Configure a grade de seleção do Gamepad usando o código abaixo
local container = script.Parent:FindFirstChild("Container")
local grid = container:GetChildren()
local rowSize = container:FindFirstChild("UIGridLayout").FillDirectionMaxCells
for _, gui in pairs(grid) do
if gui:IsA("GuiObject") then
local pos = gui.Name
-- Borda esquerda
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Borda direita
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Acima
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- Abaixo
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Teste a grade de seleção do Gamepad usando o código abaixo
local GuiService = game:GetService("GuiService")
local UserInputService = game:GetService("UserInputService")
GuiService.SelectedObject = container:FindFirstChild("1")
function updateSelection(input)
if input.UserInputType == Enum.UserInputType.Keyboard then
local key = input.KeyCode
local selectedObject = GuiService.SelectedObject
if not selectedObject then
return
end
if key == Enum.KeyCode.Up then
if not selectedObject.NextSelectionUp then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Down then
if not selectedObject.NextSelectionDown then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Left then
if not selectedObject.NextSelectionLeft then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Right then
if not selectedObject.NextSelectionRight then
GuiService.SelectedObject = selectedObject
end
end
end
end
UserInputService.InputBegan:Connect(updateSelection)
Position
Rotation
Selectable
Amostras de código
local GuiService = game:GetService("GuiService")
local textBox = script.Parent
local function gainFocus()
textBox.Selectable = true
GuiService.SelectedObject = textBox
end
local function loseFocus(_enterPressed, _inputObject)
GuiService.SelectedObject = nil
textBox.Selectable = false
end
-- The FocusLost and FocusGained event will fire because the textBox
-- is of type TextBox
textBox.Focused:Connect(gainFocus)
textBox.FocusLost:Connect(loseFocus)
SelectionImageObject
SelectionOrder
Size
Amostras de código
local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Paste script into a LocalScript that is
-- parented to a Frame within a Frame
local frame = script.Parent
local container = frame.Parent
container.BackgroundColor3 = Color3.new(0, 0, 0) -- black
-- This function is called when the humanoid's health changes
local function onHealthChanged()
local human = player.Character.Humanoid
local percent = human.Health / human.MaxHealth
-- Change the size of the inner bar
frame.Size = UDim2.new(percent, 0, 1, 0)
-- Change the color of the health bar
if percent < 0.1 then
frame.BackgroundColor3 = Color3.new(1, 0, 0) -- black
elseif percent < 0.4 then
frame.BackgroundColor3 = Color3.new(1, 1, 0) -- yellow
else
frame.BackgroundColor3 = Color3.new(0, 1, 0) -- green
end
end
-- This function runs is called the player spawns in
local function onCharacterAdded(character)
local human = character:WaitForChild("Humanoid")
-- Pattern: update once now, then any time the health changes
human.HealthChanged:Connect(onHealthChanged)
onHealthChanged()
end
-- Connect our spawn listener; call it if already spawned
player.CharacterAdded:Connect(onCharacterAdded)
if player.Character then
onCharacterAdded(player.Character)
end
SizeConstraint
Visible
Amostras de código
local gui = script.Parent
local window = gui:WaitForChild("Window")
local toggleButton = gui:WaitForChild("ToggleWindow")
local closeButton = window:WaitForChild("Close")
local function toggleWindowVisbility()
-- Vire um booleano usando a palavra-chave `not`
window.Visible = not window.Visible
end
toggleButton.Activated:Connect(toggleWindowVisbility)
closeButton.Activated:Connect(toggleWindowVisbility)
ZIndex
Métodos
TweenPosition
Parâmetros
Devolução
Amostras de código
local START_POSITION = UDim2.new(0, 0, 0, 0)
local GOAL_POSITION = UDim2.new(1, 0, 1, 0)
local guiObject = script.Parent
local function callback(state)
if state == Enum.TweenStatus.Completed then
print("The tween completed uninterrupted")
elseif state == Enum.TweenStatus.Canceled then
print("Another tween cancelled this one")
end
end
-- Initialize the GuiObject position, then start the tween:
guiObject.Position = START_POSITION
local willPlay = guiObject:TweenPosition(
GOAL_POSITION, -- Final position the tween should reach
Enum.EasingDirection.In, -- Direction of the easing
Enum.EasingStyle.Sine, -- Kind of easing to apply
2, -- Duration of the tween in seconds
true, -- Whether in-progress tweens are interrupted
callback -- Function to be callled when on completion/cancelation
)
if willPlay then
print("The tween will play")
else
print("The tween will not play")
end
TweenSize
Parâmetros
Devolução
Amostras de código
local guiObject = script.Parent
local function callback(didComplete)
if didComplete then
print("The tween completed successfully")
else
print("The tween was cancelled")
end
end
local willTween = guiObject:TweenSize(
UDim2.new(0.5, 0, 0.5, 0), -- endSize (required)
Enum.EasingDirection.In, -- easingDirection (default Out)
Enum.EasingStyle.Sine, -- easingStyle (default Quad)
2, -- time (default: 1)
true, -- should this tween override ones in-progress? (default: false)
callback -- a function to call when the tween completes (default: nil)
)
if willTween then
print("The GuiObject will tween")
else
print("The GuiObject will not tween")
end
TweenSizeAndPosition
Parâmetros
Devolução
Amostras de código
local frame = script.Parent.Frame
frame:TweenSizeAndPosition(UDim2.new(0, 0, 0, 0), UDim2.new(0, 0, 0, 0))
Eventos
InputBegan
Parâmetros
Amostras de código
-- In order to use the InputBegan event, you must specify the GuiObject
local gui = script.Parent
-- A sample function providing multiple usage cases for various types of user input
local function inputBegan(input)
if input.UserInputType == Enum.UserInputType.Keyboard then
print("A key is being pushed down! Key:", input.KeyCode)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
print("The left mouse button has been pressed down at", input.Position)
elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
print("The right mouse button has been pressed down at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Touch then
print("A touchscreen input has started at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
print("A button is being pressed on a gamepad! Button:", input.KeyCode)
end
end
gui.InputBegan:Connect(inputBegan)
InputChanged
Parâmetros
Amostras de código
local UserInputService = game:GetService("UserInputService")
local gui = script.Parent
local function printMovement(input)
print("Position:", input.Position)
print("Movement Delta:", input.Delta)
end
local function inputChanged(input)
if input.UserInputType == Enum.UserInputType.MouseMovement then
print("The mouse has been moved!")
printMovement(input)
elseif input.UserInputType == Enum.UserInputType.MouseWheel then
print("The mouse wheel has been scrolled!")
print("Wheel Movement:", input.Position.Z)
elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
if input.KeyCode == Enum.KeyCode.Thumbstick1 then
print("The left thumbstick has been moved!")
printMovement(input)
elseif input.KeyCode == Enum.KeyCode.Thumbstick2 then
print("The right thumbstick has been moved!")
printMovement(input)
elseif input.KeyCode == Enum.KeyCode.ButtonL2 then
print("The pressure being applied to the left trigger has changed!")
print("Pressure:", input.Position.Z)
elseif input.KeyCode == Enum.KeyCode.ButtonR2 then
print("The pressure being applied to the right trigger has changed!")
print("Pressure:", input.Position.Z)
end
elseif input.UserInputType == Enum.UserInputType.Touch then
print("The user's finger is moving on the screen!")
printMovement(input)
elseif input.UserInputType == Enum.UserInputType.Gyro then
local _rotInput, rotCFrame = UserInputService:GetDeviceRotation()
local rotX, rotY, rotZ = rotCFrame:toEulerAnglesXYZ()
local rot = Vector3.new(math.deg(rotX), math.deg(rotY), math.deg(rotZ))
print("The rotation of the user's mobile device has been changed!")
print("Position", rotCFrame.p)
print("Rotation:", rot)
elseif input.UserInputType == Enum.UserInputType.Accelerometer then
print("The acceleration of the user's mobile device has been changed!")
printMovement(input)
end
end
gui.InputChanged:Connect(inputChanged)
InputEnded
Parâmetros
Amostras de código
-- In order to use the InputChanged event, you must specify a GuiObject
local gui = script.Parent
-- A sample function providing multiple usage cases for various types of user input
local function inputEnded(input)
if input.UserInputType == Enum.UserInputType.Keyboard then
print("A key has been released! Key:", input.KeyCode)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
print("The left mouse button has been released at", input.Position)
elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
print("The right mouse button has been released at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Touch then
print("A touchscreen input has been released at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
print("A button has been released on a gamepad! Button:", input.KeyCode)
end
end
gui.InputEnded:Connect(inputEnded)
MouseEnter
Parâmetros
Amostras de código
local guiObject = script.Parent
guiObject.MouseEnter:Connect(function(x, y)
print("The user's mouse cursor has entered the GuiObject at position", x, ",", y)
end)
SelectionGained
Amostras de código
local guiObject = script.Parent
local function selectionGained()
print("The user has selected this button with a gamepad.")
end
guiObject.SelectionGained:Connect(selectionGained)
SelectionLost
Amostras de código
local guiObject = script.Parent
local function selectionLost()
print("The user no longer has this selected with their gamepad.")
end
guiObject.SelectionLost:Connect(selectionLost)
TouchLongPress
Parâmetros
Amostras de código
local frame = script.Parent
frame.Active = true
local dragging = false
local basePosition
local startTouchPosition
local borderColor3
local backgroundColor3
local function onTouchLongPress(touchPositions, state)
if state == Enum.UserInputState.Begin and not dragging then
-- Start a drag
dragging = true
basePosition = frame.Position
startTouchPosition = touchPositions[1]
-- Color the frame to indicate the drag is happening
borderColor3 = frame.BorderColor3
backgroundColor3 = frame.BackgroundColor3
frame.BorderColor3 = Color3.new(1, 1, 1) -- White
frame.BackgroundColor3 = Color3.new(0, 0, 1) -- Blue
elseif state == Enum.UserInputState.Change then
local touchPosition = touchPositions[1]
local deltaPosition =
UDim2.new(0, touchPosition.X - startTouchPosition.X, 0, touchPosition.Y - startTouchPosition.Y)
frame.Position = basePosition + deltaPosition
elseif state == Enum.UserInputState.End and dragging then
-- Stop the drag
dragging = false
frame.BorderColor3 = borderColor3
frame.BackgroundColor3 = backgroundColor3
end
end
frame.TouchLongPress:Connect(onTouchLongPress)
TouchPan
Parâmetros
Amostras de código
local innerFrame = script.Parent
local outerFrame = innerFrame.Parent
outerFrame.BackgroundTransparency = 0.75
outerFrame.Active = true
outerFrame.Size = UDim2.new(1, 0, 1, 0)
outerFrame.Position = UDim2.new(0, 0, 0, 0)
outerFrame.AnchorPoint = Vector2.new(0, 0)
outerFrame.ClipsDescendants = true
local dragging = false
local basePosition
local function onTouchPan(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Begin and not dragging then
dragging = true
basePosition = innerFrame.Position
outerFrame.BackgroundTransparency = 0.25
elseif state == Enum.UserInputState.Change then
innerFrame.Position = basePosition + UDim2.new(0, totalTranslation.X, 0, totalTranslation.Y)
elseif state == Enum.UserInputState.End and dragging then
dragging = false
outerFrame.BackgroundTransparency = 0.75
end
end
outerFrame.TouchPan:Connect(onTouchPan)
TouchPinch
Parâmetros
Amostras de código
local innerFrame = script.Parent
local outerFrame = innerFrame.Parent
outerFrame.BackgroundTransparency = 0.75
outerFrame.Active = true
outerFrame.Size = UDim2.new(1, 0, 1, 0)
outerFrame.Position = UDim2.new(0, 0, 0, 0)
outerFrame.AnchorPoint = Vector2.new(0, 0)
outerFrame.ClipsDescendants = true
local dragging = false
local uiScale = Instance.new("UIScale")
uiScale.Parent = innerFrame
local baseScale
local function onTouchPinch(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Begin and not dragging then
dragging = true
baseScale = uiScale.Scale
outerFrame.BackgroundTransparency = 0.25
elseif state == Enum.UserInputState.Change then
uiScale.Scale = baseScale * scale -- Notice the multiplication here
elseif state == Enum.UserInputState.End and dragging then
dragging = false
outerFrame.BackgroundTransparency = 0.75
end
end
outerFrame.TouchPinch:Connect(onTouchPinch)
TouchRotate
Parâmetros
Amostras de código
local innerFrame = script.Parent
local outerFrame = innerFrame.Parent
outerFrame.BackgroundTransparency = 0.75
outerFrame.Active = true
outerFrame.Size = UDim2.new(1, 0, 1, 0)
outerFrame.Position = UDim2.new(0, 0, 0, 0)
outerFrame.AnchorPoint = Vector2.new(0, 0)
outerFrame.ClipsDescendants = true
local dragging = false
local baseRotation = innerFrame.Rotation
local function onTouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Begin and not dragging then
dragging = true
baseRotation = innerFrame.Rotation
outerFrame.BackgroundTransparency = 0.25
elseif state == Enum.UserInputState.Change then
innerFrame.Rotation = baseRotation + rotation
elseif state == Enum.UserInputState.End and dragging then
dragging = false
outerFrame.BackgroundTransparency = 0.75
end
end
outerFrame.TouchRotate:Connect(onTouchRotate)
TouchSwipe
Parâmetros
Amostras de código
local frame = script.Parent
frame.Active = true
-- Quão longe o quadro deve rebotar em um swipe bem-sucedido
local BOUNCE_DISTANCE = 50
-- Estado atual do quadro
local basePosition = frame.Position
local hue = 0
local saturation = 128
local function updateColor()
frame.BackgroundColor3 = Color3.fromHSV(hue / 256, saturation / 256, 1)
end
local function onTouchSwipe(swipeDir, _touchCount)
-- Altere a cor de fundo 3 com base na direção de deslize
local deltaPos
if swipeDir == Enum.SwipeDirection.Right then
deltaPos = UDim2.new(0, BOUNCE_DISTANCE, 0, 0)
hue = (hue + 16) % 255
elseif swipeDir == Enum.SwipeDirection.Left then
deltaPos = UDim2.new(0, -BOUNCE_DISTANCE, 0, 0)
hue = (hue - 16) % 255
elseif swipeDir == Enum.SwipeDirection.Up then
deltaPos = UDim2.new(0, 0, 0, -BOUNCE_DISTANCE)
saturation = (saturation + 16) % 255
elseif swipeDir == Enum.SwipeDirection.Down then
deltaPos = UDim2.new(0, 0, 0, BOUNCE_DISTANCE)
saturation = (saturation - 16) % 255
else
deltaPos = UDim2.new()
end
-- Atualize a cor e rebounde o quadro um pouco
updateColor()
frame.Position = basePosition + deltaPos
frame:TweenPosition(basePosition, Enum.EasingDirection.Out, Enum.EasingStyle.Bounce, 0.7, true)
end
frame.TouchSwipe:Connect(onTouchSwipe)
updateColor()
TouchTap
Parâmetros
Amostras de código
local frame = script.Parent
frame.Active = true
local function onTouchTap()
-- Toggle background transparency
if frame.BackgroundTransparency > 0 then
frame.BackgroundTransparency = 0
else
frame.BackgroundTransparency = 0.75
end
end
frame.TouchTap:Connect(onTouchTap)