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.
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.
- 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
Essa propriedade determina se o GuiObject vai afundar a entrada no espaço 3D, como modelos subjacentes com uma classe ClickDetector como DragDetector.
Para objetos ( e ), esta propriedade determina se incêndios ( ainda funcionará para aqueles também).Os eventos InputBegan, InputChanged e InputEnded funcionam normalmente, não importa o valor dessa propriedade.
Amostras de código
This code sample demonstrates the usage of the Active property as a debounce for the Activated event.
-- 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
Essa propriedade determina o ponto de origem de um GuiObject , em relação ao seu tamanho absoluto.O ponto de origem determina de onde o elemento é posicionado (através de GuiObject.Position ) e a partir do qual o renderizado GuiObject.Size se expande.
Veja aqui para diagramas ilustrados e detalhes.
Amostras de código
This code sample moves a UI element to different sides of the parent element. It starts at the top-left and ends at the bottom-right. Paste into a LocalScript in a Frame, within a ScreenGui.
local guiObject = script.Parent
while true do
-- Top-left
guiObject.AnchorPoint = Vector2.new(0, 0)
guiObject.Position = UDim2.new(0, 0, 0, 0)
task.wait(1)
-- Top
guiObject.AnchorPoint = Vector2.new(0.5, 0)
guiObject.Position = UDim2.new(0.5, 0, 0, 0)
task.wait(1)
-- Top-right
guiObject.AnchorPoint = Vector2.new(1, 0)
guiObject.Position = UDim2.new(1, 0, 0, 0)
task.wait(1)
-- Left
guiObject.AnchorPoint = Vector2.new(0, 0.5)
guiObject.Position = UDim2.new(0, 0, 0.5, 0)
task.wait(1)
-- Dead center
guiObject.AnchorPoint = Vector2.new(0.5, 0.5)
guiObject.Position = UDim2.new(0.5, 0, 0.5, 0)
task.wait(1)
-- Right
guiObject.AnchorPoint = Vector2.new(1, 0.5)
guiObject.Position = UDim2.new(1, 0, 0.5, 0)
task.wait(1)
-- Bottom-left
guiObject.AnchorPoint = Vector2.new(0, 1)
guiObject.Position = UDim2.new(0, 0, 1, 0)
task.wait(1)
-- Bottom
guiObject.AnchorPoint = Vector2.new(0.5, 1)
guiObject.Position = UDim2.new(0.5, 0, 1, 0)
task.wait(1)
-- Bottom-right
guiObject.AnchorPoint = Vector2.new(1, 1)
guiObject.Position = UDim2.new(1, 0, 1, 0)
task.wait(1)
end
AutomaticSize
Essa propriedade é usada para dimensionar automaticamente objetos de interface pai com base no tamanho de seus descendentes.Você pode usar essa propriedade para adicionar dinamicamente texto e outros conteúdos a um objeto de UI na hora de editar ou executar, e o tamanho será ajustado para caber nesse conteúdo.
Quando é definido para um valor de qualquer coisa diferente de , este objeto de interface de usuário pode redimensionar dependendo de seu conteúdo filho.
Para mais informações sobre como usar essa propriedade e como funciona, veja aqui.
Amostras de código
The following script creates an automatically-sized parent frame with aUIListLayout, then it inserts several automatically-sized TextLabel objects. Note how the parent UIListLayout automatically resizes to fit its child content and the labels automatically resize to fit their text content. This script can be parented to a ScreenGui.
-- Array of text labels/fonts/sizes to output
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 },
}
-- Create an automatically-sized parent frame
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
-- Add a list layout
local listLayout = Instance.new("UIListLayout")
listLayout.Padding = UDim.new(0, 5)
listLayout.Parent = parentFrame
-- Set rounded corners and padding for visual aesthetics
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
-- Create an automatically-sized text label from 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
-- Visual aesthetics
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
Essa propriedade determina a cor de um plano de fundo GuiObject (a cor de preenchimento).Se o seu elemento contém texto, como um TextBox , TextButton ou TextLabel , certifique-se de que a cor de seu plano de fundo contraste com a cor do texto.
Outra propriedade que determina as propriedades visuais do plano de fundo é GuiObject.BackgroundTransparency ; se isso for definido como 1, nem o plano de fundo nem a borda serão renderizar.
Veja também BorderColor3 .
Amostras de código
This code sample causes a parent Frame to loop through all colors of the rainbow using Color3.fromHSV.
-- 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
Essa propriedade determina a transparência do plano de fundo e da borda GuiObject.No entanto, não determina a transparência do texto se a GUI for um TextBox , TextButton ou TextLabel ; a transparência do texto é determinada TextBox.TextTransparency , TextButton.TextTransparency e TextLabel.TextTransparency respectivamente.
Se esta propriedade for definida como 1, nem o plano de fundo nem a borda serão renderizados e o plano de fundo da GUI será completamente transparente.
BorderColor3
Determina a cor do GuiObject border rectangular (também conhecido como a cor do traço).Isto é separado do GuiObject.BackgroundColor3 do Objeto.Você não poderá ver a borda do Objetose sua propriedade GuiObject.BorderSizePixel for definida como 0.
Observe que o componente UIStroke permite efeitos de borda mais avançados.
Amostras de código
This code sample causes the border of a parent GuiObject to highlight when the user hovers their mouse over the element.
-- Put me inside some GuiObject, preferrably an ImageButton/TextButton
local button = script.Parent
local function onEnter()
button.BorderSizePixel = 2
button.BorderColor3 = Color3.new(1, 1, 0) -- Yellow
end
local function onLeave()
button.BorderSizePixel = 1
button.BorderColor3 = Color3.new(0, 0, 0) -- Black
end
-- Connect events
button.MouseEnter:Connect(onEnter)
button.MouseLeave:Connect(onLeave)
-- Our default state is "not hovered"
onLeave()
BorderMode
Essa propriedade determina de que maneira a borda GuiObject é disposta em relação às suas dimensões usando o enum do mesmo nome, Enum.BorderMode .
Observe que UIStroke pode anular essa propriedade e permitir efeitos de borda mais avançados.
BorderSizePixel
Essa propriedade determina o quão larga a borda GuiObject renderiza, em pixels. Definir isso como 0 desabilita a borda completamente.
Observe que UIStroke pode anular essa propriedade e permitir efeitos de borda mais avançados.
Amostras de código
This code sample causes the border of a parent GuiObject to highlight when the user hovers their mouse over the element.
-- Put me inside some GuiObject, preferrably an ImageButton/TextButton
local button = script.Parent
local function onEnter()
button.BorderSizePixel = 2
button.BorderColor3 = Color3.new(1, 1, 0) -- Yellow
end
local function onLeave()
button.BorderSizePixel = 1
button.BorderColor3 = Color3.new(0, 0, 0) -- Black
end
-- Connect events
button.MouseEnter:Connect(onEnter)
button.MouseLeave:Connect(onLeave)
-- Our default state is "not hovered"
onLeave()
ClipsDescendants
Essa propriedade determina se o GuiObject vai cortar (tornar invisível) qualquer parte dos elementos de GUI descendentes que de outro modo renderizariam fora dos limites do retângulo.
Observe que Rotation não é suportado por esta propriedade.Se esta ou qualquer GUI ancestral tiver um não zero , esta propriedade será ignorada e os elementos GUI descendentes serão renderizados independentemente do valor desta propriedade.
GuiState
Quando o dedo do jogador está sendo tocado e mantido no GuiObject, o GuiState do GuiObject será definido como Press .Da mesma forma, quando o dedo do jogador for liberado do GuiObject , o GuiState do GuiObject será definido como Idle , e quando Interactable for desligado no GuiObject , o Class.GuiState do GuiObject será definido como NonInteractable .
Interactable
Determina se o GuiButton pode ser interagido ou não, ou se o GuiState do GuiObject está mudando ou não.
Em um GuiButton :
- Quando a configuração Interactable na GuiButton for definida como false, o GuiButton não poderá mais ser pressionado ou clicado e o GuiState será constantemente definido como NonInteractable.
- Quando a configuração Interactable na GuiButton é definida como true, o GuiButton se comportará normalmente novamente e o GuiState se comportará normalmente.
Em um GuiObject :
- Quando a configuração Interactable na GuiButton é definida como false, a GuiState será constantemente definida como NonInteractable.
- Quando a configuração Interactable na GuiButton é definida como true, o GuiState se comportará normalmente novamente.
LayoutOrder
Essa propriedade controla a ordem de classificação do GuiObject quando usando um UIGridStyleLayout (como UIListLayout ou UIPageLayout ) com SortOrder definido para Enum.SortOrder.LayoutOrder .Não tem funcionalidade se o objeto não tiver uma estrutura de layout de UI irmão.
GuiObjects são classificados em ordem crescente, onde valores mais baixos têm prioridade sobre valores mais altos.Objetos com valores iguais voltam à ordem em que foram adicionados.
Se você não tem certeza se precisará adicionar um elemento entre dois elementos existentes no futuro, é uma boa prática usar múltiplos de 100 ( 0 , 100 , 200 , etc.).Isso garante uma grande lacuna de valores de ordem de layout que você pode usar para elementos ordenados entre outros elementos.
Veja também que determina a ordem de renderização do Objetoem vez de classificar a ordem.
NextSelectionDown
Essa propriedade define o GuiObject selecionado quando o usuário move o seletor de gamepad para baixo.Se esta propriedade estiver vazia, mover o gamepad para baixo não alterará a Interface gráfica do usuárioselecionada.
Mover o seletor de gamepad para baixo define o GuiService.SelectedObject para este objeto, a menos que a GUI não seja Selectable.Observe que essa propriedade pode ser definida para um elemento GUI, mesmo que não seja Selectable, então você deve garantir que o valor de uma propriedade selecionável de Interface gráfica do usuáriocorresponda ao comportamento esperado.
Veja também NextSelectionUp , NextSelectionLeft e NextSelectionRight .
Amostras de código
This example demonstrates how to enable Gamepad navigation through a grid of GuiObject|GUI elements without manually having to connect the GuiObject.NextSelectionUp, GuiObject.NextSelectionDown, and GuiObject|NextSelectionRight, and GuiObject.NextSelectionLeft properties for every element in the grid.
Note that this code sample assumes your UIGridLayout is sorted by name, where elements are named in successive numerical order.
The code relies on this to set the NextSelection properties for all GuiObjects in the same level as the UIGridLayout. In our example, the UIGridLayoutObject and GUI elements within the grid are all children of a Frame named "Container". The code gets the children of "Container" and loops through each child. Children that are not GuiObjects are ignored. For each GUI element, the code attempts to assigned the NextSelection properties using the following logic:
- Starting with 1, the name of all GUI elements match their position in the grid
- Left: The item to the left will always be numbered 1 less than the current element
- Right: The item to the left will always be numbered 1 more than the current element
- Up: The item above (up) will always be number of GUIs in a row 1 less than the current element
- Down: The item below (down) will always be the number of GUIs in a row more than the current element This logic also allows for the GUI elements at the begging and end of rows (excluding the first and last element) to wrap around to the next and previous rows. If an element doesn't exist to the left, right, up, or down, the NextSelection will remain nil and moving the Gamepad selector in the direction will not change the selected GUI.
This example also contains code to test the grid using the arrow keys (Up, Down, Left, Right) of your keyboard instead of a gamepad, just in case you don't have a gamepad to test with. This portion of code initially selects the element named "1" by assigning it to the GuiService.SelectedObject property.
-- Setup the Gamepad selection grid using the code below
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
-- Left edge
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Right edge
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Above
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- Below
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Test the Gamepad selection grid using the code below
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
Essa propriedade define o GuiObject selecionado quando o usuário move o seletor de gamepad para a esquerda.Se esta propriedade estiver vazia, mover o gamepad para a esquerda não alterará a Interface gráfica do usuárioselecionada.
Mover o seletor de gamepad para a esquerda define o GuiService.SelectedObject para este objeto, a menos que a GUI não seja Selectable.Observe que essa propriedade pode ser definida para um elemento GUI, mesmo que não seja Selectable, então você deve garantir que o valor de uma propriedade selecionável de Interface gráfica do usuáriocorresponda ao comportamento esperado.
Veja também NextSelectionUp , NextSelectionDown e NextSelectionRight .
Amostras de código
This example demonstrates how to enable Gamepad navigation through a grid of GuiObject|GUI elements without manually having to connect the GuiObject.NextSelectionUp, GuiObject.NextSelectionDown, and GuiObject|NextSelectionRight, and GuiObject.NextSelectionLeft properties for every element in the grid.
Note that this code sample assumes your UIGridLayout is sorted by name, where elements are named in successive numerical order.
The code relies on this to set the NextSelection properties for all GuiObjects in the same level as the UIGridLayout. In our example, the UIGridLayoutObject and GUI elements within the grid are all children of a Frame named "Container". The code gets the children of "Container" and loops through each child. Children that are not GuiObjects are ignored. For each GUI element, the code attempts to assigned the NextSelection properties using the following logic:
- Starting with 1, the name of all GUI elements match their position in the grid
- Left: The item to the left will always be numbered 1 less than the current element
- Right: The item to the left will always be numbered 1 more than the current element
- Up: The item above (up) will always be number of GUIs in a row 1 less than the current element
- Down: The item below (down) will always be the number of GUIs in a row more than the current element This logic also allows for the GUI elements at the begging and end of rows (excluding the first and last element) to wrap around to the next and previous rows. If an element doesn't exist to the left, right, up, or down, the NextSelection will remain nil and moving the Gamepad selector in the direction will not change the selected GUI.
This example also contains code to test the grid using the arrow keys (Up, Down, Left, Right) of your keyboard instead of a gamepad, just in case you don't have a gamepad to test with. This portion of code initially selects the element named "1" by assigning it to the GuiService.SelectedObject property.
-- Setup the Gamepad selection grid using the code below
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
-- Left edge
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Right edge
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Above
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- Below
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Test the Gamepad selection grid using the code below
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
Essa propriedade define o GuiObject selecionado quando o usuário move o seletor de gamepad para a direita.Se esta propriedade estiver vazia, mover o gamepad para a direita não alterará a Interface gráfica do usuárioselecionada.
Mover o seletor de gamepad para a direita define o GuiService.SelectedObject para este objeto, a menos que a GUI não seja Selectable.Observe que essa propriedade pode ser definida para um elemento GUI, mesmo que não seja Selectable, então você deve garantir que o valor de uma propriedade selecionável de Interface gráfica do usuáriocorresponda ao comportamento esperado.
Veja também NextSelectionUp , NextSelectionDown e NextSelectionLeft .
Amostras de código
This example demonstrates how to enable Gamepad navigation through a grid of GuiObject|GUI elements without manually having to connect the GuiObject.NextSelectionUp, GuiObject.NextSelectionDown, and GuiObject|NextSelectionRight, and GuiObject.NextSelectionLeft properties for every element in the grid.
Note that this code sample assumes your UIGridLayout is sorted by name, where elements are named in successive numerical order.
The code relies on this to set the NextSelection properties for all GuiObjects in the same level as the UIGridLayout. In our example, the UIGridLayoutObject and GUI elements within the grid are all children of a Frame named "Container". The code gets the children of "Container" and loops through each child. Children that are not GuiObjects are ignored. For each GUI element, the code attempts to assigned the NextSelection properties using the following logic:
- Starting with 1, the name of all GUI elements match their position in the grid
- Left: The item to the left will always be numbered 1 less than the current element
- Right: The item to the left will always be numbered 1 more than the current element
- Up: The item above (up) will always be number of GUIs in a row 1 less than the current element
- Down: The item below (down) will always be the number of GUIs in a row more than the current element This logic also allows for the GUI elements at the begging and end of rows (excluding the first and last element) to wrap around to the next and previous rows. If an element doesn't exist to the left, right, up, or down, the NextSelection will remain nil and moving the Gamepad selector in the direction will not change the selected GUI.
This example also contains code to test the grid using the arrow keys (Up, Down, Left, Right) of your keyboard instead of a gamepad, just in case you don't have a gamepad to test with. This portion of code initially selects the element named "1" by assigning it to the GuiService.SelectedObject property.
-- Setup the Gamepad selection grid using the code below
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
-- Left edge
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Right edge
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Above
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- Below
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Test the Gamepad selection grid using the code below
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
Essa propriedade define o GuiObject selecionado quando o usuário move o seletor de gamepad para cima.Se esta propriedade estiver vazia, mover o gamepad para cima não alterará a Interface gráfica do usuárioselecionada.
Mover o seletor de gamepad para cima define o GuiService.SelectedObject para este objeto, a menos que a GUI não seja Selectable.Observe que essa propriedade pode ser definida para um elemento GUI, mesmo que não seja Selectable, então você deve garantir que o valor de uma propriedade selecionável de Interface gráfica do usuáriocorresponda ao comportamento esperado.
Veja também NextSelectionDown , NextSelectionLeft , NextSelectionRight .
Amostras de código
This example demonstrates how to enable Gamepad navigation through a grid of GuiObject|GUI elements without manually having to connect the GuiObject.NextSelectionUp, GuiObject.NextSelectionDown, and GuiObject|NextSelectionRight, and GuiObject.NextSelectionLeft properties for every element in the grid.
Note that this code sample assumes your UIGridLayout is sorted by name, where elements are named in successive numerical order.
The code relies on this to set the NextSelection properties for all GuiObjects in the same level as the UIGridLayout. In our example, the UIGridLayoutObject and GUI elements within the grid are all children of a Frame named "Container". The code gets the children of "Container" and loops through each child. Children that are not GuiObjects are ignored. For each GUI element, the code attempts to assigned the NextSelection properties using the following logic:
- Starting with 1, the name of all GUI elements match their position in the grid
- Left: The item to the left will always be numbered 1 less than the current element
- Right: The item to the left will always be numbered 1 more than the current element
- Up: The item above (up) will always be number of GUIs in a row 1 less than the current element
- Down: The item below (down) will always be the number of GUIs in a row more than the current element This logic also allows for the GUI elements at the begging and end of rows (excluding the first and last element) to wrap around to the next and previous rows. If an element doesn't exist to the left, right, up, or down, the NextSelection will remain nil and moving the Gamepad selector in the direction will not change the selected GUI.
This example also contains code to test the grid using the arrow keys (Up, Down, Left, Right) of your keyboard instead of a gamepad, just in case you don't have a gamepad to test with. This portion of code initially selects the element named "1" by assigning it to the GuiService.SelectedObject property.
-- Setup the Gamepad selection grid using the code below
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
-- Left edge
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Right edge
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Above
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- Below
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Test the Gamepad selection grid using the code below
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
Essa propriedade determina o pixel e a posição escalar usando um . A posição é centrada em torno da posição do Objeto.
A posição escalar é relativa ao tamanho do elemento GUI pai, se algum.
As porções de pixels do valor UDim2 são as mesmas, independentemente do tamanho da Interface gráfica do usuáriopai.Os valores representam a posição do objeto em pixels.A posição de píxel atual de um Objetopode ser lida a partir da propriedade GuiBase2d.AbsolutePosition.
Rotation
Essa propriedade determina o número de graus em que o GuiObject é girado.A rotação é relativa ao centro do Objeto, não ao ponto de rotação, o que significa que você não pode alterar o ponto de rotação.Além disso, essa propriedade não é compatível com ClipsDescendants .
Selectable
Essa propriedade determina se o GuiObject pode ser selecionado ao navegar por GUIs usando um controle / controle de jogo.
Se esta propriedade for true, uma GUI pode ser selecionada. Selecionar uma GUI também define a propriedade GuiService.SelectedObject para esse Objeto.
Quando isso é false, a GUI não pode ser selecionada.No entanto, definir isso para false quando uma GUI é selecionada não desmarcará nem alterará o valor da propriedade GuiService.SelectedObject.
Adicionar GuiObject.SelectionGained e GuiObject.SelectionLost não disparará para o elemento. Para desmarcar um GuiObject, você deve alterar a propriedade GuiService.SelectedObject.
Essa propriedade é útil se uma GUI estiver conectada a várias GUIs através de propriedades como essa GuiObject.NextSelectionUp, GuiObject.NextSelectionDown, NextSelectionRight ou NextSelectionLeft.Em vez de alterar todas as propriedades para que o Gamepad não possa selecionar a Interface gráfica do usuário, você pode desativar sua propriedade Selecionável para impedi-la temporariamente de ser selecionada.Então, quando você quiser que o seletor de gamepad possa selecionar a Interface gráfica do usuário, simplesmente reative sua propriedade selecionável.
Amostras de código
The example below offers a simple demonstration on how to use the GuiObject.Selectable property to limit when a GUI element can be selected by the Gamepad navigator.
When a TextBox has gains focus, it can be selected. However, when a TextBox loses focus it can no longer be selected.
Although this is a simple demonstration, the property can also be used to prevent the navigator from selecting UI elements that exist for cosmetic rather than functional purposes. For instance, while the buttons on a menu screen should be selectable, the title image should not be.
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
Essa propriedade substitui o adorno de seleção padrão usado para gamepads.
Observe que o escolhido SelectionImageObject superpõe o selecionado GuiObject com o Size da imagem.Para melhores resultados, você deve dimensionar o personalizado SelectionImageObject via os valores da escala UDim2 para ajudar a garantir que o objeto seja dimensionado corretamente sobre o elemento selecionado.
Mudar o SelectionImageObject para um elemento GuiObject afeta apenas esse elemento. Para afetar todos os elementos de GUI de um usuário, defina a propriedade PlayerGui.SelectionImageObject.
Para determinar ou definir qual elemento de GUI é selecionado pelo usuário, você pode usar a propriedade GuiService.SelectedObject.O jogador usa o gamepad para selecionar diferentes elementos de GUI, invocando os eventos NextSelectionUp, NextSelectionDown, NextSelectionLeft e NextSelectionRight.
SelectionOrder
GuiObjects com uma Ordem de Seleção mais baixa são selecionados antes de GuiObjects com uma Ordem de Seleção mais alta ao iniciar a seleção do gamepad ou chamar GuiService:Select() em um Antecessor / ancestral.Essa propriedade não afeta a navegação direcional.O valor padrão é 0.
Size
Essa propriedade determina o tamanho GuiObject escalar e de pixels usando um UDim2.
O tamanho escalar é relativo ao tamanho do elemento GUI pai, se houver.
As porções de pixels do valor UDim2 são as mesmas, independentemente do tamanho da Interface gráfica do usuáriopai.Os valores representam o tamanho do objeto em pixels.O tamanho real de pixels de um Objetopode ser lido a partir da propriedade GuiBase2d.AbsoluteSize.
Se o GuiObject tiver um pai, o tamanho ao longo de cada eixo também é influenciado pelo tamanho do pai SizeConstraint.
Amostras de código
This code sample allows you to create a simple color-changing health bar using two nested Frames. Paste this into a LocalScript on the inner frame.
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
Essa propriedade define os eixos Size que o GuiObject será baseado, em relação ao tamanho de seu pai.
Essa propriedade é útil para criar objetos GUI que devem escalar com a largura ou altura de um Objetopai, mas não ambos, preservando efetivamente a proporção de aspecto do Objeto.
Visible
Essa propriedade se o GuiObject e seus descendentes serão renderizados.
A renderização de componentes individuais de um GuiObject pode ser controlada individualmente através de propriedades de transparência como GuiObject.BackgroundTransparency , TextLabel.TextTransparency e ImageLabel.ImageTransparency .
Quando esta propriedade é false , a GuiObject será ignorada por estruturas de layout como UIListLayout , UIGridLayout e UITableLayout .Em outras palavras, o espaço que o elemento de outro modo ocuparia no layout é usado por outros elementos em vez disso.
Amostras de código
This code sample adds open/close functionality to a Window UI. Paste as a LocalScript that is a sibling of a Frame named Window, a TextButton/ImageButton named Window, and a TextButton/ImageButton within the Window called Close.
local gui = script.Parent
local window = gui:WaitForChild("Window")
local toggleButton = gui:WaitForChild("ToggleWindow")
local closeButton = window:WaitForChild("Close")
local function toggleWindowVisbility()
-- Flip a boolean using the `not` keyword
window.Visible = not window.Visible
end
toggleButton.Activated:Connect(toggleWindowVisbility)
closeButton.Activated:Connect(toggleWindowVisbility)
ZIndex
Essa propriedade determina a ordem em que um GuiObject em relação aos outros.
Por padrão, renderizar em ordem crescente de prioridade onde aqueles com valores mais baixos são renderizados sob aqueles com valores mais altos.Você pode alterar a ordem de renderização dentro de um ScreenGui, SurfaceGui ou BillboardGui alterando o valor de seu ZIndexBehavior .
Se você não tem certeza se precisará adicionar um elemento entre dois elementos existentes no futuro, é uma boa prática usar múltiplos de 100 ( 0 , 100 , 200 , etc.).Isso garante uma grande lacuna de valores de ordem de renderização que você pode usar para elementos sobrepostos entre outros elementos.
Veja também LayoutOrder que controla a ordem de classificação de um GuiObject quando usado com uma estrutura de layout como UIListLayout ou UIGridLayout .
Métodos
TweenPosition
Mova suavemente uma GUI para uma nova posição UDim2 no tempo especificado usando o especificado Enum.EasingDirection e Enum.EasingStyle.
Essa função retornará se o tween vai jogar.Não tocará se outro pré-adolescente estiver agindo no GuiObject e o parâmetro de substituição for false.
Veja também GuiObject:TweenSize() e GuiObject:TweenSizeAndPosition().
Parâmetros
Para onde a GUI deve se mover.
A direção na qual facilitar a GUI para o final da posição.
O estilo em que facilitar a GUI para o finalPosition.
Quanto tempo, em segundos, o pré-adolescente deve levar para completar.
Se o adolescente substituirá um interseçãoem andamento.
Uma função de retorno de chamada para executar quando o tween concluir.
Devolução
Se o pré-adolescente vai jogar.
Amostras de código
This code sample demonstrates a more involved usage of TweenPosition by detecting when the tween completes/cancels by defining a callback function. It also prints whether the tween will play.
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
Redimensiona suavemente um GuiObject para um novo UDim2 no tempo especificado usando o especificado Enum.EasingDirection e Enum.EasingStyle.
Essa função retornará se o tween vai jogar.Normalmente, isso sempre retornará true, mas retornará false se outro pré-adolescente estiver ativo e a substituição for definida como false .
Veja também GuiObject:TweenSize() e GuiObject:TweenSizeAndPosition().
Parâmetros
O tamanho que a GUI deve redimensionar.
A direção na qual facilitar a GUI para o tamanho final.
O estilo em que facilitar a GUI para o tamanho final.
Quanto tempo, em segundos, o pré-adolescente deve levar para completar.
Se o adolescente substituirá um interseçãoem andamento.
Uma função de retorno de chamada para executar quando o tween concluir.
Devolução
Se o pré-adolescente vai jogar.
Amostras de código
This code sample demonstrates the usage of the GuiObject:TweenSize() function. It initiates an animation on the parent's GuiObject.Size property to UDim2.new(0.5, 0, 0.5, 0), which is half the GuiObject's parent size on both axes.
Additionally, it demonstrates how the callback parameter can be used to detect when the tween stops (whether it was cancelled by another tween or completed).
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
Redimensiona e move suavemente uma GUI para um novo tamanho e posição UDim2 usando o especificado Enum.EasingDirection e Enum.EasingStyle.
Essa função retornará se o tween vai jogar.Normalmente, isso sempre retornará true, mas retornará false se outro pré-adolescente estiver ativo e a substituição for definida como false .
Veja também GuiObject:TweenSize() e GuiObject:TweenSizeAndPosition().
Parâmetros
O tamanho que a GUI deve redimensionar.
Para onde a GUI deve se mover.
A direção na qual facilitar a GUI para o tamanho final e posição final.
O estilo em que facilitar a GUI para o tamanho final e posição final.
Quanto tempo, em segundos, o pré-adolescente deve levar para completar.
Se o adolescente substituirá um interseçãoem andamento.
Uma função de retorno de chamada para executar quando o tween concluir.
Devolução
Se o pré-adolescente vai jogar.
Amostras de código
The below example would tween a Frame to the top left of the parent's size and resize it down to 0.
local frame = script.Parent.Frame
frame:TweenSizeAndPosition(UDim2.new(0, 0, 0, 0), UDim2.new(0, 0, 0, 0))
Eventos
InputBegan
Este evento é disparado quando um usuário começa a interagir com o GuiObject uma interface de usuário humano-computador (botão do mouse para baixo, toque começar, botão da tecla para baixo, etc).
O UserInputService tem um evento de nome similar que não é restrito a um elemento de UI específico: UserInputService.InputBegan .
Este evento sempre será disparado, independentemente do estado do jogo.
Veja também GuiObject.InputEnded e GuiObject.InputChanged.
Parâmetros
Um InputObject, que contém dados úteis para consultar a entrada do usuário, como o type of input, state of input e screen coordinates of the input.
Amostras de código
The following example demonstrates one of many usage examples of handling user input from InputBegan depending on its type.
In order for this to work as expected, it must be placed in a LocalScript and a child of gui.
-- 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
Este evento dispara 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 do teclado para baixo, etc).
O UserInputService tem um evento de nome similar que não é restrito a um elemento de UI específico: UserInputService.InputChanged .
Este evento sempre será disparado, independentemente do estado do jogo.
Veja também GuiObject.InputBegan e GuiObject.InputEnded.
Parâmetros
Um InputObject, que contém dados úteis para consultar a entrada do usuário, como o type of input, state of input e screen coordinates of the input.
Amostras de código
The following example demonstrates one of many usage examples of handling user input from InputChanged depending on its type.
In order for this to work as expected, it must be placed in a LocalScript and a child of gui.
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
O evento InputEnded é acionado quando um usuário para de interagir através de um dispositivo de Interface Humano-Computador (botão do mouse para baixo, toque começa, botão de teclado para baixo, etc).
O UserInputService tem um evento de nome similar que não é restrito a um elemento de UI específico: UserInputService.InputEnded .
Este evento sempre será disparado, independentemente do estado do jogo.
Veja também GuiObject.InputBegan e GuiObject.InputChanged.
Parâmetros
Um InputObject, que contém dados úteis para consultar a entrada do usuário, como o Enum.UserInputType, Enum.UserInputState e InputObject.Position.
Amostras de código
The following example demonstrates one of many usage examples of handling user input from InputEnded depending on its type.
In order for this to work as expected, it must be placed in a LocalScript and a child of gui.
-- 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
O evento MouseEnter é acionado quando um usuário move o mouse para um elemento GuiObject.
Por favor, não confie nos argumentos x e y passados por este evento como uma maneira infalível de determinar onde o mouse do usuário está quando entra em uma Interface gráfica do usuário.Essas coordenadas podem variar mesmo quando o mouse entra na GUI através da mesma borda - especialmente quando o mouse entra no elemento rapidamente.Isso ocorre porque as coordenadas indicam a posição do mouse quando o evento é disparado, ao invés do momento exato em que o mouse entra na Interface gráfica do usuário.
Este evento dispara mesmo quando o elemento GUI é renderizado abaixo de outro elemento.
Se você quiser rastrear quando o mouse de um usuário deixa um elemento de GUI, você pode usar o evento GuiObject.MouseLeave.
Veja também
Parâmetros
A coordenada de tela do mouse X em pixels, em relação ao canto superior esquerdo da tela.
A coordenada de tela do mouse Y em pixels, em relação ao canto superior esquerdo da tela.
Amostras de código
The following example prints the mouse location, in pixels, when it enters GUI element.
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)
MouseLeave
O evento MouseLeave dispara quando um usuário move o mouse para fora de um elemento GuiObject.
Por favor, não confie nos argumentos x e y passados por este evento como uma maneira infalível de determinar onde o mouse do usuário está quando ele sai de uma Interface gráfica do usuário.Essas coordenadas podem variar mesmo quando o mouse deixa a GUI através da mesma borda - especialmente quando o mouse deixa o elemento rapidamente.Isso ocorre porque as coordenadas indicam a posição do mouse quando o evento é disparado, ao invés do momento exato em que o mouse deixa a Interface gráfica do usuário.
Este evento dispara mesmo quando o elemento GUI é renderizado abaixo de outro elemento.
Veja também
Parâmetros
A coordenada de tela do mouse X em pixels, em relação ao canto superior esquerdo da tela.
A coordenada de tela do mouse Y em pixels, em relação ao canto superior esquerdo da tela.
MouseMoved
Incêndios sempre que um usuário move o mouse enquanto ele está dentro de um elemento GuiObject.É semelhante a Mouse.Move, que dispara independentemente se o mouse do usuário está sobre um elemento de GUI.
Observe, este evento dispara quando a posição do mouse é atualizada, portanto, ele disparará repetidamente enquanto for movido.
Os argumentos x e y indicam as coordenadas atualizadas da tela do mouse do usuário em pixels.Estes podem ser úteis para determinar a localização do mouse na Interface gráfica do usuário, na tela e no delta desde a posição anterior do mouse se ele estiver sendo rastreado em uma variável global.
O código abaixo mostra como determinar o deslocamento Vector2 do mouse do usuário em relação a um elemento de GUI:
local Players = game:GetService("Players")
local CustomScrollingFrame = script.Parent
local SubFrame = CustomScrollingFrame:FindFirstChild("SubFrame")
local mouse = Players.LocalPlayer:GetMouse()
local function getPosition(X, Y)
local gui_X = CustomScrollingFrame.AbsolutePosition.X
local gui_Y = CustomScrollingFrame.AbsolutePosition.Y
local pos = Vector2.new(math.abs(X - gui_X), math.abs(Y - gui_Y - 36))
print(pos)
end
CustomScrollingFrame.MouseMoved:Connect(getPosition)
Observe que este evento pode não disparar exatamente quando o mouse do usuário entra ou sai de um elemento de GUI.Portanto, os argumentos x e y podem não combinar perfeitamente com as coordenadas dos cantos da Interface gráfica do usuário.
Veja também
Parâmetros
A coordenada de tela do mouse X em pixels, em relação ao canto superior esquerdo da tela.
A coordenada de tela do mouse Y em pixels, em relação ao canto superior esquerdo da tela.
MouseWheelBackward
O evento WheelBackward atira quando um usuário rola a roda do mouse para trás quando o mouse está sobre um elemento GuiObject.É semelhante a Mouse.WheelBackward, que dispara independentemente se o mouse do usuário está sobre um elemento de GUI.
Este evento dispara apenas como um indicador do movimento retrógrado da roda.Isso significa que os argumentos de coordenada do mouse x e y não mudam como resultado desse evento.Essas coordenadas só mudam quando o mouse se move, o que pode ser rastreado pelo evento GuiObject.MouseMoved.
Veja também
Parâmetros
A coordenada de tela do mouse X em pixels, em relação ao canto superior esquerdo da tela.
A coordenada de tela do mouse Y em pixels, em relação ao canto superior esquerdo da tela.
MouseWheelForward
O evento WheelForward é acionado quando um usuário rola a roda do mouse para a frente quando o mouse está sobre um elemento GuiObject.É semelhante a Mouse.WheelForward, que dispara independentemente se o mouse do usuário está sobre um elemento de GUI.
Este evento dispara apenas como um indicador do movimento em frente da roda.Isso significa que os argumentos de coordenada do mouse X e Y não mudam como resultado desse evento.Essas coordenadas só mudam quando o mouse se move, o que pode ser rastreado pelo evento GuiObject.MouseMoved.
Veja também
Parâmetros
A coordenada de tela do mouse X em pixels, em relação ao canto superior esquerdo da tela.
A coordenada Y do mouse do usuário.
SelectionGained
Este evento é disparado quando o seletor de Gamepad começa a se concentrar no GuiObject.
Se você quiser verificar a partir do Gamepad selecionar paradas de focar no elemento GUI, você pode usar o evento GuiObject.SelectionLost.
Quando uma GUI ganha foco de seleção, o valor da propriedade SelectedObject também muda para a que ganha seleção.Para determinar qual GUI ganhou seleção, verifique o valor dessa propriedade.
Amostras de código
The following example prints a message when the user selects the object with a gamepad.
In order for this to work as expected, it must be placed in a LocalScript and a child of gui.
local guiObject = script.Parent
local function selectionGained()
print("The user has selected this button with a gamepad.")
end
guiObject.SelectionGained:Connect(selectionGained)
SelectionLost
Este evento é disparado quando o seletor de Gamepad para de se concentrar no GuiObject.
Se você quiser verificar a partir do Gamepad seleciona começa a se concentrar no elemento GUI, você pode usar o evento GuiObject.SelectionGained.
Quando uma GUI perde o foco de seleção, o valor da propriedade SelectionObject muda para nil ou para o elemento da GUI que ganha foco de seleção.Para determinar qual GUI ganhou seleção, ou se nenhuma GUI é selecionada, verifique o valor dessa propriedade.
Amostras de código
The following example prints a message when the element has its focus lost on a gamepad.
In order for this to work as expected, it must be placed in a LocalScript and a child of gui.
local guiObject = script.Parent
local function selectionLost()
print("The user no longer has this selected with their gamepad.")
end
guiObject.SelectionLost:Connect(selectionLost)
TouchLongPress
Este evento dispara após um breve momento em que o jogador mantém o dedo na interface de usuário usando um dispositivo com suporte a toque.Dispara com uma tabela de Vector2 que descreve as posições relativas das telas dos dedos envolvidos no gesto.Além disso, ele dispara várias vezes: Enum.UserInputState.Begin após um breve atraso, Enum.UserInputState.Change se o jogador mover o dedo durante o gesto e, finalmente, Enum.UserInputState.End .O atraso é dependente da plataforma; no Studio é um pouco maior que um segundo.
Como este evento só requer um dedo, este evento pode ser simulado no Studio usando o emulador e um mouse.
Parâmetros
Um array de Vector2 que descreve as posições relativas dos dedos envolvidos no gesto.
Um Enum.UserInputState que descreve o estado do gesto:
- Comece incêndios uma vez no início do gesto (depois do breve atraso)
- Altere os fogos se o jogador mover o dedo enquanto pressiona para baixo
- Acabe com os incêndios uma vez no final do gesto quando eles liberarem seu dedo.
Amostras de código
This code sample allows the player to manipulate the screen position of some UI element, like a Frame, by holding down on the UI element for a brief moment. Then, the player moves their finger and releases. During the gesture the Frame is colored blue with a white outline.
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
Este evento é disparado quando o jogador move o dedo sobre o elemento da interface usando um dispositivo com suporte a toque.Ele dispara pouco antes de GuiObject.TouchSwipe dispara, e não dispara com GuiObject.TouchTap.Este evento é útil para permitir que o jogador manipule a posição de elementos de UI na tela.
Este evento dispara com uma tabela de Vector2 que descreve as posições relativas das telas dos dedos envolvidos no gesto.Além disso, dispara várias vezes: Enum.UserInputState.Begin após um breve atraso, Enum.UserInputState.Change quando o jogador move o dedo durante o gesto e, finalmente, com Enum.UserInputState.End .
Este evento não pode ser simulado no Studio usando o emulador e um mouse; você deve ter um dispositivo real habilitado para toque para dispará-lo.
Parâmetros
Um array Luau de Vector2 objetos, cada um indicando a posição de todos os dedos envolvidos no gesto.
Indica até onde o gesto da panela chegou de seu ponto de partida.
Indica quão rapidamente o gesto está sendo realizado em cada dimensão.
Indica o Enum.UserInputState da gesta.
Amostras de código
This code sample is meant to be placed in a LocalScript within an inner Frame that is inside an outer Frame, or other GuiObject. It allows the player to manipulate the position of the inner frame by moving their finger on the outer frame.
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
Este evento é disparado quando o jogador usa dois dedos para fazer um gesto de pinça ou puxar na interface de usuário usando um dispositivo com suporte a toque.Um aperto acontece quando dois ou mais dedos se aproximam, e um puxão acontece quando se afastam.Este evento dispara em conjunto com GuiObject.TouchPan .Este evento é útil para permitir que o jogador manipule o tamanho (tamanho) de elementos de UI na tela e é mais frequentemente usado para recursos de zoom.
Este evento dispara com uma tabela de Vector2 que descreve as posições relativas das telas dos dedos envolvidos no gesto.Além disso, dispara várias vezes: Enum.UserInputState.Begin após um breve atraso, Enum.UserInputState.Change quando o jogador move um dedo durante o gesto e, finalmente, com Enum.UserInputState.End .Deve-se notar que a escala deve ser usada multiplicativamente .
Como este evento requer pelo menos dois dedos, não é possível simulá-lo no Studio usando o emulador e um mouse; você deve ter um dispositivo real habilitado para toque.
Parâmetros
Um array Luau de Vector2 objetos, cada um indicando a posição de todos os dedos envolvidos no gesto de pinça.
Um float que indica a diferença a partir do início do gesto de pinça.
Um flutuador que indica quão rapidamente o gesto de pinça está acontecendo.
Indica o Enum.UserInputState da gesta.
Amostras de código
This code sample is meant for a LocalScript within an inner Frame that is inside an outer Frame, or other GuiObject. It allows the player to scale the inner frame by performing a GuiObject.TouchPinch gesture on the outer frame.
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
Este evento é disparado quando o jogador usa dois dedos para fazer um gesto de pinça ou puxar na interface de usuário usando um dispositivo com suporte a toque.A rotação ocorre quando o ângulo da linha entre dois dedos muda.Este evento dispara em conjunto com GuiObject.TouchPan .Este evento é útil para permitir que o jogador manipule a rotação de elementos de UI na tela.
Este evento dispara com uma tabela de Vector2 que descreve as posições relativas das telas dos dedos envolvidos no gesto.Além disso, dispara várias vezes: Enum.UserInputState.Begin após um breve atraso, Enum.UserInputState.Change quando o jogador move um dedo durante o gesto e, finalmente, com Enum.UserInputState.End .
Como este evento requer pelo menos dois dedos, não é possível ser simulado no Studio usando o emulador e um mouse; você deve ter um dispositivo real com toque habilitado.
Parâmetros
Um array Luau de Vector2 objetos, cada um indicando a posição de todos os dedos envolvidos no gesto.
Um flutuador que indica quanto a rotação foi reduzida desde o início do gesto.
Um flutuante que indica quão rapidamente o gesto está sendo executado.
Indica o Enum.UserInputState da gesta.
Amostras de código
This code sample is meant for a LocalScript within an inner Frame that is inside an outer Frame, or other GuiObject. It allows the player to rotate the inner frame by performing a GuiObject.TouchRotate gesture on the outer frame.
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
Este evento é disparado quando o jogador executa um gesto de deslize no elemento da interface usando um dispositivo habilitado para toque.Dispara com a direção do gesto (Acima, Baixo, Esquerda ou Direita) e o número de pontos de toque envolvidos no gesto.Os gestos de deslize são frequentemente usados para alterar abas em interfaces móveis.
Como este evento só requer um dedo, ele pode ser simulado no Studio usando o emulador e um mouse.
Parâmetros
Um Enum.SwipeDirection indicando a direção do gesto de deslize (Para cima, Para baixo, Para a esquerda ou Para a direita).
O número de pontos de toque envolvidos no gesto (geralmente 1).
Amostras de código
This code sample will cause a Frame (or other GuiObject) to bounce when a swipe gesture is performed on a touch-enabled device (or Studio's emulator). Horizontal swipes will change the hue of the GuiObject.BackgroundColor3, while vertical swipes will change the saturation.
local frame = script.Parent
frame.Active = true
-- How far the frame should bounce on a successful swipe
local BOUNCE_DISTANCE = 50
-- Current state of the frame
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)
-- Change the BackgroundColor3 based on the swipe direction
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
-- Update the color and bounce the frame a little
updateColor()
frame.Position = basePosition + deltaPos
frame:TweenPosition(basePosition, Enum.EasingDirection.Out, Enum.EasingStyle.Bounce, 0.7, true)
end
frame.TouchSwipe:Connect(onTouchSwipe)
updateColor()
TouchTap
Este evento é disparado quando o jogador realiza um gesto de toque no elemento da interface usando um dispositivo habilitado para toque.Um toque é um toque rápido sem qualquer movimento envolvido (um pressionamento mais longo dispararia GuiObject.TouchLongPress , e mover durante o toque dispararia GuiObject.TouchPan e/ou GuiObject.TouchSwipe ).Dispara com uma tabela de Vector2 objetos que descrevem as posições relativas dos dedos envolvidos no gesto.
Como este evento só requer um dedo, ele pode ser simulado no Studio usando o emulador e um mouse.
Parâmetros
Amostras de código
This code sample will toggle the GuiObject.BackgroundTransparency of a UI element, like a Frame, when it is tapped on a touch-enabled device.
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)