GuiObject 是一个抽象类(与 BasePart 类似)用于 2D 用户界面对象。它定义了所有与显示图形用户界面 (GUI) 对象相关的属性,例如 Size 和 Position 。它还有一些有用的只读属性,例如 AbsolutePosition , AbsoluteSize 和 AbsoluteRotation 。
要以特殊方式操纵图形用户界面对象的布局,您可以使用布局结构,例如 列表/灵活 或 网格,并通过 外观调整器 为它们超出核心属性进行风格化。
虽然使用 InputBegan 和 InputEnded 可以检测任何图形用户界面对象上的鼠标按钮事件,但只有 ImageButton 和 TextButton 有便于检测的专用事件,例如 Activated 检测单击/按下。
概要
属性
决定这个 UI 元素是否沉没输入。
确定 GuiObject 的起始点,相对于其绝对尺寸。
决定是否基于子内容进行缩放。
决定 GuiObject 背景颜色。
决定 GuiObject 背景和边界的透明度。
决定 GuiObject 边框的颜色。
决定边界 GuiObject 是如何相对于其尺寸布置。
决定 GuiObject 边框的像素宽度。
决定是否描渲染父级 GUI 元素边界外的子元素 GuiObjects。
决定玩家的鼠标是否在 GuiObject 上被主动按下。
控制使用 GuiObject 与 UIGridStyleLayout 时的排序顺序。
设置当游戏手柄选择器向下移动时将选择的 GuiObject 。
设置当游戏手柄选择器移至左侧时将选择的 GuiObject 。
设置当游戏手柄选择器移至右侧时将选择的 GuiObject 。
设置当游戏手柄选择器向上移动时将选择的 GuiObject 。
确定 GuiObject 的像素和坐标位置。
决定旋转 GuiObject 的角度数。
确定是否可以由游戏手柄选择 GuiObject 。
覆盖用于游戏手柄的默认选择装饰。
游戏手柄 UI 选择选择的 GuiObjects 顺序。
决定 GuiObject 的像素和积分尺寸。
混合属性 BackgroundTransparency 和 TextTransparency 。
决定是否渲染 GuiObject 和其子孙。
决定 GuiObject 对其他人的相对渲染顺序。
方法
- TweenPosition(endPosition : UDim2,easingDirection : Enum.EasingDirection,easingStyle : Enum.EasingStyle,time : number,override : boolean,callback : function):boolean
平滑地将图形用户界面移至新的 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
平滑地将图形用户界面移至新的尺寸和位置。
活动
当用户开始通过人机界面设备(鼠标按钮向下、触摸开始、键盘按钮向下等)进行交互时,发射。
当用户通过人机界面设备(鼠标按钮向下、触摸开始、键盘按钮向下等)更改他们的互动方式时,发射。
当用户停止通过人机界面设备(鼠标按钮向下、触摸开始、键盘按钮向下等)进行交互时,发射。
当用户将鼠标移至图形用户界面元素时发生火焰。
当用户将鼠标移出 GUI 元素时发生火焰。
在用户移动鼠标时,无论它在哪个 GUI 元素内,都会发生火焰。
当用户滚动鼠标轮返回时,火焰当鼠标悬停在图形用户界面元素上。
当用户滚动鼠标轮时向前移动时,触发当鼠标悬停在图形用户界面元素上时。
在使用游戏手柄选择器时将 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
当玩家使用界面元素上的两个手指执行捏或拉动动作时,发生火焰。
- TouchRotate(touchPositions : Array,rotation : number,velocity : number,state : Enum.UserInputState):RBXScriptSignal
当玩家使用界面元素上的两个手指执行旋转动作时,发生火焰。
当玩家在 UI 元素上执行滑动动作时发生火焰。
当玩家在 UI 元素上执行了点击动作时发生火焰。
- SelectionChanged(amISelected : boolean,previousSelection : GuiObject,newSelection : GuiObject):RBXScriptSignal
当游戏手柄选择移动到、离开或在连接的 或任何子手柄中更改时,发生火焰。
属性
Active
该属性决定 whether GuiObject 是否会将输入发送到 3D 空间,例如基于 ClickDetector 类型的模型 DragDetector .
对于 对象 ( 和 ),此属性决定是否发生火灾 ( 对于那些也仍然有效)。事件 InputBegan , InputChanged , 和 InputEnded 无论值多少都正常工作。
代码示例
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
该属性决定了 GuiObject 的起始点,相对于其绝对尺寸。起始点决定元素的位置(通过 GuiObject.Position )以及从哪里渲染的 GuiObject.Size 扩展。
请参阅这里获得说明图和详情。
代码示例
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 对象,尺寸将调整以适应该内容。
当 设置为与 不同的值时,此 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 , 或 TextLabel , 请确保背景颜色与文本颜色相反。
决定背景视觉属性的另一个属性是 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 背景和边框的透明度。然而,如果图形用户界面是 TextBox 、 TextButton 或 TextLabel ;文本透明度是由 TextBox.TextTransparency 、 TextButton.TextTransparency 和 TextLabel.TextTransparency 决定的, respectively。
如果此属性设置为 1,背景和边框都不会渲染,图形用户界面背景将完全透明。
BorderColor3
决定 GuiObject 长方形边框的颜色 (也称为stroke颜色)。这与对象的 GuiObject.BackgroundColor3 是分开的。如果其 GuiObject.BorderSizePixel 属性设置为 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()
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
该属性决定是否会将 GuiObject 剪切(使其隐形)任何子GUI元素的一部分,如果不会在矩形边界内渲染,将超出矩形边界。
请注意,Rotation 不支持此属性。如果这个或任何祖先图形用户界面具有 非零 ,该属性将被忽略,后裔图形用户界面元素将无论如何渲染,无论这个属性的值是什么。
GuiState
当玩家的手指被点击并保持在 GuiObject 上时,GuiState 的 GuiObject 将设置为 Press .同样,当玩家的手指从 被释放时,玩家的 将设置为 ,当 关闭时,玩家的 将设置为 。
LayoutOrder
此属性控制使用 (例如 或 )时的排序顺序,当 设置为 时。如果对象没有兄弟 UI 布局结构,它没有功能。
GuiObjects 在排序顺序中,较低的值优先于较高的值。具有相同值的对象会回到它们被添加的顺序。
如果你不确定未来是否需要在两个现有元素之间添加元素,那么使用 100 ( 0 , 100 , 200 ,等等) 的倍数是一个好习惯。这可确保你可以使用在其他元素之间订购的元素的布局顺序值的大差距。
还见到 ZIndex ,它决定了对象的 渲染顺序 而不是排序顺序。
NextSelectionDown
该属性设置在用户向下移动游戏手柄选择器时选择的 属性。如果此属性为空,向下移动游戏手柄不会更改选定的图形GUI界面。
将游戏手柄选择器向下移动将使 GuiService.SelectedObject 设置为此对象,除非 GUI 不是 Selectable 。请注意,即使它不是 Selectable ,此属性也可以设置为 GUI 元素,因此您应该确保 GUI 的可选属性值与预期的行为匹配。
还见 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
该属性设置了用户将游戏手柄选择器移到左边时选择的 属性。如果此属性为空,将游戏手柄移至左侧不会更改选定的图形用户界面。
将游戏手柄选择器移到左边将设置 GuiService.SelectedObject 为此对象,除非 GUI 不是 Selectable 。请注意,即使它不是 Selectable ,此属性也可以设置为 GUI 元素,因此您应该确保 GUI 的可选属性值与预期的行为匹配。
还见 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
该属性设置了用户将游戏手柄选择器移到右侧时选择的 属性。如果此属性为空,将游戏手柄移至右侧不会更改选定的图形用户界面。
将游戏手柄选择器移至右侧将设置 GuiService.SelectedObject 为此对象,除非 GUI 不是 Selectable 。请注意,即使它不是 Selectable ,此属性也可以设置为 GUI 元素,因此您应该确保 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
该属性设置用户移动游戏手柄选择器向上时选择的 属性。如果此属性为空,将游戏手柄向上移动不会更改选定的 GUI。
将游戏手柄选择器向上移动将设置 GuiService.SelectedObject 为此对象,除非 GUI 不是 Selectable 。请注意,即使它不是 Selectable ,此属性也可以设置为 GUI 元素,因此您应该确保 GUI 的可选属性值与预期的行为匹配。
还见 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
这个属性使用 确定像素和坐标位置。位置是围绕对象的 。
缩放位置相对于父GUI元素的大小,如果有。
UDim2 值的像素部分无论父GUI的大小都相同这些值代表对象在像素上的位置。对象的实际像素位置可以从 GuiBase2d.AbsolutePosition 属性中阅读。
Rotation
该属性决定了 GuiObject 旋转的度数。旋转与对象的 中心 相对, 不 是AnchorPoint,意味着您无法更改旋转点。此外,该属性不兼容 ClipsDescendants .
Selectable
这个属性决定了使用游戏手柄导航GUI时是否可以选择GuiObject。
如果此属性是 true,可以选择图形用户界面。选择图形用户界面还会将 GuiService.SelectedObject 属性设置为该对象。
当这是 false 时,无法选择 GUI 。然而,将此设置为 false 当用户选择 GUI 时,将不会卸下它或更改 GuiService.SelectedObject 属性的值。
添加 GuiObject.SelectionGained 和 GuiObject.SelectionLost 不会为元素发射。要取消选择 GuiObject,您必须更改 GuiService.SelectedObject 属性。
如果图形用户界面通过属性如此 GuiObject.NextSelectionUp , GuiObject.NextSelectionDown , NextSelectionRight 或 NextSelectionLeft 连接到多个图形用户界面,此属性就有用。而不是更改所有属性以使游戏手柄无法选择图形用户界面,您可以禁用其可选属性以暂时防止其被选择。然后,当您想要游戏手柄选择器能够选择 GUI 时,只需重新启用其可选属性。
代码示例
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 。为了获得最佳效果,您应该通过缩放 SelectionImageObject 值将自定义 UDim2 缩放到选定元素上,以确保对象正确缩放。
更改 SelectionImageObject 对一个 GuiObject 元素仅影响该元素。要影响用户所有的图形用户界面元素,请设置 PlayerGui.SelectionImageObject 属性。
要确定或设置用户选择哪个图形用户界面元素,您可以使用 GuiService.SelectedObject 属性。玩家使用游戏手柄选择不同的图形用户界面元素,触发 NextSelectionUp , NextSelectionDown , NextSelectionLeft 和 NextSelectionRight 事件。
SelectionOrder
低选择顺序的 GuiObject 在开始游戏手柄选择或调用祖先时 GuiService:Select() 时比高选择顺序的 GuiObject 先被选择。该属性不影响方向导航。默认值为 0。
Size
该属性使用 确定计算单元和像素大小。
计数器尺寸与父级 GUI 元素的尺寸相对,如果有。
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
SizeConstraint
该属性设置了 斧头将基于其父元素辈的尺寸对比而生成的斧头,相对于其父辈的尺寸。
此属性有助于创建具有宽度 或 高度的父对象的图形用户界面对象,但不两者都,有效保留对象的比例。
Visible
这个属性是否 GuiObject 和其子孙将被渲染。
的个体组件的渲染可以通过透明属性,例如 、 和 单独控制。
当此属性为 false 时,GuiObject 将被忽略布局结构,例如 UIListLayout , UIGridLayout 和 UITableLayout 。换言之,元素通常在布局中占用的空间被其他元素使用。
代码示例
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 值的人被渲染在拥有更高值的人之下。您可以在 ScreenGui 、 SurfaceGui 或 BillboardGui 中更改渲染顺序,通过更改其 ZIndexBehavior 的值来实现。
如果你不确定未来是否需要在两个现有元素之间添加元素,那么使用 100 ( 0 , 100 , 200 ,等等) 的倍数是一个好习惯。这可确保渲染顺序值的大差距,您可以使用它来为元素层在其他元素之间。
还见到 ,它控制布局结构如 或 与布局结构一起使用时的排序顺序。
方法
TweenPosition
使用指定的 UDim2 和 Enum.EasingDirection 以及 Enum.EasingStyle 平滑地移动图形用户界面到指定时间的新位置。
此函数将返回青少年是否会播游玩。如果另一个青少年正在操作 GuiObject 并覆盖参数为 false,将不会播放。
还见 GuiObject:TweenSize() 和 GuiObject:TweenSizeAndPosition() 。
参数
GUI应移动到哪里。
将图形用户界面简化到 终端位置 的方向。
用于将图形用户界面简化到 终端位置 的风格。
青少年需要多久,以秒为单位,才能完成。
青少年是否会覆盖进行中的青少年。
在青少年完成时执行的回调函数。
返回
青少年是否会播游玩。
代码示例
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
使用指定的 GuiObject 和 Enum.EasingStyle 在指定时间将 UDim2 调整为新的 Enum.EasingDirection 。
此函数将返回青少年是否会播游玩。通常这将始终返回 true , 但如果另一个青少年激活并将覆盖设置为 false , 它将返回 false .
还见 GuiObject:TweenSize() 和 GuiObject:TweenSizeAndPosition() 。
参数
图形用户界面应调整的尺寸。
将图形用户界面简化到 endSize 的方向。
用于将图形用户界面简化到 endSize 的风格。
青少年需要多久,以秒为单位,才能完成。
青少年是否会覆盖进行中的青少年。
在青少年完成时执行的回调函数。
返回
青少年是否会播游玩。
代码示例
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
使用指定的 和 以及 在指定时间内平滑地移动图形用户界面到新的 大小和位置。
此函数将返回青少年是否会播游玩。通常这将始终返回 true , 但如果另一个青少年激活并将覆盖设置为 false , 它将返回 false .
还见 GuiObject:TweenSize() 和 GuiObject:TweenSizeAndPosition() 。
参数
图形用户界面应调整的尺寸。
GUI应移动到哪里。
将图形用户界面简化到 endSize 和 endPosition 的方向。
用于将图形用户界面简化到 endSize 和 endPosition 的风格。
青少年需要多久,以秒为单位,才能完成。
青少年是否会覆盖进行中的青少年。
在青少年完成时执行的回调函数。
返回
青少年是否会播游玩。
代码示例
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 通过人机界面设备(鼠标按钮向下、触摸开始、键盘按钮向下等)互动时,此事件会发生。
UserInputService 有一个类似名称的事件,不受到特定 UI 元素的限制:UserInputService.InputBegan。
该事件将无论游戏状态如何总是发射。
还见 GuiObject.InputEnded 和 GuiObject.InputChanged 。
参数
一个 InputObject , 包含用于查询用户输入的有用数据,例如 type of input , state of input 和 screen coordinates of the input .
代码示例
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
当用户通过人机界面设备(鼠标按钮向下、触摸开始、键盘按钮向下等)更改互动方式时,该事件会发生。
UserInputService 有一个类似名称的事件,不受到特定 UI 元素的限制:UserInputService.InputChanged。
该事件将无论游戏状态如何总是发射。
还见 GuiObject.InputBegan 和 GuiObject.InputEnded 。
参数
一个 InputObject , 包含用于查询用户输入的有用数据,例如 type of input , state of input 和 screen coordinates of the input .
代码示例
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
输入已结束事件会在用户停止通过人机界面设备(鼠标按钮向下、触摸开始、键盘按钮向下等)进行交互时触发。
UserInputService 有一个类似名称的事件,不受到特定 UI 元素的限制:UserInputService.InputEnded。
该事件将无论游戏状态如何总是发射。
还见 GuiObject.InputBegan 和 GuiObject.InputChanged 。
参数
一个 InputObject , 包含用于查询用户输入的有用数据,例如 Enum.UserInputType , Enum.UserInputState 和 InputObject.Position .
代码示例
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
当用户将鼠标移到 GuiObject 元素时,鼠标进入事件发生。
请不要依赖这个事件传递的 x 和 y 参数作为确定用户鼠标位置的有效方法。当鼠标通过同一边界进入图形用户界面时,这些坐标可能会变化,尤其是当鼠标快速进入元素时。这是因为坐标指示事件发生时鼠标的位置,而不是鼠标进入 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
当用户将鼠标移出 GuiObject 元素时,鼠标离开事件发生。
请不要依赖这个事件传递的 x 和 y 参数作为确定用户鼠标在离开 GUI 时位置的笃定方法。即使在鼠标通过同一边界离开 GUI 时,这些坐标可能会变化 - 尤其是当鼠标快速离开元素时。这是因为坐标表示的是鼠标在事件触发时的位置,而不是鼠标离开 GUI 的准确时刻。
此事件即使在其 GUI 元素渲染在另一个元素下时也会触发。
还看到也看到
参数
MouseMoved
在 GuiObject 元素内时,用户移动鼠标时发生火焰。与 Mouse.Move 类似,无论用户的鼠标是否在图形用户界面元素上,都会发射。
注意,此事件在鼠标位置更新时发生,因此在移动时会反复发生。
x 和 y 参数表示用户鼠标的更新屏幕坐标以像素表示。这些可以用于确定鼠标在图形用户界面、屏幕和 delta 上的位置,因为如果鼠标在全球变量中被跟踪,它的前一个位置。
下面的代码展示了如何确定用户鼠标对图形用户界面元素的偏移:Vector2
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)
请注意,该事件可能不会在用户的鼠标进入或离开图形用户界面元素时发生。因此,x 和 y 参数可能不完全匹配 GUI 边缘的坐标。
还看到也看到
参数
MouseWheelBackward
当用户滚动鼠标轮时,当鼠标悬停在 GuiObject 元素上时,轮回向后事件发生。与 Mouse.WheelBackward 类似,无论用户的鼠标是否在图形用户界面元素上,都会发射。
这个事件仅作为轮子向后移动的指标发射。这意味着 x 和 y 鼠标坐标参数在这个事件的结果下不会发生变化。这些坐标只在鼠标移动时更改,可以通过 GuiObject.MouseMoved 事件进行跟踪。
还看到也看到
参数
MouseWheelForward
当用户滚动鼠标轮时,当鼠标悬停在 GuiObject 元素上时,轮向前事件发生,当用户滚动鼠标轮时。与 Mouse.WheelForward 类似,无论用户的鼠标是否在图形用户界面元素上,都会发射。
这个事件仅仅作为轮子前进的指标发射。这意味着 X 和 Y 鼠标坐标参数在此事件的影响下不会发生变化。这些坐标只在鼠标移动时更改,可以通过 GuiObject.MouseMoved 事件进行跟踪。
还看到也看到
参数
SelectionGained
当游戏手柄选择器开始关注 GuiObject 时,此事件发生。
如果您想从游戏手柄检查停止关注 GUI 元素,您可以使用 GuiObject.SelectionLost 事件。
当 GUI 获得选择焦点时,SelectedObject 属性的值也会更改为获得选择的那个值。要确定哪个图形用户界面获得选择,检查此属性的值。
代码示例
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
当游戏手柄选择器停止关注 GuiObject 时,此事件发生
如果您想从游戏手柄检查开始关注图形用户界面元素,您可以使用 GuiObject.SelectionGained 事件。
当图形用户界面失去选择焦点时,SelectionObject 属性的值将改变为nil 或获得选择焦点的图形用户界面元素。要确定哪个图形用户界面获得选择,或者如果没有选择任何图形用户界面,检查此属性的值。
代码示例
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
此事件在玩家使用触摸启用的设备将手指放在 UI 元素上时短暂等待后发生。它发射一个包含 Vector2 描述手指相对屏幕位置的表。此外,它发射多次:Enum.UserInputState.Begin后短暂延迟,Enum.UserInputState.Change如果玩家在动作期间移动手指,最后Enum.UserInputState.End。延迟是平台依赖的;在 Studio 中它比一秒钟长一点。
由于此事件只需要一根手指,因此可以使用 Studio 的模拟器和鼠标来模拟此事件。
参数
描述手指参与手势的相对位置的 阵列。
描述手势状态的 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
当玩家使用触摸启用的设备移动手指到 UI 元素时,此事件发生。它在 GuiObject.TouchSwipe 之前短暂发射,并不会与 GuiObject.TouchTap 发射。此事件有助于允许玩家在屏幕上操纵 UI 元素的位置。
这个事件发射与包含描述手指相对屏幕位置的 Vector2 表的表。此外,它发射多次:Enum.UserInputState.Begin在短暂的延迟后,Enum.UserInputState.Change当玩家移动手指时,最后使用 Enum.UserInputState.End。
这个事件无法在 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
当玩家使用两个手指对 UI 元素进行捏或拉动动作时,触发此事件,使用触摸启用的设备。当两个或更多的手指靠近时,出现一次 捏 ;当它们分开时,出现一次 拉 。此事件与 GuiObject.TouchPan 同时发生。此事件有助于允许玩家在屏幕上操纵 UI 元素的尺寸(规模),最常用于缩放功能。
这个事件发射与包含描述手指相对屏幕位置的 Vector2 表的表。此外,它发射多次:Enum.UserInputState.Begin在短暂的延迟后,Enum.UserInputState.Change当玩家在动作期间移动手指时,最后使用 Enum.UserInputState.End。应注意的是,缩放应用为 倍数 。
由于此事件需要至少两个手指,因此无法使用 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
当玩家使用两个手指对 UI 元素进行捏或拉动动作时,触发此事件,使用触摸启用的设备。旋转发生在当两个手指之间的线的角度发生变化时。此事件与 GuiObject.TouchPan 同时发生。这个事件有助于允许玩家在屏幕上操纵 UI 元素的旋转。
这个事件发射与包含描述手指相对屏幕位置的 Vector2 表的表。此外,它发射多次:Enum.UserInputState.Begin在短暂的延迟后,Enum.UserInputState.Change当玩家在动作期间移动手指时,最后使用 Enum.UserInputState.End。
由于此事件需要至少两个手指,因此无法使用 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 元素上发射,当玩家执行滑动动作时。它以手势的方向(向上、向下、向左或向右)和涉及手势的触摸点数发射。滑动手势经常用于在移动用户界面中更改选项卡。
由于此事件只需要一根手指,因此可以在工作室使用模拟器和鼠标进行模拟。
参数
一个 Enum.SwipeDirection 指示滑动手势的方向(向上、向下、向左或向右)。
触摸点数量涉及到的手势(通常为 1)。
代码示例
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 元素上使用触摸启用设备执行点击动作。点击是一种快速的单次触摸,不涉及任何移动(长按将触发GuiObject.TouchLongPress,移动期间触发GuiObject.TouchPan和/或GuiObject.TouchSwipe)。它发射带有描述涉及手势的相对位置的表Vector2对象的表。
由于此事件只需要一根手指,因此可以在工作室使用模拟器和鼠标进行模拟。
参数
描述手指参与手势的相对位置的 阵列。
代码示例
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)