Tool
*Questo contenuto è tradotto usando AI (Beta) e potrebbe contenere errori. Per visualizzare questa pagina in inglese, clicca qui.
Gli strumenti sono oggetti che un oggetto Humanoid può equipaggiare.Per i giocatori, vengono memorizzati in un oggetto Backpack genitore di un oggetto Player.In gioco, i giocatori possono avere più strumenti che appaiono come icone in basso sullo schermo.Equipaggiare uno strumento lo sposta dal Backpack e in un modello Player.Character nel Workspace .Per impostazione predefinita, gli strumenti sono tenuti nella mano destra e hanno una maniglia in loro, che è un Part chiamato "Maniglia" all'interno (anche se uno non è richiesto se Tool.RequiresHandle è Off).Gli strumenti che devono essere forniti ai (re)spawn dei giocatori dovrebbero essere memorizzati nel StarterPack .
Sul Desktop, premendo una tastiera numerica (1, 2, 3...) verrà equipaggiato uno strumento.Gli strumenti equipaggiati possono essere rilasciati nello spazio di lavoro premendo Backspace.Si consiglia di disattivare Tool.CanBeDropped off in modo che non sia possibile rilasciare uno strumento, morire, respawnare e rilasciare di nuovo gli strumenti duplicati.Sugli gamepad, i pulsanti LB e RB equipaggeranno gli strumenti.Puoi disabilitare l'attivazione tramite clic sinistro (o trigger destro sul gamepad) impostando Tool.ManualActivationOnly su.Per farlo è necessario che tu chiami Attiva te stesso attraverso una sorta di input dell'altro utente.
Gli strumenti non sono l'unico modo per catturare l'input dell'utente.Puoi anche usare ContextActionService , UserInputService o Player:GetMouse() .Se hai bisogno di uno strumento per avere più azioni, come premere un tasto mentre lo strumento è equipaggiato, dovresti usare ContextActionService's BindAction e UnbindAction negli eventi Equipped e Unequipped, rispettivamente.Usa un LocalScript invia queste azioni al server tramite un RemoteFunction all'interno dello strumento.
Campioni di codice
This code is meant to be placed in a Script within a Tool. It allows a player to spawn explosions by equipping the tool and clicking on the ground. It does so by defining a function, explode, which creates a non-deadly explosion at a given point. Then, it defines a function, onActivated, that runs when the tool is activated. Finally, it connects the Activated event of the tool to the onActivated function.
To test this code out, try creating a Tool and put a Part inside it. Name the Part "Handle". Put a Script inside the Tool next, and paste the code into it. Finally, put the Tool in the StarterPack.
local tool = script.Parent
local function explode(point)
local e = Instance.new("Explosion")
e.DestroyJointRadiusPercent = 0 -- Make the explosion non-deadly
e.Position = point
e.Parent = workspace
end
local function onActivated()
-- Get the Humanoid that Activated the tool
local human = tool.Parent.Humanoid
-- Call explode with the current point the Humanoid is targetting
explode(human.TargetPoint)
end
tool.Activated:Connect(onActivated)
This code sample is for a Tool object with a Part named Handle. It detects when Humanoids other than the current holder hit the handle, and deals some damage to them. In addition, when the Tool is activated, it triggers a slash animation in the default character animation scripts. Try out this script by creating a Tool object in the StarterPack. Put a Part inside it, and name it Handle. Paste this code into a Script inside the Tool, then try slashing at another Humanoid!
local tool = script.Parent
local function onTouch(partOther)
-- First, try to see if the part we touched was part of a Humanoid
local humanOther = partOther.Parent:FindFirstChild("Humanoid")
-- Ignore touches by non-humanoids
if not humanOther then
return
end
-- Ignore touches by the Humanoid carrying the sword
if humanOther.Parent == tool.Parent then
return
end
humanOther:TakeDamage(5)
end
-- Trigger a slash animation
local function slash()
-- Default character scripts will listen for a "toolanim" StringValue
local value = Instance.new("StringValue")
value.Name = "toolanim"
value.Value = "Slash" -- try also: Lunge
value.Parent = tool
end
tool.Activated:Connect(slash)
tool.Handle.Touched:Connect(onTouch)
Sommario
Proprietà
Controlla se il giocatore può rilasciare lo strumento.
Si riferisce se lo strumento può essere utilizzato o meno.
Memorizza le proprietà "grip" dello strumento come una sola CFrame.
Rappresenta il R02 , R12 e R22 i valori della matrice di rotazione dell'impugnatura CFrame .
Lo spostamento posizionale della matrice di saldatura dello strumento.
Rappresenta il R00 , R10 e R20 i valori della matrice di rotazione dell'impugnatura CFrame .
Rappresenta il R01 , R11 e R21 i valori della matrice di rotazione dell'impugnatura CFrame .
La proprietà ManualActivationOnly controlla se il Tool può essere attivato senza eseguire Tool:Activate() .
Determina se una funzione Tool senza gestire.
Controlla il messaggio visualizzato quando il mouse del Giocatoresi posiziona sullo strumento nel suo zaino.
L'icona della texture che viene visualizzata per uno strumento nel backpack del Giocatore.
Imposta il livello di dettaglio sul modello per le esperienze con streaming di istanza abilitato.
Controlla il comportamento di streaming del modello su Models quando l' streaming delle istanze è abilitato.
La parte principale del Model , o nil se non esplicitamente Impostare.
Proprietà utilizzata solo dall'editor per ridimensionare il modello attorno al suo asse. Impostare questa proprietà sposterà la scala come se Model/ScaleTo fosse stata chiamata su di essa.
Determina dove si trova il punto di rotazione di un che non ha un set è situato.
Metodi
Metodi provenienti da ModelImposta questo modello per essere persistente per il Giocatorespecificato.Model.ModelStreamingMode deve essere impostato su PersistentPerPlayer perché il comportamento venga modificato come risultato dell'aggiunta.
Restituisce una descrizione di un volume che contiene tutte le parti di un modello.
Restituisce la dimensione della più piccola scatola di confine che contiene tutto il BaseParts in Model, allineata con la Model.PrimaryPart se è Impostare.
Restituisce tutti gli oggetti Player che questo oggetto modello è persistente per.Il comportamento varia a seconda se questo metodo viene chiamato da un Script o da un LocalScript.
Restituisce la scala canonica del modello, che predefinisce 1 per i modelli appena creati e cambierà come viene scala tramite Model/ScaleTo .
Sposta il PrimaryPart a la posizione data. Se una parte primaria non è stata specificata, verrà utilizzata la parte radice del modello.
Rende questo modello non più persistente per il Giocatorespecificato.Model.ModelStreamingMode deve essere impostato su PersistentPerPlayer perché il comportamento venga modificato come risultato della rimozione.
Imposta il fattore di ridimensionamento del modello, regolando la dimensione e la posizione di tutte le istanze discendenti in modo che abbiano quel fattore di ridimensionamento rispetto alle loro dimensioni iniziali e alla posizione quando il fattore di ridimensionamento era 1.
Sposta un Model con lo Dislocamentodato Vector3 , preservando l'orientamento del modello.Se un altro BasePart o Terrain esiste già nella nuova posizione allora il Model sovrapporrà l'oggetto dichiarato.
Ottiene il punto focale di un PVInstance .
Trasforma il PVInstance insieme a tutti i suoi discendenti PVInstances in modo che il punto di rotazione sia ora situato all'interno del CFrame specificato.
Eventi
Si accende quando il giocatore fa clic mentre lo strumento è equipaggiato.
Si attiva quando il giocatore rilascia il clic mentre lo strumento è equipaggiato e attivato.
Si accende quando lo strumento è equipaggiato.
Si accende quando lo strumento è disequipaggiato.
Proprietà
CanBeDropped
La proprietà CanBeDropped controlla se il giocatore può rilasciare il Tool .
Se è vero, quando viene premuto il pulsante Backspace, lo strumento verrà parentizzato a Workspace e rimosso dal Giocatoredi Backpack .Se falso, non accadrà nulla quando viene premuto Backspace e lo strumento rimarrà equipaggiato.
Enabled
La proprietà Abilitata si riferisce se o meno la Tool può essere utilizzata.Questo è utile se vuoi impedire a un giocatore di utilizzare uno strumento, ma non vuoi rimuoverlo dal loro Backpack .
Quando è impostato su true, il giocatore può utilizzare lo strumento.Quando è impostato su false , lo strumento è disabilitato e il giocatore non può usarlo; ciò impedisce che lo strumento venga attivato o disattivato dai metodi Tool:Activate() e Tool:Deactivate() e impedisce che gli eventi Tool.Activated e Tool.Deactivated si attivino.
Campioni di codice
The code sample below creates Tool in the local player's Backpack that increases their JumpPower from 50 to 150 for 5 seconds.
This example uses the tool's Tool.Enabled property as a debounce by setting the property to true when the player jumps and back to false after the 5 second duration.
Unequipping the tool also stops the player from super jumping by changing the JumpPower back to 50.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local tool = Instance.new("Tool")
tool.Name = "SuperJump"
tool.RequiresHandle = false
tool.Parent = player.Backpack
function toolActivated()
humanoid.JumpPower = 150
tool.Enabled = false
task.wait(5)
tool.Enabled = true
humanoid.JumpPower = 50
end
tool.Activated:Connect(toolActivated)
tool.Unequipped:Connect(function()
humanoid.JumpPower = 50
end)
Grip
La proprietà Grip memorizza le proprietà "grip" dello strumento come un singolo CFrame.Queste proprietà posizionano come il giocatore tiene lo strumento e includono GripUp , GripRight , GripForward e GripPos .
Campioni di codice
The code below insert's a Tool named Stick into the local player's Class.BackPack. When the player activates the tool, the code prints the values of the tool's grip properties.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local tool = Instance.new("Tool")
tool.Name = "Stick"
tool.Parent = player.Backpack
local handle = Instance.new("Part")
handle.Name = "Handle"
handle.Parent = tool
handle.Size = Vector3.new(0.1, 3, 0.1)
handle.Color = Color3.fromRGB(108, 88, 75) -- Brown
tool.Activated:Connect(function()
print(tool.Grip)
print(tool.GripUp)
print(tool.GripRight)
print(tool.GripForward)
print(tool.GripPos)
end)
GripForward
Una delle proprietà che specifica l'orientamento di uno strumento nella mano di un personaggio.Questo rappresenta i R02 , R12 e R22 valori della matrice di rotazione dell'impugnatura CFrame .
Altre proprietà degli strumenti che controllano il modo in cui un personaggio tiene uno strumento includono Tool.GripUp , Tool.GripRight e Tool.GripPos .Tutte queste proprietà sono memorizzate in un singolo CFrame nella ProprietàTool.Grip.
Campioni di codice
The code below insert's a Tool named Stick into the local player's Class.BackPack. When the player activates the tool, the code prints the values of the tool's grip properties.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local tool = Instance.new("Tool")
tool.Name = "Stick"
tool.Parent = player.Backpack
local handle = Instance.new("Part")
handle.Name = "Handle"
handle.Parent = tool
handle.Size = Vector3.new(0.1, 3, 0.1)
handle.Color = Color3.fromRGB(108, 88, 75) -- Brown
tool.Activated:Connect(function()
print(tool.Grip)
print(tool.GripUp)
print(tool.GripRight)
print(tool.GripForward)
print(tool.GripPos)
end)
GripPos
Questa proprietà controlla lo spostamento posizionale della matrice di saldatura dello strumento.È una delle diverse proprietà utilizzate per posizionare come il personaggio del giocatore tiene lo strumento.
Altre proprietà che controllano come un personaggio tiene uno strumento includono Tool.GripUp , Tool.GripRight e Tool.GripForward .Tutte queste proprietà sono memorizzate in un singolo CFrame nella ProprietàTool.Grip.
Campioni di codice
The code below insert's a Tool named Stick into the local player's Class.BackPack. When the player activates the tool, the code prints the values of the tool's grip properties.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local tool = Instance.new("Tool")
tool.Name = "Stick"
tool.Parent = player.Backpack
local handle = Instance.new("Part")
handle.Name = "Handle"
handle.Parent = tool
handle.Size = Vector3.new(0.1, 3, 0.1)
handle.Color = Color3.fromRGB(108, 88, 75) -- Brown
tool.Activated:Connect(function()
print(tool.Grip)
print(tool.GripUp)
print(tool.GripRight)
print(tool.GripForward)
print(tool.GripPos)
end)
GripRight
Una delle proprietà che specifica l'orientamento di uno strumento nella mano di un personaggio.Questo rappresenta i R00 , R10 e R20 valori della matrice di rotazione dell'impugnatura CFrame .
Altre proprietà degli strumenti che controllano il modo in cui un personaggio tiene uno strumento includono Tool.GripUp , Tool.GripForward e Tool.GripPos .Tutte queste proprietà sono memorizzate in un singolo CFrame nella ProprietàTool.Grip.
Campioni di codice
The code below insert's a Tool named Stick into the local player's Class.BackPack. When the player activates the tool, the code prints the values of the tool's grip properties.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local tool = Instance.new("Tool")
tool.Name = "Stick"
tool.Parent = player.Backpack
local handle = Instance.new("Part")
handle.Name = "Handle"
handle.Parent = tool
handle.Size = Vector3.new(0.1, 3, 0.1)
handle.Color = Color3.fromRGB(108, 88, 75) -- Brown
tool.Activated:Connect(function()
print(tool.Grip)
print(tool.GripUp)
print(tool.GripRight)
print(tool.GripForward)
print(tool.GripPos)
end)
GripUp
Una delle proprietà che specifica l'orientamento di uno strumento nella mano di un personaggio.Questo rappresenta i R01 , R11 e R21 valori della matrice di rotazione dell'impugnatura CFrame .
Altre proprietà degli strumenti che controllano il modo in cui un personaggio tiene uno strumento includono Tool.GripRight , Tool.GripForward e Tool.GripPos .Tutte queste proprietà sono memorizzate in un singolo CFrame nella ProprietàTool.Grip.
Campioni di codice
The code below insert's a Tool named Stick into the local player's Class.BackPack. When the player activates the tool, the code prints the values of the tool's grip properties.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local tool = Instance.new("Tool")
tool.Name = "Stick"
tool.Parent = player.Backpack
local handle = Instance.new("Part")
handle.Name = "Handle"
handle.Parent = tool
handle.Size = Vector3.new(0.1, 3, 0.1)
handle.Color = Color3.fromRGB(108, 88, 75) -- Brown
tool.Activated:Connect(function()
print(tool.Grip)
print(tool.GripUp)
print(tool.GripRight)
print(tool.GripForward)
print(tool.GripPos)
end)
ManualActivationOnly
La proprietà ManualActivationOnly controlla se il Tool può essere attivato senza eseguire esplicitamente Tool:Activate() in uno script.
Quando è impostato su vero, lo strumento spara solo Tool.Activated quando viene chiamata Tool:Activate(). Questo annulla anche la funzione ContextActionService:BindActivate().
Quando è impostato su false, i clic del mouse (quando lo strumento è equipaggiato) attiveranno anche Tool.Activated .
Campioni di codice
The code sample below creates Tool in the local player's Backpack that increases their WalkSpeed from 16 to 30 for 5 seconds.
This example uses the tool's Tool.ManualActivationOnly property as a debounce by setting the property to true when the player begins sprinting and to false when the player stops sprinting. As a result, when the player is sprinting, the tool cannot be re-activated.
Unequipping the tool also stops the player from sprinting by changing the WalkSpeed to 16.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local tool = Instance.new("Tool")
tool.Name = "Sprint"
tool.RequiresHandle = false
tool.Parent = player:WaitForChild("Backpack")
function toolActivated()
humanoid.WalkSpeed = 30
tool.ManualActivationOnly = true
task.wait(5)
tool.ManualActivationOnly = false
humanoid.WalkSpeed = 16
end
tool.Activated:Connect(toolActivated)
tool.Unequipped:Connect(function()
humanoid.WalkSpeed = 16
end)
RequiresHandle
Questa proprietà determina se una funzione Tool senza gestire.
Uno strumento ha una maniglia quando contiene una parte figlia chiamata Maniglia .Gli strumenti con maniglie richiedono di solito che il giocatore li equipaggi per mantenere un oggetto per usarli, ad esempio le armi.Gli strumenti senza maniglie di solito non richiedono che il giocatore li equipaggi per mantenere qualcosa per usarli, ad esempio strumenti "fly" o "summon".
Quando è impostato su true , lo strumento funzionerà solo con una gestire. Quando è impostato su false , lo strumento funzionerà anche senza gestire.
ToolTip
La proprietà ToolTip controlla il messaggio che verrà visualizzato quando il GiocatoreMouse passa il mouse su Tool nella loro Backpack .
Generalmente, il valore di questa proprietà dovrebbe descrivere ciò che lo strumento è o il suo uso.Ad esempio, per uno strumento di pala, puoi scegliere di impostare il ToolTip a:
tool.ToolTip = "Shovel"
or
tool.ToolTip = "Use to dig"
or
tool.ToolTip = "Shovel - Use to dig"
Metodi
Activate
Questa funzione simula l'attivazione del Tool . Lo strumento deve essere equipaggiato perché questa funzione funzioni.
Restituzioni
Campioni di codice
The code below creates a Tool in the local player's Backpack that turns the player invisible when activated and visible when deactivated.
When equipped, the script simulates the tool being activated and turns the player invisible for 3 seconds and then simulates the tool being deactivated. Holding the left mouse button down turns the player invisible for up to 3 seconds, with a cooldown period of 1 second, or until the player releases their left mouse button.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character
local tool = Instance.new("Tool")
tool.Name = "Invisibility Tool"
tool.RequiresHandle = false
tool.Parent = player.Backpack
local invisible = false
local function toolActivated()
if invisible then
return
end
invisible = true
for _, bodypart in pairs(character:GetChildren()) do
if bodypart:IsA("MeshPart") or bodypart:IsA("Part") then
bodypart.Transparency = 1
end
end
task.wait(3)
tool:Deactivate()
task.wait(1)
invisible = false
end
local function toolDeactivated()
if not invisible then
return
end
for _, bodypart in pairs(character:GetChildren()) do
if bodypart.Name ~= "HumanoidRootPart" then
if bodypart:IsA("MeshPart") or bodypart:IsA("Part") then
bodypart.Transparency = 0
end
end
end
end
local function toolEquipped()
tool:Activate()
end
tool.Equipped:Connect(toolEquipped)
tool.Activated:Connect(toolActivated)
tool.Deactivated:Connect(toolDeactivated)
tool.Unequipped:Connect(toolDeactivated)
Deactivate
Questa funzione simula la disattivazione del Tool . Lo strumento deve essere equipaggiato perché questa funzione funzioni.
Restituzioni
Campioni di codice
The code below creates a Tool in the local player's Backpack that turns the player invisible when activated and visible when deactivated.
When equipped, the script simulates the tool being activated and turns the player invisible for 3 seconds and then simulates the tool being deactivated. Holding the left mouse button down turns the player invisible for up to 3 seconds, with a cooldown period of 1 second, or until the player releases their left mouse button.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character
local tool = Instance.new("Tool")
tool.Name = "Invisibility Tool"
tool.RequiresHandle = false
tool.Parent = player.Backpack
local invisible = false
local function toolActivated()
if invisible then
return
end
invisible = true
for _, bodypart in pairs(character:GetChildren()) do
if bodypart:IsA("MeshPart") or bodypart:IsA("Part") then
bodypart.Transparency = 1
end
end
task.wait(3)
tool:Deactivate()
task.wait(1)
invisible = false
end
local function toolDeactivated()
if not invisible then
return
end
for _, bodypart in pairs(character:GetChildren()) do
if bodypart.Name ~= "HumanoidRootPart" then
if bodypart:IsA("MeshPart") or bodypart:IsA("Part") then
bodypart.Transparency = 0
end
end
end
end
local function toolEquipped()
tool:Activate()
end
tool.Equipped:Connect(toolEquipped)
tool.Activated:Connect(toolActivated)
tool.Deactivated:Connect(toolDeactivated)
tool.Unequipped:Connect(toolDeactivated)
Eventi
Activated
Questo evento si attiva quando il giocatore fa clic mentre il Tool è equipaggiato.Non è non sparato se la chiave Ctrl viene premuta durante il clic.
Questo evento viene tipicamente utilizzato per eseguire un'azione quando il giocatore utilizza lo strumento, ad esempio per lanciare un razzo da un'arma lanciatore di razzi.
Il codice seguente, quando viene posizionato in un LocalScript , crea uno strumento nel Giocatorelocale Backpack e stampa "Strumento attivato" quando il giocatore fa clic mentre lo strumento creato è equipaggiato.
local Players = game:GetService("Players")
local tool = Instance.new("Tool")
tool.RequiresHandle = false
tool.Parent = Players.LocalPlayer.Backpack
function onActivation()
print("Tool activated")
end
tool.Activated:Connect(onActivation)
Deactivated
Questo evento si attiva quando il giocatore rilascia il clic mentre il Tool è equipaggiato e attivato.Viene tipicamente utilizzato per eseguire un'azione quando il giocatore smette di utilizzare uno strumento.
Il codice seguente, quando viene posizionato in un LocalScript, crea uno strumento nel Giocatorelocale Backpack e stampa "Strumento disattivato" quando il giocatore rilascia il clic mentre lo strumento è equipaggiato e attivato.
local Players = game:GetService("Players")
local tool = Instance.new("Tool")
tool.RequiresHandle = false
tool.Parent = Players.LocalPlayer.Backpack
function toolDeactivated()
print("Tool deactivated")
end
tool.Deactivated:Connect(toolDeactivated)
Equipped
Questo evento si attiva quando un giocatore equipaggia il Tool (lo toglie dal loro Backpack ).
L'opposto di questo evento, Tool.Unequipped , può essere utilizzato per determinare quando il giocatore disequipaggia lo strumento mettendolo nel suo zaino.
Nota che questo evento non fa fuoco quando Tool.RequiresHandle è abilitato e non è presente alcun handle.
Parametri
Il Topo, or mouse as computer mousedel Giocatore.
Campioni di codice
The example shown below will print "A tool was equipped" each time the tool is equipped by the player. Please note that the below example assumes that you've already defined what "Tool" is.
local Tool = script.Parent
local function onEquipped(_mouse)
print("The tool was equipped")
end
Tool.Equipped:Connect(onEquipped)
Unequipped
Questo evento si attiva quando un giocatore disequipaggia il Tool (lo mette nel loro Backpack ).
L'opposto di questo evento, Tool.Equipped , può essere utilizzato per determinare quando il giocatore equipaggia lo strumento estraendolo dal suo zaino.
Nota che questo evento non fa fuoco quando Tool.RequiresHandle è abilitato e non è presente alcun handle.