Mouse

Mostrar obsoleto

*Este conteúdo é traduzido por IA (Beta) e pode conter erros. Para ver a página em inglês, clique aqui.

Não criável

Ratón ha sido superado por UserInputService y ContextActionService, que cubren un alcance más amplio, son más ricos en características y soportan mejor los patrones de 0>plataforma cruzada0>. Se mantiene soportado debido a su amplio uso, pero deberías considerar fuertemente usar estas alternativas.

El objeto Ratón alberga varias API para apuntadores, principalmente para botones y intersección rayo-superficie, emisión de rayos. Se puede acceder a través de Player:GetMouse() llamado en el Players.LocalPlayer en un 1> Class.LocalScript1> . También se pasa por el evento 4> Class.Tool.Equipped4> .

  • Es más notorio por la propiedad Icon , que cambia la aspecto, lookdel cursor.
  • Raycastiza continuamente la posición del mouse de la pantalla en el mundo 3D usando la propiedad TargetFilter, que almacena los resultados del raycast en el Hit, Class.Mouse.Target|Target</
  • Plugins puede usar Plugin:GetMouse() para obtener un PluginMouse , que se comporta de manera similar.

-- De un LocalScript:
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
-- Configurando el íconode mouse
mouse.Icon = "rbxasset://SystemCursors/Wait"

Nota:

  • Este objeto no controla/restringe el movimiento del puntero. Para esto, see UserInputService.MouseBehavior y UserInputService.MouseDeltaSensitivity .

  • Si dos funciones están conectadas a un mismo evento de entrada, como Button1Down, ambas funciones se ejecutarán cuando se activa el evento. No hay concepto de hundimiento/paso de entrada, ya que los eventos no soportan este comportamiento. Sin embargo, ContextActionService tiene este comportamiento a través de

  • Si bien no puede haber un mouse disponible en todas las plataformas, Mouse seguirá funcionando en móvil (toque) y consola (controlador para juego), que no tienen normalmente mouse o hardware de puntero. Para comportamientos explícitos de plataforma cruzada, use UserInputService y ContextActionService .

    Vea Entrada y cámara para obtener más información sobre la personalización de las entradas en su experiencia.

Resumo

Propriedades

  • Somente leitura
    Não replicado
    Ler Parallel

    El CFrame de la posición del ratónen el espacio 3D.

  • Icon:ContentId
    Ler Parallel

    El ID de contenido de la imagen usada como el íconode Mouse

  • Somente leitura
    Não replicado
    Ler Parallel

    Un CFrame colocado en el Workspace.CurrentCamera y orientado hacia la posición 3D del ratón.

  • Somente leitura
    Não replicado
    Ler Parallel

    El objeto en el espacio 3D al que apunta el mouse está apuntando a.

  • Determina un objeto (y sus descendientes) para ser ignorado al determinar Mouse.Hit y Mouse.Target .

  • Somente leitura
    Não replicado
    Ler Parallel

    Indica el Enum.NormalId de la superficie en la que se encuentra el mouse.

  • Somente leitura
    Não replicado
    Ler Parallel

    Un Ray dirigido hacia la posición mundial del ratón, que se origina desde la posición mundial del Workspace.CurrentCamera .

  • Somente leitura
    Não replicado
    Ler Parallel

    Describe el ancho de la ventana del juego en píxeles.

  • Somente leitura
    Não replicado
    Ler Parallel

    Describe la altura de la ventana del juego en píxeles.

  • Somente leitura
    Não replicado
    Ler Parallel

    Describe la X ( horizontal ) componente de la posición del ratónen la pantalla.

  • Somente leitura
    Não replicado
    Ler Parallel

    Describe el componente de Y (vertical) de la posición de la pantalla del ratón.

Eventos

Propriedades

Somente leitura
Não replicado
Ler Parallel

Esta propiedad indica CFrame de la posición del ratónen el espacio 3D. Nota que Mouse.TargetFilter y sus descendientes serán ignorados.

Los desarrolladores pueden obtener la posición de Hit como sigue:


local position = mouse.Hit.Position

El golpe a menudo se usa por Tools para disparar un arma hacia el mouse en tercera persona.

Los desarrolladores que buscan el BasePart el mouse está apuntando a deber usar Mouse.Target .

¿Cómo se calcula Mouse.Hit?

La posición de la cámara de golpe se calcula como el punto de intersección entre el ratón's internal Ray (una extensión de Mouse.UnitRay ) y un objeto en el espacio 3D (como una parte).

La orientación de la Hit CFrame coincide con la dirección de la Mouse.UnitRay .


local unitRayDirection = mouse.UnitRay.Direction
local mouseHitDirection = mouse.Hit.lookVector
-- unitRayDirection ≈ mouseHitDirection
-- the vectors are approximately equal

Nota, el giro de la Workspace.CurrentCamera no se usa al calcular la orientación del Hit CFrame .

El rayo interno del ratónse extiende por 1,000 studs. Si el mouse no apunta a un objeto en el espacio 3D (por ejemplo, al apuntar al cielo), esta propiedad estará 1,000 studs lejos de la Workspace.CurrentCamera .

Amostras de código

The code in this sample, when placed inside a LocalScript within StarterPlayerScripts will draw a red laser beam between the character's head and Mouse.Hit at all times.

Note, this beam will pass directly through obstructions in third person as the Mouse's raycasting is done from the Workspace.CurrentCamera not the head.

Mouse.Hit Laser Beam

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local beam = Instance.new("Beam")
beam.Segments = 1
beam.Width0 = 0.2
beam.Width1 = 0.2
beam.Color = ColorSequence.new(Color3.new(1, 0, 0))
beam.FaceCamera = true
local attachment0 = Instance.new("Attachment")
local attachment1 = Instance.new("Attachment")
beam.Attachment0 = attachment0
beam.Attachment1 = attachment1
beam.Parent = workspace.Terrain
attachment0.Parent = workspace.Terrain
attachment1.Parent = workspace.Terrain
local function onRenderStep()
local character = player.Character
if not character then
beam.Enabled = false
return
end
local head = character:FindFirstChild("Head")
if not head then
beam.Enabled = false
return
end
beam.Enabled = true
local origin = head.Position
local finish = mouse.Hit.Position
attachment0.Position = origin
attachment1.Position = finish
end
RunService.RenderStepped:Connect(onRenderStep)

The code below visualizes the difference between Mouse.Hit and Mouse.Origin. In order to do this, the code uses the Vector3 positions of the hit and origin CFrame values using .p.

The difference is that the origin is "where the mouse came from" (its origin) and the hit is the position where the mouse hits (is when the player presses their mouse).

This example also visualizes that the mouse origin is very similar to the position of the CurrentCamera by printing the magnitude (distance) between the two positions.

Mouse Origin vs Mouse Hit vs CurrentCamera Position

local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local player = Players.LocalPlayer
local camera = Workspace.CurrentCamera
local mouse = player:GetMouse()
local camPos = camera.CFrame.Position
local function onButton1Down()
print("Mouse.Hit:", mouse.Hit.Position)
print("camPos:", camPos)
print("Mouse.Origin:", mouse.Origin.Position)
print("Magnitude:", (mouse.Origin.Position - camPos).Magnitude)
end
mouse.Button1Down:Connect(onButton1Down)

Icon

ContentId
Ler Parallel

Icono es una propiedad que determina la imagen utilizada como puntero. Si no hay espacio, se usa una flecha predeterminada. Mientras el cursor se posiciona sobre un GuiButton , esta propiedad se ignora temporalmente.

Para ocultar el cursor por completo, no use una imagen transparente – en cambio, establezca Class.UserInputService.MouseIconEnabled a falso.

Para obtener/ajustar el icono de usuario en las experiencias, deberías usar UserInputService.MouseIcon . Mouse.Icon se desactivará después de que se lance la nueva API para que los plugin establezcan el cursor del mouse.

Diseñando un Cursor

Las siguientes pautas pueden ser útiles al crear sus propios cursores de mouse:

  • Las dimensiones de la imagen utilizada determinan el tamaño del cursor.
  • El centro de la imagen es donde se emiten los ingresos del mouse.
  • La imagen de mouse predeterminada es 64x64 píxeles, con el mouse ocupando 17x24 píxeles de espacio.

System Cursors for PluginMouse

Cuando se usa un PluginMouse recuperado desde Plugin:GetMouse(),


<tbody>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-Pointer.png">
</img>
</td>
<td><code>rbxasset://Sistema de cursores/ Flecha</code></td>
<td>Clic y selección predeterminados.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-PointingHand.png">
</img>
</td>
<td><code>rbxasset://Sistema de cursores/PointingHand</code></td>
<td>Pasar el cursor sobre un enlace/botón activo.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-OpenHand.png">
</img>
</td>
<td><code>rbxasset://Sistema de cursores/OpenHand</code></td>
<td>Pasar el cursor sobre un objetoarrastrable.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-GrabbingHand.png">
</img>
</td>
<td><code>rbxasset://Sistema de cursores/Mano cerrada</code></td>
<td>Arrastrar un objeto.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-IBeam.png">
</img>
</td>
<td><code>rbxasset://Sistema de cursores/IBeam</code></td>
<td>Pasar el cursor en un campo de texto.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-ResizeNS.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/SizeNS</code></td>
<td>Pasar el cursor por encima de un controladorde resize vertical.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-ResizeEW.png">
</img>
</td>
<td><code>rbxasset://Sistema de cursores/TamañoEW</code></td>
<td>Pase el cursor por encima de un controladorde escalado horizontal.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-ResizeNESW.png">
</img>
</td>
<td><code>rbxasset://Sistema de cursores/Tamaño NESW</code></td>
<td>Pase el controladorpor encima de un mango de resize de esquina.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-ResizeNWSE.png">
</img>
</td>
<td><code>rbxasset://Sistema de cursores/Tamaño NWSE</code></td>
<td>Pase el controladorpor encima de un mango de resize de esquina.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-ResizeAll.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/SizeAll</code></td>
<td>Pasar el cursor por encima de un multi-dirección resize controlador.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-ResizeSplitV.png">
</img>
</td>
<td><code>rbxasset://Sistema de cursores/SplitNS</code></td>
<td>Pasar el cursor por encima de un controlador"divisorio" vertical.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-ResizeSplitH.png">
</img>
</td>
<td><code>rbxasset://Sistema de cursores/SplitEW</code></td>
<td>Pasar el cursor por encima de un controladorhorizontal "diviso".</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-Forbidden.png">
</img>
</td>
<td><code>rbxasset://Sistema de cursores/Prohibido</code></td>
<td>Pasar el cursor sobre un objetobloqueado/prohibido.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-Wait.png">
</img>
</td>
<td><code>rbxasset://Sistema de cursores/Espera</code></td>
<td>Indicar que una acción está en progreso.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-Busy.png">
</img>
</td>
<td><code>rbxasset://Sistema de cursores/Busy</code></td>
<td>Indicando que el sistema está ocupado.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-Crosshair.png">
</img>
</td>
<td><code>rbxasset://Sistema de cursores/Cross</code></td>
<td>Pasar el cursor por encima de un área de selección de pines.</td>
</tr>
</tbody>
Mira\*ActivoUso recomendado

Estas apariencias son aproximaciones; el aspecto real depende de su sistema operativo.

Amostras de código

This example changes the Players.LocalPlayer mouse icon to look like a dragon image.

Dragon Mouse Icon

local Players = game:GetService("Players")
local mouse = Players.LocalPlayer:GetMouse()
mouse.Icon = "http://www.roblox.com/asset?id=163023520"

Origin

Somente leitura
Não replicado
Ler Parallel

La propiedad de origen Mouse es una CFrame que indica de dónde se originó el mouse. Está posicionado en el Workspace.CurrentCamera y se orienta hacia la posición 3D del ratón.

Mouse.UnitRay comienza en la misma posición que el origen, y se extiende por un stud en la misma dirección.


local unitRay = mouse.UnitRay
local origin = mouse.Origin
-- unitRay.Direction = p.o
-- unitRay.Direction ≈ origin.lookVector

Para la posición del Mouse en el espacio 3D, see Mouse.Hit .

Amostras de código

The code below visualizes the difference between Mouse.Hit and Mouse.Origin. In order to do this, the code uses the Vector3 positions of the hit and origin CFrame values using .p.

The difference is that the origin is "where the mouse came from" (its origin) and the hit is the position where the mouse hits (is when the player presses their mouse).

This example also visualizes that the mouse origin is very similar to the position of the CurrentCamera by printing the magnitude (distance) between the two positions.

Mouse Origin vs Mouse Hit vs CurrentCamera Position

local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local player = Players.LocalPlayer
local camera = Workspace.CurrentCamera
local mouse = player:GetMouse()
local camPos = camera.CFrame.Position
local function onButton1Down()
print("Mouse.Hit:", mouse.Hit.Position)
print("camPos:", camPos)
print("Mouse.Origin:", mouse.Origin.Position)
print("Magnitude:", (mouse.Origin.Position - camPos).Magnitude)
end
mouse.Button1Down:Connect(onButton1Down)

Target

Somente leitura
Não replicado
Ler Parallel

El objeto en el espacio 3D al que apunta el mouse está apuntando a.

Nota:

  • Si Mouse.TargetFilter se ha establecer, el filtro de objetivo y sus descendientes se ignorarán.
  • Cuando el mouse no esté apuntando a un BasePart, por ejemplo cuando esté apuntando al cielo, Target será nulo.
  • Los desarrolladores que buscan la posición del mouse en el espacio 3D deberían usar Mouse.Hit .

Amostras de código

The following code sample, when placed in StarterPlayerScripts will create a tool in the player's backpack that, once equipped, will change the BasePart.BrickColor of every BasePart the player clicks on.

Color Randomizer Tool

local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
local backpack = localPlayer:WaitForChild("Backpack")
local tool = Instance.new("Tool")
tool.RequiresHandle = false
tool.CanBeDropped = false
tool.Parent = backpack
tool.Equipped:Connect(function(mouse)
mouse.Button1Down:Connect(function()
if mouse.Target and mouse.Target.Parent then
mouse.Target.BrickColor = BrickColor.random()
end
end)
end)

TargetFilter

Ler Parallel

Esta propiedad determina un objeto para ser ignorado por el mouse cuando se calcula Mouse.Hit y Mouse.Target . Los descendientes del objeto también se ignoran, por lo que es posible ignorar múltiples objetos siempre que sean descendientes del objeto a cui esta propiedad está establecer. Esta propiedad es

Esta propiedad se puede establecer a cualquier Instance o nulo, por ejemplo:


local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
mouse.TargetFilter = workspace.Model

Nota que el Character del Players.LocalPlayer es ignorado por el mouse automáticamente.

TargetSurface

Somente leitura
Não replicado
Ler Parallel

Esta propiedad indica el Enum.NormalId de la superficie de BasePart a la que apunta el mouse. Esta propiedad se deriva de la posición mundial del mouse ( Mouse.Hit ) y la parte hacia la que apunta el mouse ( 2>Class.Mouse.Target2> ).

Esta propiedad no tiene sentido cuando el mouse no apunta a una parte, por ejemplo cuando el mouse apunta al cielo. En este momento, esta propiedad está configurada como "Derecha" bajo estas condiciones. Antes de usar esta propiedad, asegúrese de que el objetivo del ratónno es nulo.


local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
-- Asegúrese de que hay una parte en la que el mouse está apuntando
if mouse.Target then
print("The mouse is pointing to the " .. mouse.TargetSurface.Name .. " side of " .. mouse.Target.Name)
else
print("The mouse is not pointing at anything.")
end

Amostras de código

The code in this sample, when placed in a LocalScript inside StarterPlayerScripts will set the surface of any BasePart clicked on to a random surface.

Surface Randomizer

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local surfaceTypes = {
Enum.SurfaceType.Smooth,
Enum.SurfaceType.Glue,
Enum.SurfaceType.Weld,
Enum.SurfaceType.Studs,
Enum.SurfaceType.Inlet,
Enum.SurfaceType.Universal,
Enum.SurfaceType.Hinge,
Enum.SurfaceType.Motor,
}
local function onMouseClick()
-- make sure the mouse is pointing at a part
local target = mouse.Target
if not target then
return
end
local surfaceType = surfaceTypes[math.random(1, #surfaceTypes)]
local surface = mouse.TargetSurface
local propertyName = surface.Name .. "Surface"
mouse.Target[propertyName] = surfaceType
end
mouse.Button1Down:Connect(onMouseClick)

UnitRay

Somente leitura
Não replicado
Ler Parallel

La propiedad UnitRay es una Ray dirigida hacia la posición del ratónen el espacio 3D (descripción de Mouse.Hit). Procede del CFrame del 2>Class.Workspace.CurrentCamera2> . Como todos los rayos de unidad, tiene una distancia de 1.


local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
print(mouse.UnitRay.Direction.magnitude) -- Always 1

ViewSizeX

Somente leitura
Não replicado
Ler Parallel

La propiedad ViewSizeX describe el componente horizontal del tamaño de la ventana del juego en píxeles.

Amostras de código

This code sample shows how you can create a Vector2 representing the Mouse object's position on screen (X() and Y()) and the size of the screen itself (ViewSizeX() and ViewSizeY()). Using these, you can normalize the position of the mouse on-screen such that the top-left just under the topbar maps to (0, 0) and the bottom-right maps to (1, 1). This normalized position is calculated and printed as the mouse moves using the Move() event.

Normalized Mouse Position

local Players = game:GetService("Players")
-- Note: You should use ContextActionService or UserInputService instead of
-- the Mouse object for accomplishing this task.
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local function onMouseMove()
-- Construct Vector2 objects for the mouse's position and screen size
local position = Vector2.new(mouse.X, mouse.Y)
local size = Vector2.new(mouse.ViewSizeX, mouse.ViewSizeY)
-- A normalized position will map the top left (just under the topbar)
-- to (0, 0) the bottom right to (1, 1), and the center to (0.5, 0.5).
-- This is calculated by dividing the position by the total size.
local normalizedPosition = position / size
print(normalizedPosition)
end
mouse.Move:Connect(onMouseMove)

ViewSizeY

Somente leitura
Não replicado
Ler Parallel

La propiedad ViewSizeY describe el componente vertical del tamaño de la ventana del juego en píxeles. Esta longitud incluye el espacio usado por la barra superior.

Amostras de código

This code sample shows how you can create a Vector2 representing the Mouse object's position on screen (X() and Y()) and the size of the screen itself (ViewSizeX() and ViewSizeY()). Using these, you can normalize the position of the mouse on-screen such that the top-left just under the topbar maps to (0, 0) and the bottom-right maps to (1, 1). This normalized position is calculated and printed as the mouse moves using the Move() event.

Normalized Mouse Position

local Players = game:GetService("Players")
-- Note: You should use ContextActionService or UserInputService instead of
-- the Mouse object for accomplishing this task.
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local function onMouseMove()
-- Construct Vector2 objects for the mouse's position and screen size
local position = Vector2.new(mouse.X, mouse.Y)
local size = Vector2.new(mouse.ViewSizeX, mouse.ViewSizeY)
-- A normalized position will map the top left (just under the topbar)
-- to (0, 0) the bottom right to (1, 1), and the center to (0.5, 0.5).
-- This is calculated by dividing the position by the total size.
local normalizedPosition = position / size
print(normalizedPosition)
end
mouse.Move:Connect(onMouseMove)
Somente leitura
Não replicado
Ler Parallel

Cuando se detectan cambios en la posición de la ratónen la pantalla, se recomienda que uses ContextActionService:BindAction() con Enum.UserInputType.MouseMovement o Class.UserInputService.InputChanged</

La propiedad X describe el componente horizontal de la posición del ratónen la pantalla. La posición se mide en píxeles relativo a la esquina superior izquierda, debajo de la barra superior. Esta propiedad se puede utilizar en conjunción con Mouse.Y para producir un Vector2 representando la posición del ratón:


local position = Vector2.new(mouse.X, mouse.Y)

Esta propiedad no dispara Changed o el señal que se devuelve de GetPropertyChangedSignal . Usa el evento Mouse.Move en su lugar.

Amostras de código

This code sample shows how you can create a Vector2 representing the Mouse object's position on screen (X() and Y()) and the size of the screen itself (ViewSizeX() and ViewSizeY()). Using these, you can normalize the position of the mouse on-screen such that the top-left just under the topbar maps to (0, 0) and the bottom-right maps to (1, 1). This normalized position is calculated and printed as the mouse moves using the Move() event.

Normalized Mouse Position

local Players = game:GetService("Players")
-- Note: You should use ContextActionService or UserInputService instead of
-- the Mouse object for accomplishing this task.
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local function onMouseMove()
-- Construct Vector2 objects for the mouse's position and screen size
local position = Vector2.new(mouse.X, mouse.Y)
local size = Vector2.new(mouse.ViewSizeX, mouse.ViewSizeY)
-- A normalized position will map the top left (just under the topbar)
-- to (0, 0) the bottom right to (1, 1), and the center to (0.5, 0.5).
-- This is calculated by dividing the position by the total size.
local normalizedPosition = position / size
print(normalizedPosition)
end
mouse.Move:Connect(onMouseMove)
Somente leitura
Não replicado
Ler Parallel

Cuando se detectan cambios en la posición de la ratónen la pantalla, se recomienda que uses ContextActionService:BindAction() con Enum.UserInputType.MouseMovement o Class.UserInputService.InputChanged</

La propiedad Y describe el componente vertical de la posición del ratónen la pantalla. La posición se mide en píxeles relativa al esquina superior izquierda, debajo de la barra superior. Esta propiedad se puede utilizar en conjunción con Mouse.X para producir un Vector2 representando la posición del ratón:


local position = Vector2.new(mouse.X, mouse.Y)

Esta propiedad no dispara Changed o el señal que se devuelve de GetPropertyChangedSignal . Usa el evento Mouse.Move en su lugar.

Amostras de código

This code sample shows how you can create a Vector2 representing the Mouse object's position on screen (X() and Y()) and the size of the screen itself (ViewSizeX() and ViewSizeY()). Using these, you can normalize the position of the mouse on-screen such that the top-left just under the topbar maps to (0, 0) and the bottom-right maps to (1, 1). This normalized position is calculated and printed as the mouse moves using the Move() event.

Normalized Mouse Position

local Players = game:GetService("Players")
-- Note: You should use ContextActionService or UserInputService instead of
-- the Mouse object for accomplishing this task.
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local function onMouseMove()
-- Construct Vector2 objects for the mouse's position and screen size
local position = Vector2.new(mouse.X, mouse.Y)
local size = Vector2.new(mouse.ViewSizeX, mouse.ViewSizeY)
-- A normalized position will map the top left (just under the topbar)
-- to (0, 0) the bottom right to (1, 1), and the center to (0.5, 0.5).
-- This is calculated by dividing the position by the total size.
local normalizedPosition = position / size
print(normalizedPosition)
end
mouse.Move:Connect(onMouseMove)

Métodos

Eventos

Button1Down

El Botón1Down incluso se activa cuando el jugador presiona su botón izquierdo del ratón.

Esto también se puede acceder desde un Tool. Por ejemplo, cuando se coloca en un LocalScript, el código de abajo imprime Button1Down cada vez que se presiona el botón izquierdo del ratón:


local Tool = script.Parent --asegúrese de que se trate de un objeto de herramienta
Tool.Equipped:Connect(function(Mouse)
Mouse.Button1Down:Connect(function()
print("Button1Down")
end)
end)

Los desarrolladores pueden encontrar la posición del mouse en el espacio del mundo, y si está apuntando a cualquier BasePart , utilizando las propiedades de Mouse.Hit y Mouse.Target.

Para obtener información sobre cómo obtener el objeto del mouse, consulte la página Mouse.

Nota, se recomienda a los desarrolladores usar UserInputService en lugar del objeto Mouse en el nuevo trabajo.


Amostras de código

The following code sample, when placed in StarterPlayerScripts will create a tool in the player's backpack that, once equipped, will change the BasePart.BrickColor of every BasePart the player clicks on.

Color Randomizer Tool

local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
local backpack = localPlayer:WaitForChild("Backpack")
local tool = Instance.new("Tool")
tool.RequiresHandle = false
tool.CanBeDropped = false
tool.Parent = backpack
tool.Equipped:Connect(function(mouse)
mouse.Button1Down:Connect(function()
if mouse.Target and mouse.Target.Parent then
mouse.Target.BrickColor = BrickColor.random()
end
end)
end)

Button1Up

Dispara cuando el botón izquierdo del ratón se libera.

Para obtener la información sobre cómo obtener el objeto Mouse, consulte la página Mouse.

Los desarrolladores pueden encontrar la posición del mouse en el espacio del mundo, y si está apuntando a cualquier BasePart usando las propiedades Mouse.Hit y Mouse.Target.

Nota, se recomienda a los desarrolladores usar UserInputService en lugar del objeto Mouse en el nuevo trabajo.


Amostras de código

The follow example changes the BasePart.BrickColor of every BasePart the player clicks and releases their mouse on.

In order for a part to change color, the player's mouse must be over the part both when the player presses their left mouse button down and when the player releases their left mouse button.

Color Randomizer Tool (Button1Up)

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local target = nil
local function button1Down()
target = mouse.Target
end
local function button1Up()
if target == mouse.Target then
target.BrickColor = BrickColor.random()
end
end
mouse.Button1Down:Connect(button1Down)
mouse.Button1Up:Connect(button1Up)

Button2Down

El Botón2Down incluso se activa cuando el jugador presiona su botón derecho del ratón.

Esto también se puede acceder a partir de un Tool. Por ejemplo, cuando se coloca en un LocalScript, el código de abajo imprime Button2Down cada vez que se presiona el botón derecho del ratón:


local Tool = script.Parent --asegúrese de que se trate de un objeto de herramienta
Tool.Equipped:Connect(function(Mouse)
Mouse.Button2Down:Connect(function()
print("Button2Down")
end)
end).

Los desarrolladores pueden encontrar la posición del mouse en el espacio del mundo, y si está apuntando a cualquier BasePart , utilizando las propiedades de Mouse.Hit y Mouse.Target.

Para obtener información sobre cómo obtener el objeto del mouse, consulte la página Mouse.

Nota, se recomienda a los desarrolladores usar UserInputService en lugar del objeto Mouse en el nuevo trabajo.


Amostras de código

The following code sample, when placed in StarterPlayerScripts will create a tool in the player's backpack that, once equipped, will change the BasePart.BrickColor of every BasePart the player clicks on.

Color Randomizer Tool

local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
local backpack = localPlayer:WaitForChild("Backpack")
local tool = Instance.new("Tool")
tool.RequiresHandle = false
tool.CanBeDropped = false
tool.Parent = backpack
tool.Equipped:Connect(function(mouse)
mouse.Button2Down:Connect(function()
if mouse.Target and mouse.Target.Parent then
mouse.Target.BrickColor = BrickColor.random()
end
end)
end)

Button2Up

Se activa cuando se libera el botón derecho del ratón.


mouse.Button2Up:Connect(function()
print("button 2 up!")
end

Para obtener la información sobre cómo obtener el objeto Mouse, consulte la página Mouse.

Los desarrolladores pueden encontrar la posición del mouse en el espacio del mundo, y si está apuntando a cualquier BasePart usando las propiedades Mouse.Hit y Mouse.Target.

Nota, se recomienda a los desarrolladores usar UserInputService en lugar del objeto Mouse en el nuevo trabajo.


Amostras de código

The follow example changes the BasePart.BrickColor of every BasePart the player clicks and releases their right mouse button on.

In order for a part to change color, the player's mouse must be over the part both when the player presses their right mouse button down and when the player releases their right mouse button.

Color Randomizer Tool (Button2Up)

local Players = game:GetService("Players")
local mouse = Players.LocalPlayer:GetMouse()
local target = nil
mouse.Button2Down:Connect(function()
target = mouse.Target
end)
mouse.Button2Up:Connect(function()
if target == mouse.Target then
target.BrickColor = BrickColor.random()
end
end)

Idle

Se activa durante cada latido del corazón que el mouse no se está pasando a otro evento del mouse.

Nota, este evento no debe utilizarse para determinar cuando el mouse aún está. Como se activa cada latido del corazón, se activará entre los eventos Mouse.Move .

Para obtener la información sobre cómo obtener el objeto Mouse, consulte la página Mouse.

Los desarrolladores pueden encontrar la posición del mouse en el espacio del mundo, y si está apuntando a cualquier BasePart usando las propiedades Mouse.Hit y Mouse.Target.

Nota, se recomienda a los desarrolladores usar UserInputService en lugar del objeto Mouse en el nuevo trabajo.


Amostras de código

This example demonstrates how mouse events are passed during each frame

Mouse.Idle

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local events = {
"Button1Down",
"Button1Up",
"Button2Down",
"Button2Up",
"Idle",
"Move",
"WheelBackward",
"WheelForward",
"KeyDown",
"KeyUp",
}
local currentEvent
local frame = 0
local function processInput()
frame = frame + 1
print("Frame", frame, "- mouse event was passed to", currentEvent)
end
for _, event in pairs(events) do
mouse[event]:Connect(function()
currentEvent = event
end)
end
RunService:BindToRenderStep("ProcessInput", Enum.RenderPriority.Input.Value, processInput)

Move

Se activa cuando el mouse se mueve.

Nota, este evento se activa cuando se actualiza la posición del ratón, por lo tanto, se activará repetidamente mientras se mueve.

Para obtener la información sobre cómo obtener el objeto Mouse, consulte la página Mouse.

Los desarrolladores pueden encontrar la posición del mouse en el espacio del mundo, y si está apuntando a cualquier BasePart usando las propiedades Mouse.Hit y Mouse.Target.


mouse.Move:Connect(function()
local position = mouse.Hit.p
local target = mouse.Target
print(target, position)
end)

Nota, se recomienda a los desarrolladores usar UserInputService en lugar del objeto Mouse en el nuevo trabajo.


Amostras de código

The example below allows the local player to move parts with their mouse.

When the player presses their left mouse button over a part, that part is the mouse's target and becomes the point. Until the player releases their left mouse button, that part will move to the mouse's world position when the player moves their mouse.

Note that the Mouse.TargetFilter property allows the code to ignore the part being moved when determining the mouse's world position.

The code should work as expected when placed in a LocalScript.

Move Parts with the Mouse

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local point
local down
local function selectPart()
if mouse.Target and not mouse.Target.Locked then
point = mouse.Target
mouse.TargetFilter = point
down = true
end
end
local function movePart()
if down and point then
local posX, posY, posZ = mouse.Hit.X, mouse.Hit.Y, mouse.Hit.Z
point.Position = Vector3.new(posX, posY, posZ)
end
end
local function deselectPart()
down = false
point = nil
mouse.TargetFilter = nil
end
mouse.Button1Down:Connect(selectPart)
mouse.Button1Up:Connect(deselectPart)
mouse.Move:Connect(movePart)

WheelBackward

El evento WheelBackward se activa cuando la rueda del mouse se desplaza hacia atrás. Las posibles usos para este evento incluyen alternar el enfoque de un rifle de asalto en primera persona (FPS) o acercar la cámara del jugador.

Esto se puede utilizar junto con el evento de desplazamiento hacia adelante, Mouse.WheelForward .

Para obtener la información sobre cómo obtener el objeto Mouse, consulte la página Mouse.

Nota, se recomienda a los desarrolladores usar UserInputService en lugar del objeto Mouse en el nuevo trabajo.


Amostras de código

The below example assumes that you have already got the player's mouse (and set it as a variable named 'mouse'), whether by use of a Tool, HopperBin or the Player:GetMouse() method. It will print "Wheel went backwards!" when the player scrolls backwards.

Mouse.WheelBackward

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local function onWheelBackward()
print("Wheel went backwards!")
end
mouse.WheelBackward:Connect(onWheelBackward)

WheelForward

El evento WheelForward se activa cuando la rueda del mouse se desplaza hacia adelante. Las posibles usos para este evento incluyen alternar el enfoque de un rifle de asalto en un tirador de primera persona (FPS) o acercar la cámara del jugador.

Esto se puede utilizar junto con el evento de desplazamiento hacia atrás, Mouse.WheelBackward .

Para obtener la información sobre cómo obtener el objeto Mouse, consulte la página Mouse.

Nota, se recomienda a los desarrolladores usar UserInputService en lugar del objeto Mouse en el nuevo trabajo.


Amostras de código

The below example assumes that you have already got the player's mouse (and set it as a variable named 'mouse'), whether by use of a Tool, HopperBin or the Player:GetMouse() method. It will print "Wheel went forward!" when the player scrolls forwards.

Mouse.WheelForward

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local function onWheelBackward()
print("Wheel went forward!")
end
mouse.WheelForward:Connect(onWheelBackward)