GuiObject 是一个抽象类 (就像 BasePart 一样) 对 2D 用户界面对象。它定义了与
要特殊地操作图形用户界面对象的布局,您可以使用列表/灵活或网格结构,并通过外观模式调整其核心属性。
虽然您可以使用 InputBegan 和 InputEnded 来检测鼠标按钮事件,但只有 ImageButton 和 1> Class.TextButton1> 有便利的专用
概要
属性
确定是否同时输入。
对 GuiObject 的起始位置,相对于其绝对大小。
决定是否按照子内容进行调整。
确定 GuiObject 背景颜色。
确定 GuiObject 背景和边框的透明度。
确定 GuiObject 边框的颜色。
确定GuiObject边界的方式是与其尺寸相对于其他方式。
确定 GuiObject 边框的像素宽度。
决定是否在父 GUI 元素外的子元素 GuiObjects 会渲染。
确定玩家是否在 GuiObject 上主动按着。
确定 GuiButton 是否可以与或不可以与之交互,或 GuiState 的 GuiObject 是否正在变更或不变更。
控制使用 GuiObject 与 UIGridStyleLayout 时的排序顺序。
设置 GuiObject 将在游戏手柄选择器向下移动时选择。
设置 GuiObject 将在游戏手柄选择器移动到左侧时选择。
设置 GuiObject ,该选项卡将在游戏手柄选择器移动到右侧时被选中。
设置 GuiObject ,该选项卡将在游戏手柄选择器上移动时选择。
确定 GuiObject 的像素和向量位置。
确定GuiObject的旋转角度。
确定游戏手柄是否可以选择GUI。
覆盖游戏手柄的默认装饰。
游戏手柄选择 GuiObjects 的顺序。
确定 GuiObject 的像素和浮点大小。
设置 Size 轴,其父元素对象的大小将对应于其大小。
Class.GuiObject.BackgroundTransparency|BackgroundTransparency 和 TextTransparency 的混合属性。
确定 GuiObject 和它的子代是否会被渲染。
确定GuiObject 在其他人的相对位置上渲染的顺序。
描述 UI 元素的实际屏幕位置,以像素计。
描述 UI 元素的实际屏幕旋转度。
描述 UI 元素的实际屏幕大小,以像素计。
设置为“真”时,本地化将被应用到此 GuiBase2d 和它的子代。
一个引用 LocalizationTable 用于应用自动本地化到此 GuiBase2d 和它的子代。
在下向方向中自定义游戏手柄选择行为。
在左向向选择游戏手柄的行为进行自定义。
自定义游戏手柄选择行为在正确的方向。
在上向方向中自定义游戏手柄选择行为。
允许自定义游戏手柄选择移动。
方法
- TweenPosition(endPosition : UDim2,easingDirection : Enum.EasingDirection,easingStyle : Enum.EasingStyle,time : number,override : bool,callback : function):bool
顺滑地将一个 GUI 移到一个新的 UDim2 。
- TweenSize(endSize : UDim2,easingDirection : Enum.EasingDirection,easingStyle : Enum.EasingStyle,time : number,override : bool,callback : function):bool
无缝地将 GUI 重新 UDim2 。
- TweenSizeAndPosition(endSize : UDim2,endPosition : UDim2,easingDirection : Enum.EasingDirection,easingStyle : Enum.EasingStyle,time : number,override : bool,callback : function):bool
无缝地将 GUI 移到新的大小和位置。
活动
发生在用户开始通过人类-计算机界面设备(鼠标按钮,触摸开始,键盘按钮,等等)进行交互时。
发生在用户改变通过人类-计算机界面设备(鼠标按钮向下,触摸开始,键盘按钮向下等)的交互方式时。
发生在用户停止通过人类-计算机界面设备(鼠标按钮向下,触摸开始,键盘按钮向下等)的交互。
当用户将鼠标移动到 GUI 元素时,它会发生。
当用户移动鼠标时,发生。
在用户移动鼠标时,每当它在 GUI 元素内时,它就会发生。
当用户回到鼠标轮时,火焰会在鼠标上方的 GUI 元素上燃烧。
当鼠标位于 GUI 元素上时,用户会滚动鼠标轮。
当 Gamepad 选择器对 GuiObject 时,发生了焦点错误。
当游戏手柄选择器停止对 GuiObject 的焦点时发生。
在玩家开始时,持续并停止长按 UI 元素。
- TouchPan(touchPositions : Array,totalTranslation : Vector2,velocity : Vector2,state : Enum.UserInputState):RBXScriptSignal
当玩家移动其手指时,触发 UI 元素。
- TouchPinch(touchPositions : Array,scale : number,velocity : number,state : Enum.UserInputState):RBXScriptSignal
在玩家使用两个手指在 UI 元素上执行叠捏或拉动动作时触发。
- TouchRotate(touchPositions : Array,rotation : number,velocity : number,state : Enum.UserInputState):RBXScriptSignal
在玩家使用两个手指在 UI 元素上执行旋转动作时触发。
在玩家在 UI 元素上执行滑动手势时触发。
当玩家在 UI 元素上执行点击手势时触发。
- SelectionChanged(amISelected : bool,previousSelection : GuiObject,newSelection : GuiObject):RBXScriptSignal
在游戏手柄选择移动到,离开或更改连接的 GuiBase2d 或任何子对象。
属性
Active
此属性确定此 GuiObject 将输入沉没在 3D 空间,例如基础模型具有 ClickDetector 类似 DragDetector 。 在其他 words,如果玩家尝试用鼠标悬停在激活 UI 元素上,UI 将阻止输入从达到激活 UI 元素。
对于 GuiButton 对象 (ImageButton 和 Class.TextButton
代码示例
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
AnchorPoint 属性确定 GuiObject 的起始点,相对于其绝对大小。起始点由从哪里放置元素(通过 GuiObject.Position )和从哪里展开渲染 1> Class.GuiObject.Size1> 扩展。
请参阅这里了解有关图形和详细信息。
代码示例
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
此属性用于根据子对象的大小自动调整父对象的 UI 对象的尺寸。您可以使用此属性来在编辑或运行时将文本和其他内容添加到 UI 对象,子对象的大小将会随着内容的大小进行调整。
当 AutomaticSize 设置为 Enum.AutomaticSize 值,其他值,例如 None,这个 UI 对象可能会缩放。
了解有关该属性的使用方法和工作方式,请参阅这里。
代码示例
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
这个属性确定背景GuiObject 的颜色 (填充颜色)。如果您的元素包含文本,例如TextBox、TextButton或1> Class.TextLabel1>,请确保背景颜色与文本颜色相反。
另一个决定背景视觉属性的属性是 GuiObject.BackgroundTransparency ;如果此属性设置为 1 ,背景或边界都不会渲染。
还请参阅 BorderColor3 。
代码示例
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
此属性确定GuiObject背景和边框的透明度。它不会, however, 确定TextBox、TextButton或1>Class.TextLabel1>; 文本透明度
如果此属性设置为 1,背景或边框都不会渲染,而且GUI 背景完全透明。
BorderColor3
确定GuiObject 长方形边框的颜色(也称为线条颜色)。 这与对象的GuiObject.BackgroundColor3属性无关。 您无法看到对象的边框,如果其GuiObject.BorderSizePixel属性设置为1> 01>。
注意,UIStroke 组件允许您创建更高级的边界效果。
代码示例
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
这个属性决定使用同名枚列的 GuiObject 边界是否与其尺寸相对于其尺寸使用 Enum.BorderMode 。
注意 UIStroke 可以覆盖此属性并允许更高级的边界效果。
BorderSizePixel
此属性确定边界 GuiObject 的渲染宽度,以像素计。将其设置为 0 会禁用边界。
注意 UIStroke 可以覆盖此属性并允许更高级的边界效果。
代码示例
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
这个属性决定 whether the GuiObject 会剪切 (使其隐形) 任何与否会在长方形边界之外渲染的子元素。
注意 GuiObject.Rotation 不支持此属性。如果此或任何祖先 GUI 具有一个 非零 GuiObject.Rotation ,此属性将被忽略,并且后代 GUI 元素将无视此属性的值。
Interactable
确定 GuiButton 是否可以与或不可以与之交互,或 GuiState 的 GuiObject 是否正在变更或不变更。
在 GuiButton 上:
- 当 Interactable 设置在 GuiButton 上时,true,1> Class.GuiButton1> 将正常显示,4> Class.GuiObject.GuiState|GuiState4> 将正常显示。
在 GuiObject 上:
LayoutOrder
此属性控制使用 GuiObject (例如 UIGridStyleLayout 或 UIListLayout ) 使用 2> Class.UIGridStyleLayout.SortOrder|SortOrder2> 设置为 5>
GuiObjects 按照上升的顺序排序,其中较低的值优先于最高的值。对于具有相同值的对象,将返回其添加到的顺序。
如果您不确定在将来需要在两个现有元素之间添加元素时是否需要使用多个 100 (0 ,100 ,1> 2001> ,等等) ,这是一个良好的实践使用多个 2>2002> ,以确保您可以在其他
还请参阅ZIndex,这将对象的 渲染 顺序而不是排序顺序进行决定。
NextSelectionDown
此属性设置 GuiObject 选定时,当用户向下移动游戏手柄选择器时,选择器将显示。如果此属性为空,移动游戏手柄向下将不会更改选择的 GUI。
将游戏手柄选择器向下移动将GuiService.SelectedObject设置为此对象,除非GUI不是Selectable。 注意,此属性可以设置为Selectable,即使它不是2> Class.GuiObj.Selectable|Selectable2>
还请参阅NextSelectionUp、NextSelectionLeft和NextSelectionRight。
代码示例
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
此属性设置 GuiObject 选择时,当用户将游戏手柄选择器移动到左侧时。如果此属性为空,将游戏手柄移动到左侧不会更改选择的 GUI。
将游戏手柄选择器移动到左侧将GuiService.SelectedObject设置为此对象,除非GUI不是Selectable。注意,此属性可以设置为Selectable,即使它不是2>Class.GuiObj.Selectable|Selectable2>。因此,您应该
还请参阅 NextSelectionUp 、 NextSelectionDown 和 NextSelectionRight 。
代码示例
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
此属性设置 GuiObject 选择时,当用户将游戏手柄选择器移动到右侧时。如果此属性为空,将游戏手柄移动到右侧不会更改选择的 GUI。
将游戏手柄选择器移动到右侧将 GuiService.SelectedObject 设置为此对象,除非 GUI 为 Selectable 。注意,此属性可以设置为 GUI 元素,即使它不是 Selectable 。因此,您应该确保 GUI 选择器属
还请参阅 NextSelectionUp 、 NextSelectionDown 和 NextSelectionLeft 。
代码示例
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
此属性设置 GuiObject 选定时,当用户向上移动游戏手柄选择器时,选择器将显示。如果此属性为空,将游戏手柄向上移动不会更改选中的 GUI。
将游戏手柄选择器向上移动将GuiService.SelectedObject设置为此对象,除非Selectable。注意,此属性可以设置为Selectable,即使它不是2>Class.GuiObj.Selectable|Selectable2>。因此,您应该确保5>
还参阅 NextSelectionDown , NextSelectionLeft , NextSelectionRight 。
代码示例
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
这个属性使用一个 GuiObject 来确定 UDim2 像素和轴向位置。位置位于对象的 GuiObject.AnchorPoint 。
该指向向父 GUI 元素的大小,如有。
Datatype.UDim2 的像素部分无论父级 GUI 的大小都是相同的。这些值代表对象在像素上的位置。一个对象的实际像素位置可以从 GuiBase2d.AbsolutePosition 属性阅读。
Rotation
此属性确定旋转GuiObject的旋转数度。旋转与对象的中心 不 是 Class.GuiObject.AnchorPoint|AnchorPoint ,这意味着您无法改变旋转点。此外,此属性与1> Class.GuiObject.ClipsDescendants|ClipsDescendants1>不
Selectable
此属性确定是否可以使用游戏手柄导航 GUIs 时选择 GuiObject 。
如果此属性是真的,可以选择一个图形用户界面。选择一个图形用户界面也会设置该对象的 GuiService.SelectedObject 属性。
当此为错误时,GUI 不能被选择。 但将此设置为错误,当 GUI 被选择时,它不会取消选择,也不会更改 GuiService.SelectedObject 属性的值。
添加 GuiObject.SelectionGained 和 GuiObject.SelectionLost 将不会为元素发射。要选择一个 GuiObject,您必须更改 GuiService.SelectedObject 属性。
这个属性有助于在 GUI 通过此类属性如此 GuiObject.NextSelectionUp 、 GuiObject.NextSelectionDown 、 NextSelectionRight 或
代码示例
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
此属性覆盖了游戏手柄的默认装饰。
注意,选择的 SelectionImageObject 覆盖了选定的 GuiObject 与图像的 Size 。为了获得最佳结果,您应该通过缩放 1> Datatype.UDim21> 值来帮助确保对象正确缩放在选定的元素上。
只有将SelectionImageObject更改为GuiObject元素,才会影响该元素。要影响所有用户的GUI元素,请设置PlayerGui.SelectionImageObject属性。
要确定或设置用户选择哪个图形用户界面元素,您可以使用 GuiService.SelectedObject 属性。玩家使用游戏手柄选择不同的图形用户界面元素,并且调用 Class.GuiObject.NextSelectionUp|
SelectionOrder
选择顺序较低的 GuiObjects 会在开始游戏手柄选择或调用 GuiService:Select() 时选择更早,而不是开始游戏手柄选择或调用 Class.GuiService:Select 时选择。这个属性不会影响方向导航。默认值为 0。
Size
这个属性使用一个 GuiObject 使其在 UDim2 的平面图形中确定其大小。
指数大小与父级图形用户界面元素的大小相对,如果有。
Datatype.UDim2 的像素部分的值与父级 GUI 的大小无论如何都是相同的。这些值代表对象在像素级别上的大小。一个对象的实际像素大小可以从GuiBase2d.AbsoluteSize 属性读取。
如果 GuiObject 有一个父元素,其在每个轴上的大小也受到父元素级的 SizeConstraint 的影响。
代码示例
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
Visible
这个属性是否会渲染 GuiObject 和它的子集。
Class.GuiObject 的个〔 Class.GuiObject.BackgroundTransparency 〕〔 Class.TextLabel.TextTransparency 〕〔 Class.ImageLabel.ImageTransparency 〕〔 通过控制透明度属性,例如 GuiObject.BackgroundTransparency 、 TextLabel.TextTransparency 和 1>Class.ImageLabel.ImageTransparency1> 来控制个〔 Class.Gui
当此属性为 false 时,GuiObject 将被 layout 结构,例如 UIListLayout 、 1> Class.UIGridLayout1> 和 4> Class.UITableLayout4> 忽略。 在其他 words,元素的空间将被其他元素占用。
代码示例
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
这个属性决定GuiObject的渲染顺序与其他人相对。
默认情况下,GuiObjects 按默认排序顺序在上升的优先级顺序中渲染,其中具有较低 ZIndex 值的人被高值的人所替换。您可以在 ZIndex 、 ScreenGui
如果您不确定在将来需要在两个现有元素之间添加元素时是否需要使用多个 100 (0 ,100 ,1> 2001> ,等等) 。这确保大范围的渲染顺序值,您可以使用它们来层次化其他元素。
还请参阅 LayoutOrder ,该操作可以控制 Class.GuiObject 的排序顺序,如果与布局结构 GuiObject 或 2>Class.UIGridLayout2> 类似。
方法
TweenPosition
使用指定的 Datatype.UDim2 位置在指定时间内使用指定的 Enum.EasingDirection 和 Enum.EasingStyle 移动图形用户界面到新位置。
此函数将返回是否播游玩 тви恩。它不会播放,如果另一个 тви恩正在 GuiObject 上演出,并且覆盖参数是 false。
还请参阅:
- GuiObject:TweenSize() , tweens 一个 GUI 的大小
- GuiObject:TweenSizeAndPosition(),同步调整 GUI 的大小和位置
参数
GUI 应该放置在哪里。
向哪里轻松导航 GUI 到 endPosition。
用于将图形用户界面轻松地移动到endPosition的样式。
在秒内,调整曲线需要多久。
否定义渐变会覆盖进行中的补间动画。
调用函数,当渐变完成时执行。
返回
是否游玩放 tween。
代码示例
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
使用指定的 Datatype.UDim2 在指定时间内使 GUI 重新处理为新的 Enum.EasingDirection 。
此函数将返回是否播游玩。 通常这会总是返回 true,但如果另一个 твиен处于运行状态并且设置为 false ,就会返回 false。
还请参阅:
- GuiObject:TweenPosition(), tweens 一个 GUI 的位置
- GuiObject:TweenSizeAndPosition(),同步调整 GUI 的大小和位置
参数
图形用户界面的尺寸。
向哪里轻松导航 GUI 到 endSize。
用于将图形用户界面轻松适应到endSize的样式。
在秒内,调整曲线需要多久。
否定义渐变会覆盖进行中的补间动画。
调用函数,当渐变完成时执行。
返回
是否游玩放 tween。
代码示例
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
使用指定的 Datatype.UDim2 尺寸和位置,在指定时间内使 GUI 自动调整为新的尺寸和位置,使用指定的 Enum.EasingDirection 和 Enum.EasingStyle 。
此函数将返回是否播游玩。 通常这会总是返回 true,但如果另一个 твиен处于运行状态并且设置为 false ,就会返回 false。
还请参阅:
- GuiObject:TweenSize() , tweens 一个 GUI 的大小
- GuiObject:TweenPosition(), tweens 一个 GUI 的位置
参数
图形用户界面的尺寸。
GUI 应该放置在哪里。
向哪里轻松导航图形用户界面到endSize和endPosition。
用于轻松调整 GUI 到 endSize 和 endPosition 的样式。
在秒内,调整曲线需要多久。
否定义渐变会覆盖进行中的补间动画。
调用函数,当渐变完成时执行。
返回
是否游玩放 tween。
代码示例
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))
活动
InputBegan
当用户使用人-电脑界面设备(鼠标按钮、触摸开始、键盘按钮等)与GuiObject交互时,此事件将触发。
Class.UserInputService 有一个名为 UserInputService.InputBegan 的事件,该事件不仅限于特定的 UI 元素:
这个事件总是会在游戏状态无论如何发生。
还请参阅:
参数
一个 InputObject ,其中包含有用的数据用于查询用户输入,例如 type of input 、 state of input 和 2> Class.InputObj.Position|屏幕坐标2> 。
代码示例
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
此事件触发时,用户改变了通过人类-计算机界面设备(鼠标按钮向下,触摸开始,键盘按钮向下等)的交互方式。
Class.UserInputService 有一个名为 “UserInputService.InputChanged” 的事件,该事件不仅限于特定的 UI 元素:Class.UserInputService.InputChanged 。
这个事件总是会在游戏状态无论如何发生。
还请参阅:
参数
一个 InputObject ,其中包含有用的数据用于查询用户输入,例如 type of input 、 state of input 和 2> Class.InputObj.Position|屏幕坐标2> 。
代码示例
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
输入结束事件触发,当用户停止通过人类-计算机界面设备(鼠标按钮向下,触摸开始,键盘按钮向下等)进行交互时。
Class.UserInputService 有一个名为 “UserInputService.InputEnded” 的事件,该事件不受特定 UI 元素的限制:Class.UserInputService.InputEnded 。
这个事件总是会在游戏状态无论如何发生。
还请参阅:
参数
一个 InputObject ,其中包含有用的数据用于查询用户输入,例如 type of input 、 state of input 和 2> Class.InputObj.Position|屏幕坐标2> 。
代码示例
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
MouseEnter 事件触发,当用户将鼠标移动到 GUI 元素。
请不要基于此事件通过此事件传送的 x 和 y 参数作为一个傻瓜方法来确定用户的鼠标在进入 GUI 时在哪里。这些坐标可能会在同一边缘进入 GUI 时变化,尤其是当鼠标快速进入 GUI 时。这是因为这些坐标表示
当 GUI 元素渲染到另一个元素下时,这个事件也会触发。
如果您想跟踪用户的鼠标离开 GUI 元素,您可以使用 GuiObject.MouseLeave 事件。
还请参阅:
参数
代码示例
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
MouseLeave 事件触发,当用户将鼠标从 GUI 元素移出时。
请不要基于此事件上的 x 和 y 参数来确定用户鼠标在离开 GUI 时在哪里。这些坐标可能会在同一个边缘离开 GUI 时变化 - 特别是当鼠标离开 GUI 时快速。这是因为它们指示鼠标位置,而不是在 GUI 上的正确时间。这是因为
当 GUI 元素渲染到另一个元素下时,这个事件也会触发。
还请参阅:
参数
MouseMoved
在用户移动鼠标时,它会触发。当用户的鼠标位于 GUI 元素内时,它与 Mouse.Move 类似。
注意,该事件触发时,鼠标的位置更新,因此在移动时会再次触发。
x 和 y 参数表示用户鼠标在像素级别的更新屏幕坐标。这些可以有助于确定鼠标在 GUI、屏幕和 delta 上的位置,因为鼠标的前一位置如果在全球变量中跟踪,可能会在屏幕上跟踪。
下面的代码显示了如何确定用户鼠标相对于 GUI 元素的 Vector2 Offset:
local CustomScrollingFrame = script.Parent
local SubFrame = CustomScrollingFrame:FindFirstChild("SubFrame")
local mouse = game.Players.LocalPlayer:GetMouse()
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)
注意,这个事件可能不会发生正确,当用户的鼠标进入或离开 GUI 元素。因此,x 和y 参数可能不会完全匹配到 GUI 边缘的坐标。
还请参阅:
参数
MouseWheelBackward
当用户滚动鼠标轮时,轮回向后事件触发,当鼠标位于GUI 元素上时,它与Mouse.WheelBackward类似,无论用户的鼠标是否位于 GUI 元素上。
此事件仅作为轮子向后运动的指示器发生。这意味着 x 和 y 鼠标坐标参数不会因此事件的发生而改变。这些坐标仅在鼠标移动时更改,这可以通过 GuiObject.MouseMoved 事件跟踪。
还请参阅:
参数
MouseWheelForward
当用户滚动鼠标时,轮子前进事件触发,当鼠标指针位于GUI 元素上时。 它与Mouse.WheelForward类似,无论用户的鼠标是否位于 GUI 元素上。
此事件仅作为轮子前进的指示发生。这意味着 x 和 y 坐标参数不会因此事件的发生而改变。这些坐标仅在鼠标移动时更改,这可以通过 GuiObject.MouseMoved 事件跟踪。
还请参阅:
参数
SelectionGained
此事件发生,当 Gamepad 选择器开始注意到 GuiObject 。
如果您想从游戏手柄上检查,请选择停止将注意力放置在 GUI 元素上,您可以使用 GuiObject.SelectionLost 事件。
当 GUI 获得选择焦点时,SelectedObject 属性的值也会更改为该选择。要确定哪个 GUI 获得选择,请检查此属性的值。
代码示例
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
此事件发生,当 Gamepad 选择器停止关注 GUI 。
如果您想从游戏手柄上检查,请选择开始专注于GUI元素,您可以使用 GuiObject.SelectionGained 事件。
当GUI失去选择焦点时,SelectionObject 属性的值可能会改为为nil或为获得选择焦点的GUI元素。要确定哪个GUI获得选择,或没有选择任何GUI,请检查此属性的值。
代码示例
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
TouchLongPress 事件发生在玩家使用触摸设备按住其手指时,当玩家的手指在 UI 元素上使用触摸设备时,它会发生在一秒后
该事件仅需要一个手指,因此,它可以在 Studio 使用 emulator 和鼠标模拟。
参数
一个 Enum.UserInputState 描述手势状态的状态:
- 开始火焰在手势开始时(稍后)
- 更改玩家在下按时移动手指的火焰
- 当手势结束时,结束一次手势的时候,当手势释放手指时。
代码示例
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
当玩家使用触摸设备移动其指针时,TouchPan事件触发。它与GuiObject.TouchSwipe将在触摸设备启用的时候发生,并不会在GuiObject.TouchTap上发生。 此事件有助于允许玩家操作屏幕上的UI元素的位置。
此事件发生时,表 Vector2 描述参与此操作的手指的相对屏幕位置。 此外,它还会发生多次: Enum.UserInputState.Begin 后稍后延迟, Enum.UserInputState.Change 当玩家移动其手指在gesture中,并最后于 1> enum.UserInput
此事件无法在 Studio 使用模拟器和鼠标模拟器中模拟;您必须有一个具有真实触摸功能的设备才能发射它。
参数
代码示例
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
当玩家使用两个手指在屏幕元素上使用触摸设备时触发 TouchPinch 事件。当两个或多个手指接近时,发生 TouchPinch 。当它们离开时,发生 拉动 。此事件与 Class.GuiObject.
此事件发生时,表 Vector2 描述手势参与者的相对屏幕位置。此外,它还会发生多次: Enum.UserInputState.Begin 后稍后的延迟, Enum.UserInputState.Change 玩家移动手指
该事件需要至少两个手指,因此,使用 Studio 的模拟器和鼠标无法模拟它;您必须有真实的触摸启用设备。
参数
代码示例
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
TouchRotate 事件触发时,玩家使用两个手指在UI元素上使用触摸设备进行抚摸或拖动动作。当角线在两个手指之间变化时,旋转发生。此事件与 GuiObject.TouchPan 一起发生。此事件有助于允许玩家操作屏幕上的旋转。
此事件发生时,表 Vector2 描述参与手势的相对屏幕位置。 此外,它还会发生多次: Enum.UserInputState.Begin 后稍后的延迟, Enum.UserInputState.Change 玩家移动手指期间的屏幕位置,并最后于 1> enuem.userinputstate
该事件需要至少两个手指,因此使用 Studio 模拟器和鼠标无法模拟,您必须有实时触摸启用的设备。
参数
代码示例
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
触摸滑动事件触发,当玩家使用触摸设备在 UI 元素上执行滑动动作时。它与滑动点的方向(向上、向下、向左或向右)和涉及的触摸点数量(多达触摸点)。滑动动作通常用于更改移动设备的选项卡在移动设备上。
该事件只需要一个手指,因此它可以在 Studio 使用模拟器和鼠标来模拟。
参数
向下滑动gesture的方向(向上、向下、向左或向右)。
触摸点数(通常为 1)在gesture中涉及的数量。
代码示例
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
触摸事件触发时,玩家使用触摸启用的设备在 UI 元素上执行了一个触摸手势。触摸是一个快速的单击,不涉及任何移动 (使用触摸启用的设备的话) ,而移动是触摸的标准 (
该事件只需要一个手指,因此它可以在 Studio 使用模拟器和鼠标来模拟。
参数
代码示例
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)