Mouse

Visualizza obsoleti

*Questo contenuto è tradotto usando AI (Beta) e potrebbe contenere errori. Per visualizzare questa pagina in inglese, clicca qui.

Non costruibile

Mouse è stato superato da UserInputService e ContextActionService, che coprono un'ampia gamma, sono più ricche di funzionalità e supportano meglio i modelli 0> cross-platform0>. Viene supportato per il suo ampio utilizzo, ma dovresti fortemente considerare di utilizzare queste alternative.

L'oggetto Mouse contiene varie API per i puntatori, principalmente per i pulsanti e il raycasting. Può essere accessato attraverso Player:GetMouse() chiamato sul Players.LocalPlayer in un 1> Class.LocalScript1> . È anche passato dall'evento 4> Class.Tool.Equipped4> .

  • È il più noto per la ProprietàIcon, che cambia l'aspetto del cursore.
  • Raggiunge continuamente la posizione del mouse sullo schermo utilizzando la ProprietàTargetFilter, memorizzando i risultati del raycast nel Hit, Target e
  • Plugins può usare Plugin:GetMouse() per ottenere un PluginMouse, che funziona allo stesso modo.

-- Da un LocalScript:
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
-- Impostazione dell'Iconadel mouse
mouse.Icon = "rbxasset://SystemCursors/Wait"

Nota:

  • Questo oggetto non controlla/limitare il movimento del puntatore. Per questo, vedi UserInputService.MouseBehavior e UserInputService.MouseDeltaSensitivity .

  • Se due funzioni sono connesse allo stesso evento di input, come Button1Down, entrambe le funzioni saranno eseguite quando si attiva l'evento. Non esiste il concetto di affondamento/passaggio dell'input, poiché gli eventi non supportano questo comportamento. Tuttavia, ContextActionService ha questo

  • Mentre un mouse potrebbe non essere disponibile su tutte le piattaforme, Mouse funzionerà comunque su mobile (触摸) e console (gamepad), che non hanno di solito mouse o hardware di punterizzazione. Per comportamenti espliciti su piattaforma croce, usa UserInputService e ContextActionService .

    Vedi Ingresso e telecamera per ulteriori informazioni sulla personalizzazione degli input nella tua esperienza.

Sommario

Proprietà

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Il CFrame della posizione del Topo, or mouse as computer mousenello Spazio3D.

  • Icon:ContentId
    Lettura Parallela

    L'ID del contenuto dell'immagine utilizzata come Mouse Icona.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Un CFrame posizionato al Workspace.CurrentCamera e orientato verso la posizione 3D del Topo, or mouse as computer mouse.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    L'oggetto nello spazio 3D a cui si riferisce il mouse è in mostra.

  • Lettura Parallela

    Determina un oggetto (e i suoi discendenti) da ignorare quando si determinano Mouse.Hit e Mouse.Target .

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Indica il Enum.NormalId della superficie BasePart a cui il mouse punta.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Un Ray diretto verso la posizione mondiale del Topo, or mouse as computer mouse, originato dalla posizione mondiale Workspace.CurrentCamera .

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Descrive la larghezza della finestra di gioco in pixel.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Descrive l'altezza della finestra di gioco in pixel.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Descrive il component X (orizzontale) della posizione del Topo, or mouse as computer mousesullo schermo.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Descrive il component Y (vertical) della posizione della Topo, or mouse as computer mouse.

Eventi

Proprietà

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà indica CFrame della posizione del Topo, or mouse as computer mousenello Spazio3D. Nota che Mouse.TargetFilter e i suoi discendenti saranno ignorati.

Gli sviluppatori possono ottenere la posizione di Hit come segue:


local position = mouse.Hit.Position

Hit è spesso usato da Tools per sparare un'arma verso il mouse in terza persona.

Gli sviluppatori che cercano il BasePart il mouse punta a dovrebbe usare Mouse.Target .

Come viene calcolato Mouse.Hit?

La posizione del CFrame Hit viene calcolata come punto di intersezione tra il Topo, or mouse as computer mouse's interno Ray (un'estensione di Mouse.UnitRay ) e un oggetto nello spazio 3D (come una parte).

L'orientamento del CFrame corrisponde alla direzione del Mouse.UnitRay .


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

Nota, il rullaggio della Workspace.CurrentCamera non è utilizzato quando si calcola l'orientamento del Hit CFrame .

Il raggio interno del Topo, or mouse as computer mousesi estende per 1,000 studs. Se il mouse non punta a un oggetto nello spazio 3D (ad esempio quando punta al cielo), questa proprietà sarà 1,000 studs away from the Workspace.CurrentCamera .

Campioni di codice

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
Lettura Parallela

Icon è una proprietà che determina l'immagine utilizzata come punter. Se vuoto, viene utilizzata una freccia predefinita. Mentre il cursore si posiziona su un GuiButton , questa proprietà viene temporaneamente ignorata.

Per nascondere completamente il cursore, non usare un'immagine trasparente - invece, imposta UserInputService.MouseIconEnabled su false.

Per ottenere/impostare l'icona del mouse dell'utente nelle esperienze, dovresti usare UserInputService.MouseIcon . Mouse.Icon sarà deprecato dopo la nuova API per i plugin per impostare il cursore del mouse.

Progettazione di un Cursor

Le seguenti linee guida potrebbero essere utili per creare i tuoi cursori del mouse:

  • Le dimensioni dell'immagine usata determinano la dimensione del cursore.
  • Il centro dell'immagine è dove vengono emessi gli input del mouse.
  • L'immagine del mouse predefinita è 64x64 pixel, con il mouse che occupa 17x24 pixel di Spazio.

System Cursors for PluginMouse

Quando si utilizzano PluginMouse recuperati da Plugin:GetMouse(), si


<tbody>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-Pointer.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/Arrow</code></td>
<td>Clicca e seleziona predefinito.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-PointingHand.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/PointingHand</code></td>
<td>Passare il mouse su un link/ pulsante attivo.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-OpenHand.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/OpenHand ]</code></td>
<td>Passare il mouse su un Articolotrascinabile.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-GrabbingHand.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/ClosedHand</code></td>
<td>Trascinare un Articolo.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-IBeam.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/IBeam</code></td>
<td>Passare in un campo di testo.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-ResizeNS.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/SizeNS</code></td>
<td>Passare il mouse su una gestiredi ridimensionamento verticale.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-ResizeEW.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/SizeEW</code></td>
<td>Passare il mouse su una gestiredi ridimensionamento orizzontale.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-ResizeNESW.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/SizeNESW</code></td>
<td>Passare il mouse su un'immagine di gestire.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-ResizeNWSE.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/SizeNWSE</code></td>
<td>Passare il mouse su un'immagine di gestire.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-ResizeAll.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/SizeAll</code></td>
<td>Passare il mouse su una gestiredi ridimensionamento multi-direzione.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-ResizeSplitV.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/SplitNS</code></td>
<td>Passare il mouse su un gestire"spaccabile" verticale.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-ResizeSplitH.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/SplitEW</code></td>
<td>Passare il mouse su un'gestireorizzontale "spaccata".</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-Forbidden.png">
</img>
</td>
<td> rbxasset://SystemCursors/Forbidden ]]</td>
<td>Passare il mouse su un Articolobloccato/vietato.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-Wait.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/Wait</code></td>
<td>Indica un'azione in corso.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-Busy.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/Busy ]</code></td>
<td>Indicare che il sistema è occupato.</td>
</tr>
<tr>
<td>
<img src="../../../assets/legacy/Mouse-Icon-Crosshair.png">
</img>
</td>
<td><code>rbxasset://SystemCursors/Cross</code></td>
<td>Passare con il mouse su un'area di selezione.</td>
</tr>
</tbody>
Ottieni\*AttivitàUso consigliato

Queste apparenze sono approssimazioni - l'aspetto reale è dipendente dal tuo sistema operativo.

Campioni di codice

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

Sola Lettura
Non Replicato
Lettura Parallela

La proprietà Mouse deriva è una CFrame che indica da dove viene il mouse. È posizionato al Workspace.CurrentCamera e orientato verso la posizione 3D del Topo, or mouse as computer mouse.

Mouse.UnitRay inizia nella stessa posizione dell'Origin, e si estende per uno stud nella stessa direzione.


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

Per la posizione della Mouse in Spazio3D, vedi Mouse.Hit .

Campioni di codice

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

Sola Lettura
Non Replicato
Lettura Parallela

L'oggetto nello spazio 3D a cui si riferisce il mouse è in mostra.

Nota:

  • Se Mouse.TargetFilter è stato Impostare, il filtro target e i suoi discendenti saranno ignorati.
  • Quando il mouse non punta a un BasePart , ad esempio quando punta al cielo, Target sarà nullo.
  • Gli sviluppatori che cercano la posizione del mouse nello spazio 3D dovrebbero usare Mouse.Hit .

Campioni di codice

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

Lettura Parallela

Questa proprietà determina un oggetto da ignorare dal mouse quando si calcola Mouse.Hit e Mouse.Target . I discendenti dell'oggetto sono anche ignorati, quindi è possibile ignorare più oggetti finché non sono discendenti dell'oggetto a cui questa proprietà è Impostare. Questa proprietà

Questa proprietà può essere impostata su qualsiasi Instance o null, ad esempio:


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

Nota che il Character del Players.LocalPlayer viene ignorato automaticamente dal mouse.

TargetSurface

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà indica il Enum.NormalId della superficie BasePart a cui il mouse punta. Questa proprietà è得ata dalla posizione mondiale del mouse ( Mouse.Hit ) e dalla parte verso cui il mouse punta ( 1> Class.Mouse.Target1> ).

Questa proprietà non ha senso quando il mouse non punta a una parte, ad esempio quando il mouse punta al cielo. Al momento, questa proprietà è impostata su "Giusto" in queste condizioni. Prima di utilizzare questa Proprietà, controlla che il target del Topo, or mouse as computer mousenon sia null.


local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
-- Controlla che esista una parte a cui il mouse punta
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

Campioni di codice

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

Sola Lettura
Non Replicato
Lettura Parallela

La proprietà UnitRay è una Ray rivolta verso la posizione del Topo, or mouse as computer mousenello spazio 3D (descritta da Mouse.Hit ) . Si originò dal CFrame della 2> Class.Area di lavoro.CurrentCamera2> . Come tutti i ray dell'unità, ha una distanza di 1.


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

ViewSizeX

Sola Lettura
Non Replicato
Lettura Parallela

La proprietà ViewSizeX descrive la componenti orizzontali della dimensione della finestra di gioco in pixel.

Campioni di codice

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

Sola Lettura
Non Replicato
Lettura Parallela

La proprietà ViewSizeY descrive la dimensione verticale della finestra di gioco in pixel. Questa lunghezza include lo spazio usato dalla barra superiore.

Campioni di codice

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)
Sola Lettura
Non Replicato
Lettura Parallela

Quando si rileva la posizione delle modifiche nella posizione del Topo, or mouse as computer mousesullo schermo, si consiglia di utilizzare ContextActionService:BindAction() con Enum.UserInputType.MouseMovement o Class.UserInputService.InputChanged

La proprietà X descrive la componentente orizzontale della posizione del Topo, or mouse as computer mousesullo schermo. La posizione viene misurata in pixel rispetto all'angolo in alto a sinistra, sotto la barra superiore. Questa proprietà può essere utilizzata in conjunction with Mouse.Y to produce a Vector2 rappresentante la posizione del Topo, or mouse as computer mouse:


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

Questa proprietà non fire Changed o il segnale restituito da GetPropertyChangedSignal . Usa invece l'evento Mouse.Move .

Campioni di codice

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)
Sola Lettura
Non Replicato
Lettura Parallela

Quando si rileva la posizione delle modifiche nella posizione del Topo, or mouse as computer mousesullo schermo, si consiglia di utilizzare ContextActionService:BindAction() con Enum.UserInputType.MouseMovement o Class.UserInputService.InputChanged

La proprietà Y descrive la componente verticale della posizione del Topo, or mouse as computer mousesulla schermata. La posizione viene misurata in pixel rispetto all'angolo in alto a sinistra, sotto la barra superiore. Questa proprietà può essere utilizzata in conjunction with Mouse.X to produce a Vector2 rappresentante la posizione del Topo, or mouse as computer mouse:


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

Questa proprietà non fire Changed o il segnale restituito da GetPropertyChangedSignal . Usa invece l'evento Mouse.Move .

Campioni di codice

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)

Metodi

Eventi

Button1Down

Il pulsante1Down persino si attiva quando il giocatore premere il loro pulsante sinistro del mouse.

Questo può essere acceduto anche da un Tool. Ad esempio, quando viene inserito in un LocalScript, il codice seguente stampa Button1Down ogni volta che viene premuto il pulsante sinistro del mouse:


local Tool = script.Parent --assicurati che questo sia un oggetto Tool
Tool.Equipped:Connect(function(Mouse)
Mouse.Button1Down:Connect(function()
print("Button1Down")
end)
end)

Gli sviluppatori possono trovare la posizione del mouse nello spazio del mondo e se punta a qualsiasi BasePart , utilizzando le proprietà Mouse.Hit e Mouse.Target.

Per informazioni su come ottenere l'oggetto del mouse, vedi la pagina Mouse.

Nota, gli sviluppatori sono raccomandati a utilizzare UserInputService invece dell'oggetto Mouse nel nuovo lavoro.


Campioni di codice

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

Si attiva quando il pulsante sinistro del mouse viene rilasciato.

Per informazioni su come ottenere l'oggetto Mouse, vedi la pagina Mouse.

Gli sviluppatori possono trovare la posizione del mouse nello spazio del mondo e se punta a qualsiasi BasePart utilizzando le proprietà Mouse.Hit e Mouse.Target.

Nota, gli sviluppatori sono raccomandati a utilizzare UserInputService invece dell'oggetto Mouse nel nuovo lavoro.


Campioni di codice

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

Il pulsante2Down persino si attiva quando il giocatore premere il loro pulsante destro del mouse.

Questo può essere acceduto anche da un Tool. Ad esempio, quando viene inserito in un LocalScript, il codice seguente stampa Button2Down ogni volta che viene premuto il pulsante destro del mouse:


local Tool = script.Parent --assicurati che questo sia un oggetto Tool
Tool.Equipped:Connect(function(Mouse)
Mouse.Button2Down:Connect(function()
print("Button2Down")
end)
end).

Gli sviluppatori possono trovare la posizione del mouse nello spazio del mondo e se punta a qualsiasi BasePart , utilizzando le proprietà Mouse.Hit e Mouse.Target.

Per informazioni su come ottenere l'oggetto del mouse, vedi la pagina Mouse.

Nota, gli sviluppatori sono raccomandati a utilizzare UserInputService invece dell'oggetto Mouse nel nuovo lavoro.


Campioni di codice

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

Si attiva quando viene rilasciato il pulsante destro del mouse.


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

Per informazioni su come ottenere l'oggetto Mouse, vedi la pagina Mouse.

Gli sviluppatori possono trovare la posizione del mouse nello spazio del mondo e se punta a qualsiasi BasePart utilizzando le proprietà Mouse.Hit e Mouse.Target.

Nota, gli sviluppatori sono raccomandati a utilizzare UserInputService invece dell'oggetto Mouse nel nuovo lavoro.


Campioni di codice

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

Si attiva durante ogni battito cardiaco in cui il mouse non viene passato a un altro evento del mouse.

Nota, questo evento non dovrebbe essere utilizzato per determinare quando il mouse è ancora. Poiché si attiva ogni battito cardiaco, si attiverà tra Mouse.Move eventi.

Per informazioni su come ottenere l'oggetto Mouse, vedi la pagina Mouse.

Gli sviluppatori possono trovare la posizione del mouse nello spazio del mondo e se punta a qualsiasi BasePart utilizzando le proprietà Mouse.Hit e Mouse.Target.

Nota, gli sviluppatori sono raccomandati a utilizzare UserInputService invece dell'oggetto Mouse nel nuovo lavoro.


Campioni di codice

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

Si attiva quando il mouse viene spostato.

Nota, questo evento viene attivato quando la posizione del Topo, or mouse as computer mouseviene aggiornata, quindi si attiva ripetutamente mentre viene spostato.

Per informazioni su come ottenere l'oggetto Mouse, vedi la pagina Mouse.

Gli sviluppatori possono trovare la posizione del mouse nello spazio del mondo e se punta a qualsiasi BasePart utilizzando le proprietà Mouse.Hit e Mouse.Target.


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

Nota, gli sviluppatori sono raccomandati a utilizzare UserInputService invece dell'oggetto Mouse nel nuovo lavoro.


Campioni di codice

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

L'evento WheelBackward viene attivato quando la ruota del mouse viene scorrevole verso l'indietro. Possibili utilizzi per questo evento includono l'attivazione di uno scopo di un'arma in una prima persona shooter (FPS) o l'allargamento della Telecameradel Giocatore.

Questo può essere utilizzato insieme all'evento di avanzamento della scorrimento, Mouse.WheelForward .

Per informazioni su come ottenere l'oggetto Mouse, vedi la pagina Mouse.

Nota, gli sviluppatori sono raccomandati a utilizzare UserInputService invece dell'oggetto Mouse nel nuovo lavoro.


Campioni di codice

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

L'evento WheelForward si attiva quando la ruota del mouse viene scorrevole verso l'avanti. Possibili utilizzi per questo evento includono la attivazione di uno scopo di un'arma in un primo person shooter (FPS) o la riproduzione della Telecameradel Giocatore.

Questo può essere utilizzato insieme all'evento di scorrimento in avanti, Mouse.WheelBackward .

Per informazioni su come ottenere l'oggetto Mouse, vedi la pagina Mouse.

Nota, gli sviluppatori sono raccomandati a utilizzare UserInputService invece dell'oggetto Mouse nel nuovo lavoro.


Campioni di codice

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)