GuiObject
*Este contenido se traduce usando la IA (Beta) y puede contener errores. Para ver esta página en inglés, haz clic en aquí.
GuiObject es una clase abstracta (mucho como BasePart ) para un objeto de interfaz de usuario 2D.Define todas las propiedades relacionadas con la visualización de un objeto de interfaz gráfica de usuario (Interfaz gráfica (o GUI)), como Size y Position.También tiene algunas propiedades útiles de solo lectura como AbsolutePosition , AbsoluteSize y AbsoluteRotation .
Para manipular el diseño de objetos GUI de manera especial, puedes usar una estructura de diseño como lista/flex o cuadrícula , y puedes estilarlos más allá de sus propiedades principales a través de modificadores de apariencia .
Aunque es posible detectar eventos de botones de ratón en cualquier objeto GUI usando InputBegan y InputEnded, solo ImageButton y TextButton tienen eventos convenientes dedicados como Activated para detectar clics/presiones.
Resumen
Propiedades
Determina si este elemento de interfaz de usuario sienta la entrada.
Determina el punto de origen de un GuiObject , relativo a su tamaño absoluto.
Determina si se produce un redimensionamiento basado en el contenido de los hijos.
Determina el color de fondo GuiObject.
Determina la transparencia del fondo y del borde GuiObject.
Determina el color del borde GuiObject .
Determina de qué manera se coloca el borde GuiObject relativo a sus dimensiones.
Determina el ancho de píxel del borde GuiObject .
Determina si el descendiente GuiObjects fuera de los límites de un elemento GUI padre debe Renderizar.
Determina si el mouse del jugador está presionado activamente en el GuiObject o no.
Determina si el GuiButton se puede interactuar o no, o si el GuiState del GuiObject está cambiando o no.
Controla el orden de clasificación del GuiObject cuando se usa con un UIGridStyleLayout .
Establece el GuiObject que se seleccionará cuando el selector de gamepad se mueva hacia abajo.
Establece el GuiObject que se seleccionará cuando el seleccionador de gamepad se mueva a la izquierda.
Establece el GuiObject que se seleccionará cuando el seleccionador de gamepad se mueva a la derecha.
Establece el GuiObject que se seleccionará cuando el seleccionador de gamepad se mueva hacia arriba.
Determina la posición píxel y escalar del GuiObject .
Determina el número de grados por los cuales se gira el GuiObject .
Determine si el GuiObject se puede seleccionar por un controlador para juego.
Anula el adorno de selección predeterminado utilizado para los gamepads.
El orden de GuiObjects seleccionado por la selección de la interfaz de usuario del gamepad.
Determina el tamaño píxel y escalar del GuiObject .
Establece los ejes Size que el GuiObject se basará, en relación con el tamaño de su padre.
Una propiedad mixta de BackgroundTransparency y TextTransparency.
Determina si se renderizarán los GuiObject y sus descendientes.
Determina el orden en que un GuiObject renderiza en relación con los demás.
Propiedades
Describe la posición actual de la pantalla de un elemento GuiBase2d , en píxeles.
Describe la rotación de la pantalla actual de un elemento GuiBase2d en grados.
Describe el tamaño de la pantalla actual de un elemento GuiBase2d , en píxeles.
Cuando se establece en true, la localización se aplicará a este GuiBase2d y a sus descendientes.
Una referencia a un LocalizationTable para usar para aplicar localización automatizada a este GuiBase2d y sus descendientes.
Personaliza el comportamiento de selección del gamepad en la dirección de abajo.
Personaliza el comportamiento de selección del gamepad en la dirección izquierda.
Personaliza el comportamiento de selección del gamepad en la dirección correcta.
Personaliza el comportamiento de selección del gamepad en la dirección de arriba.
Permite la personalización del movimiento de selección del gamepad.
Métodos
- TweenPosition(endPosition : UDim2,easingDirection : Enum.EasingDirection,easingStyle : Enum.EasingStyle,time : number,override : boolean,callback : function):boolean
Mueve suavemente una GUI a una nueva 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
Mueve suavemente una GUI a un nuevo tamaño y posición.
Eventos
Despedido cuando un usuario comienza a interactuar a través de un dispositivo de interfaz humana-computadora (botón del mouse hacia abajo, toque de inicio, botón de teclado hacia abajo, etc.).
Despedido cuando un usuario cambia la forma en que interactúa a través de un dispositivo de interfaz humana-computadora (botón del mouse hacia abajo, toque de inicio, botón de teclado hacia abajo, etc.).
Despedido cuando un usuario deja de interactuar a través de un dispositivo de interfaz humana-ordenador (botón del ratón hacia abajo, toque de inicio, botón de teclado hacia abajo, etc.).
Se activa cuando un usuario mueve el mouse a un elemento de interfaz gráfica.
Se activa cuando un usuario mueve el mouse fuera de un elemento de interfaz gráfica.
Se activa cada vez que un usuario mueve el mouse mientras está dentro de un elemento de interfaz gráfica.
Se activa cuando un usuario desplaza la rueda del ratón hacia atrás cuando el ratón está sobre un elemento de interfaz gráfica.
Se activa cuando un usuario desplaza la rueda del ratón hacia adelante cuando el ratón está sobre un elemento de interfaz gráfica.
Se desfija cuando el GuiObject se está enfocando con el seleccionador de Gamepad.
Despedido cuando el seleccionador de Gamepad deja de centrarse en el GuiObject.
Se enciende cuando el jugador comienza, continúa y detiene presionando largamente el elemento de la interfaz de usuario.
- TouchPan(touchPositions : Array,totalTranslation : Vector2,velocity : Vector2,state : Enum.UserInputState):RBXScriptSignal
Se activa cuando el jugador mueve el dedo en el elemento de la interfaz de usuario.
- TouchPinch(touchPositions : Array,scale : number,velocity : number,state : Enum.UserInputState):RBXScriptSignal
Se activa cuando el jugador realiza un gesto de pinzamiento o de tiro usando dos dedos en el elemento de la interfaz de usuario.
- TouchRotate(touchPositions : Array,rotation : number,velocity : number,state : Enum.UserInputState):RBXScriptSignal
Se activa cuando el jugador realiza un gesto de rotación usando dos dedos en el elemento de la interfaz de usuario.
Se activa cuando el jugador realiza un gesto de deslizamiento en el elemento de la interfaz de usuario.
Se activa cuando el jugador realiza un gesto de toque en el elemento de la interfaz de usuario.
Eventos
- SelectionChanged(amISelected : boolean,previousSelection : GuiObject,newSelection : GuiObject):RBXScriptSignal
Se enciende cuando la selección del gamepad se mueve a, deja o cambia dentro del conectado GuiBase2d o cualquier descendiente GuiObjects .
Propiedades
Active
Muestras 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
Muestras de código
local guiObject = script.Parent
while true do
-- Superior izquierda
guiObject.AnchorPoint = Vector2.new(0, 0)
guiObject.Position = UDim2.new(0, 0, 0, 0)
task.wait(1)
-- Superior
guiObject.AnchorPoint = Vector2.new(0.5, 0)
guiObject.Position = UDim2.new(0.5, 0, 0, 0)
task.wait(1)
-- Derecha superior
guiObject.AnchorPoint = Vector2.new(1, 0)
guiObject.Position = UDim2.new(1, 0, 0, 0)
task.wait(1)
-- Izquierda
guiObject.AnchorPoint = Vector2.new(0, 0.5)
guiObject.Position = UDim2.new(0, 0, 0.5, 0)
task.wait(1)
-- Centro muerto
guiObject.AnchorPoint = Vector2.new(0.5, 0.5)
guiObject.Position = UDim2.new(0.5, 0, 0.5, 0)
task.wait(1)
-- Derecha
guiObject.AnchorPoint = Vector2.new(1, 0.5)
guiObject.Position = UDim2.new(1, 0, 0.5, 0)
task.wait(1)
-- Inferior izquierda
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 derecha
guiObject.AnchorPoint = Vector2.new(1, 1)
guiObject.Position = UDim2.new(1, 0, 1, 0)
task.wait(1)
end
AutomaticSize
Muestras de código
-- Array de etiquetas de texto/fuentes/tamaños para imprimir
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 },
}
-- Crear un marco padre de tamaño 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
-- Añadir un diseño de lista
local listLayout = Instance.new("UIListLayout")
listLayout.Padding = UDim.new(0, 5)
listLayout.Parent = parentFrame
-- Establecer esquinas redondeadas y relleno para la 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
-- Crear una etiqueta de texto de tamaño automático desde un 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
Muestras 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
Muestras de código
-- Póngame dentro de algún GuiObject, preferiblemente un ImageButton/TextButton
local button = script.Parent
local function onEnter()
button.BorderSizePixel = 2
button.BorderColor3 = Color3.new(1, 1, 0) -- Amarillo
end
local function onLeave()
button.BorderSizePixel = 1
button.BorderColor3 = Color3.new(0, 0, 0) -- Negro
end
-- Conectar eventos
button.MouseEnter:Connect(onEnter)
button.MouseLeave:Connect(onLeave)
-- Nuestro estado predeterminado es "no se ha desplazado"
onLeave()
BorderMode
BorderSizePixel
Muestras de código
-- Póngame dentro de algún GuiObject, preferiblemente un ImageButton/TextButton
local button = script.Parent
local function onEnter()
button.BorderSizePixel = 2
button.BorderColor3 = Color3.new(1, 1, 0) -- Amarillo
end
local function onLeave()
button.BorderSizePixel = 1
button.BorderColor3 = Color3.new(0, 0, 0) -- Negro
end
-- Conectar eventos
button.MouseEnter:Connect(onEnter)
button.MouseLeave:Connect(onLeave)
-- Nuestro estado predeterminado es "no se ha desplazado"
onLeave()
ClipsDescendants
GuiState
Interactable
LayoutOrder
NextSelectionDown
Muestras de código
-- Configura la cuadrícula de selección del gamepad usando el código a continuación
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
-- Borde izquierdo
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Borde derecho
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Arriba
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- A continuación
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Prueba la cuadrícula de selección del Gamepad usando el código a continuación
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
Muestras de código
-- Configura la cuadrícula de selección del gamepad usando el código a continuación
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
-- Borde izquierdo
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Borde derecho
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Arriba
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- A continuación
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Prueba la cuadrícula de selección del Gamepad usando el código a continuación
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
Muestras de código
-- Configura la cuadrícula de selección del gamepad usando el código a continuación
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
-- Borde izquierdo
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Borde derecho
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Arriba
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- A continuación
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Prueba la cuadrícula de selección del Gamepad usando el código a continuación
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
Muestras de código
-- Configura la cuadrícula de selección del gamepad usando el código a continuación
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
-- Borde izquierdo
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Borde derecho
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Arriba
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- A continuación
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Prueba la cuadrícula de selección del Gamepad usando el código a continuación
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
Muestras 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
Muestras 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
Muestras 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()
-- Girar un booleano usando la palabra clave `not`
window.Visible = not window.Visible
end
toggleButton.Activated:Connect(toggleWindowVisbility)
closeButton.Activated:Connect(toggleWindowVisbility)
ZIndex
Métodos
TweenPosition
Parámetros
Devuelve
Muestras 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
Devuelve
Muestras 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
Devuelve
Muestras 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
Muestras 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
Muestras 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
Muestras 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
Muestras 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
Muestras 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
Muestras 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
Muestras 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
Muestras 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
Muestras 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
Muestras 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
Muestras de código
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
Parámetros
Muestras 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)