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 sostituito da UserInputService e ContextActionService, che coprono una gamma più ampia, sono più ricchi di funzionalità e supportano meglio i modelli cross-platform .Rimane supportato a causa del suo uso diffuso, ma dovresti prendere in considerazione fortemente l'uso di queste alternative.

L'oggetto Mouse ospita diverse API per i puntatori, principalmente per i pulsanti e il raycasting.Può essere accessato attraverso Player:GetMouse() chiamato sul Players.LocalPlayer in un LocalScript .Viene anche passato dall'evento Tool.Equipped .

  • È più notevole per la ProprietàIcon che cambia l'aspetto del cursore.
  • Continua a lanciare la posizione del mouse dello schermo nel mondo 3D utilizzando la ProprietàTargetFilter, memorizzando i risultati del lancio del raycast nelle proprietà Hit, Target e TargetSurface.Questi possono essere utili per casi semplici, ma WorldRoot:Raycast() dovrebbero essere utilizzati in scenari più complicati di raycasting.
  • Plugins può utilizzare Plugin:GetMouse() per ottenere un PluginMouse, che si comporta in modo simile.

-- Da uno script locale:
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
-- Impostare l'Iconadel mouse
mouse.Icon = "rbxasset://SystemCursors/Wait"

Nota:

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

  • Se due funzioni sono connesse allo stesso evento di input, come , entrambe le funzioni verranno eseguite quando l'evento si attiva.Non esiste il concetto di input che affonda/passa, poiché gli eventi non supportano questo comportamento.Tuttavia, ContextActionService ha questo comportamento attraverso BindAction .

  • Mentre un mouse potrebbe non essere disponibile su tutte le piattaforme, il mouse funzionerà ancora su mobile (touch) e console (gamepad), che di solito non hanno mouse o puntatori hardware.Per i comportamenti cross-piattaforma espliciti, usa UserInputService e ContextActionService .

    Vedi Input e fotocamera 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 IconaMouse.

  • 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 il mouse punta.

  • Lettura Parallela

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

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Indica il Enum.NormalId della superficie BasePart in cui il mouse è puntato.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Un Ray diretto verso la posizione del mondo del Topo, or mouse as computer mouse, originato dalla posizione del mondo 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 del gioco in pixel.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

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

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Descrive la componente Y (verticale) della posizione dello schermo del 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 verranno ignorati.

Gli sviluppatori possono ottenere la posizione di Hit come segue:


local position = mouse.Hit.Position

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

Gli sviluppatori che cercano il BasePart il mouse è puntato dovrebbero usare Mouse.Target .

Come viene calcolato Mouse.Hit?

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

L'orientamento del CFrame colpito 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 rotolo del Workspace.CurrentCamera non viene utilizzato quando si calcola l'orientamento del colpo 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à a 1.000 studs di distanza dal 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

L'icona è una proprietà che determina l'immagine utilizzata come puntatore.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 verrà rilasciata.

Progettazione di un cursore

Le seguenti linee guida possono rivelarsi utili quando crei i tuoi cursori del mouse:

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

Quando si utilizza un PluginMouse recuperato da Plugin:GetMouse() , puoi utilizzare le seguenti icone simili ai cursori predefiniti del tuo sistema, come mani, frecce, I-beam, ecc.Puoi usarli con eventi GUI come MouseEnter , MouseLeave e MouseButton1Down per fornire un'esperienza Studio coerente quando interagisci con determinati tipi di componenti GUI.Nota che funzionano solo per i plugin di Studio; non funzioneranno per altri oggetti Mouse .


<th>Attività</th>
<th>Uso suggerito</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<img src="../../../assets/misc/Mouse-Icon-Pointer.png" width="30">
</img>
</td>
<td><code>rbxasset://SystemCursors/Arrow</code></td><td>Clicking e selezione predefinita.</td>
</tr>
<tr>
<td>
<img src="../../../assets/misc/Mouse-Icon-PointingHand.png" width="30">
</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/misc/Mouse-Icon-OpenHand.png" width="30">
</img>
</td>
<td><code>rbxasset://SystemCursors/OpenHand</code></td><td>Passare il mouse su un Articolotrascinabile.</td>
</tr>
<tr>
<td>
<img src="../../../assets/misc/Mouse-Icon-GrabbingHand.png" width="30">
</img>
</td>
<td><code>rbxasset://SystemCursors/ClosedHand</code></td><td>Trascinare un Articolo.</td>
</tr>
<tr>
<td>
<img src="../../../assets/misc/Mouse-Icon-IBeam.png" width="30">
</img>
</td>
<td><code>rbxasset://SystemCursors/IBeam</code></td><td>Passare il mouse su un campo di testo.</td>
</tr>
<tr>
<td>
<img src="../../../assets/misc/Mouse-Icon-ResizeNS.png" width="30">
</img>
</td>
<td><code>rbxasset://SystemCursors/SizeNS</code></td><td>Passare il gestiresu una maniglia di ridimensionamento verticale.</td>
</tr>
<tr>
<td>
<img src="../../../assets/misc/Mouse-Icon-ResizeEW.png" width="30">
</img>
</td>
<td><code>rbxasset://SystemCursors/SizeEW</code></td><td>Passare il gestiresu un cursore orizzontale di ridimensionamento.</td>
</tr>
<tr>
<td>
<img src="../../../assets/misc/Mouse-Icon-ResizeNESW.png" width="30">
</img>
</td>
<td><code>rbxasset://SystemCursors/SizeNESW</code></td><td>Passare il gestiresu un bordo della maniglia di ridimensionamento.</td>
</tr>
<tr>
<td>
<img src="../../../assets/misc/Mouse-Icon-ResizeNWSE.png" width="30">
</img>
</td>
<td><code>rbxasset://SystemCursors/SizeNWSE</code></td><td>Passare il gestiresu un bordo della maniglia di ridimensionamento.</td>
</tr>
<tr>
<td>
<img src="../../../assets/misc/Mouse-Icon-ResizeAll.png" width="30">
</img>
</td>
<td><code>rbxasset://SystemCursors/SizeAll</code></td><td>Passare il gestiresu una maniglia di ridimensionamento multi-direzionale.</td>
</tr>
<tr>
<td>
<img src="../../../assets/misc/Mouse-Icon-ResizeSplitV.png" width="30">
</img>
</td>
<td><code>rbxasset://SystemCursors/SplitNS</code></td><td>Passare il gestiresu un'impugnatura verticale "divisa".</td>
</tr>
<tr>
<td>
<img src="../../../assets/misc/Mouse-Icon-ResizeSplitH.png" width="30">
</img>
</td>
<td><code>rbxasset://SystemCursors/SplitEW</code></td><td>Passare il gestiresu un'impugnatura orizzontale "divisa".</td>
</tr>
<tr>
<td>
<img src="../../../assets/misc/Mouse-Icon-Forbidden.png" width="30">
</img>
</td>
<td><code>rbxasset://SystemCursors/Forbidden</code></td><td>Passare il mouse su un Articolobloccato/vietato.</td>
</tr>
<tr>
<td>
<img src="../../../assets/misc/Mouse-Icon-Wait.png" width="30">
</img>
</td>
<td><code>rbxasset://SystemCursors/Wait</code></td><td>Indicare un'azione è in corso.</td>
</tr>
<tr>
<td>
<img src="../../../assets/misc/Mouse-Icon-Busy.png" width="30">
</img>
</td>
<td><code>rbxasset://SystemCursors/Busy</code></td><td>Indicando che il sistema è occupato.</td>
</tr>
<tr>
<td>
<img src="../../../assets/misc/Mouse-Icon-Crosshair.png" width="30">
</img>
</td>
<td><code>rbxasset://SystemCursors/Cross</code></td><td>Passare il mouse su un'area di selezione precisa.</td>
</tr>
</tbody>
Guarda*
\* Queste apparenze sono approssimazioni — l'aspetto effettivo dipende 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à origine indica l'origine da cui il mouse si è originato.Si trova alla Workspace.CurrentCamera e si orienta verso la posizione 3D del Topo, or mouse as computer mouse.

Mouse.UnitRay inizia nello stesso punto di Origin e si estende per uno stud nella stessa direzione.


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

Per la posizione del 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 il mouse punta.

Nota:

  • Se Mouse.TargetFilter è stato Impostare, il filtro target e i suoi discendenti verranno ignorati.
  • Quando il mouse non punta a un BasePart, ad esempio quando punta al cielo, il bersaglio sarà nil .
  • 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 durante il calcolo di Mouse.Hit e Mouse.Target .Anche i discendenti dell'oggetto vengono ignorati, quindi è possibile ignorare più oggetti finché sono un discendente dell'oggetto a cui questa proprietà è Impostare.Questa proprietà è utile quando si filtra modelli che contengono effetti speciali o decorazioni che non dovrebbero influenzare Mouse.Hit o Mouse.Target .

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


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

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

TargetSurface

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà indica la Enum.NormalId della superficie BasePart in cui il mouse si sta muovendo.Questa proprietà deriva dalla posizione mondiale del mouse ( Mouse.Hit ) e dalla parte a cui il mouse si sta dirigendo ( Mouse.Target ).

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 'Destra' in queste circostanze.Prima di utilizzare questa Proprietà, controlla che il bersaglio del Topo, or mouse as computer mousenon sia nil .


local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
-- Verifica che esista una parte a cui il mouse è puntato
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 diretta verso la posizione del Topo, or mouse as computer mousenello spazio 3D (descritta da Mouse.Hit ).Deriva dal CFrame del Workspace.CurrentCamera .Come tutti i raggi di 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 componente orizzontale della dimensione della finestra del 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 componente verticale della dimensione della finestra del gioco in pixel. Questa lunghezza include lo spazio utilizzato 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 rilevano modifiche nella posizione del Topo, or mouse as computer mousesullo schermo, si consiglia di utilizzare ContextActionService:BindAction() con Enum.UserInputType.MouseMovement o UserInputService.InputChanged , che entrambi descrivono la posizione del mouse utilizzando il Position (un Vector3 ) di un InputObject, invece di utilizzare questa e le proprietà correlate.

La proprietà X descrive la componente 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 combinazione con Mouse.Y per produrre un Vector2 che rappresenta la posizione del Topo, or mouse as computer mouse:


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

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

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 rilevano modifiche nella posizione del Topo, or mouse as computer mousesullo schermo, si consiglia di utilizzare ContextActionService:BindAction() con Enum.UserInputType.MouseMovement o UserInputService.InputChanged , che entrambi descrivono la posizione del mouse utilizzando il Position (un Vector3 ) di un InputObject, invece di utilizzare questa e le proprietà correlate.

La proprietà Y descrive la componente verticale 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 combinazione con Mouse.X per produrre un Vector2 che rappresenta la posizione del Topo, or mouse as computer mouse:


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

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

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

Questo evento si attiva quando il giocatore premere il pulsante sinistro del mouse.Nota che questo può essere accessibile da un Tool ; ad esempio, quando viene posizionato 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)

Puoi scoprire la posizione del mouse nello spazio del mondo e se sta puntando a qualsiasi BasePart utilizzando le proprietà Hit e Target.


Button1Up

Questo evento si attiva quando il giocatore rilascia il pulsante sinistro del mouse.Nota che questo può essere accessibile da un Tool ; ad esempio, quando viene posizionato in un LocalScript , il codice seguente stampa Button1Up ogni volta che viene rilasciato il pulsante sinistro del mouse.


local tool = script.Parent -- Assicurati che questo sia un oggetto Tool
tool.Equipped:Connect(function(mouse)
mouse.Button1Up:Connect(function()
print("Button1Up")
end)
end)

Puoi scoprire la posizione del mouse nello spazio del mondo e se sta puntando a qualsiasi BasePart utilizzando le proprietà Hit e Target.


Button2Down

Questo evento si attiva quando il giocatore premere il pulsante destro del mouse.Nota che questo può essere accessibile da un Tool ; ad esempio, quando viene posizionato 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)

Puoi scoprire la posizione del mouse nello spazio del mondo e se sta puntando a qualsiasi BasePart utilizzando le proprietà Hit e Target.


Button2Up

Questo evento si attiva quando il giocatore rilascia il pulsante destro del mouse.Nota che questo può essere accessibile da un Tool ; ad esempio, quando viene posizionato in un LocalScript , il codice seguente stampa Button2Up ogni volta che viene rilasciato il pulsante destro del mouse.


local tool = script.Parent -- Assicurati che questo sia un oggetto Tool
tool.Equipped:Connect(function(mouse)
mouse.Button2Up:Connect(function()
print("Button2Up")
end)
end)

Puoi scoprire la posizione del mouse nello spazio del mondo e se sta puntando a qualsiasi BasePart utilizzando le proprietà Hit e Target.


Idle

Sparato durante ogni battito di cuore in cui il mouse non viene passato ad un altro evento del mouse.

Nota, questo evento non deve essere utilizzato per determinare quando il mouse è fermo. Come spara ogni battito cardiaco, spara tra Mouse.Move eventi.

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

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

Nota, agli sviluppatori si consiglia di utilizzare UserInputService invece dell'oggetto Mouse in 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

Sparato quando il mouse viene spostato.

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

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

Gli sviluppatori possono scoprire la posizione del mouse nello spazio mondiale 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, agli sviluppatori si consiglia di utilizzare UserInputService invece dell'oggetto Mouse in 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 si attiva quando la ruota del mouse viene scoraggiata all'indietro.Gli usi possibili di questo evento includono la selezione del campo visivo di una pistola in un primo giocatore in prima persona (FPS) o lo zoom della Telecameradel Giocatore.

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

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

Nota, agli sviluppatori si consiglia di utilizzare UserInputService invece dell'oggetto Mouse in 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 scoraggiata in avanti.Gli usi possibili di questo evento includono la selezione del campo visivo di una pistola in un primo giocatore in prima persona (FPS) o lo zoom della Telecameradel Giocatore.

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

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

Nota, agli sviluppatori si consiglia di utilizzare UserInputService invece dell'oggetto Mouse in 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 onWheelForward()
print("Wheel went forward!")
end
mouse.WheelForward:Connect(onWheelForward)