AnimationTrack
*Questo contenuto è tradotto usando AI (Beta) e potrebbe contenere errori. Per visualizzare questa pagina in inglese, clicca qui.
Controlla il riproduzione di un'animazione su un Animator . Questo oggetto non può essere creato, invece viene restituito dal metodo Animator:LoadAnimation().
Sommario
Proprietà
L'oggetto Animation che è stato utilizzato per creare questo AnimationTrack .
Una proprietà solo lettura che restituisce vero quando il AnimationTrack sta giocando.
Una proprietà solo lettura che restituisce la lunghezza (in secondi) di un AnimationTrack .Questo restituirà 0 fino a quando l'animazione non sarà completamente caricata e quindi potrebbe non essere immediatamente disponibile.
Imposta se l'animazione si ripeterà dopo aver finito. Se viene cambiata durante il gioco, l'animazione avrà effetto dopo che l'animazione finisce.
Imposta la priorità di un AnimationTrack .A seconda di ciò che è impostato, giocare a più animazioni contemporaneamente cercherà questa proprietà per capire quale Class.Keyframe``Class.Pose|Poses deve essere riprodotta sull'un l'altra.
La velocità di un AnimationTrack è una proprietà di lettura solo che dà la velocità di riproduzione attuale del AnimationTrack .Questo ha un valore predefinito di 1.Quando la velocità è uguale a 1, la quantità di tempo che un'animazione richiede per completarsi è uguale a AnimationTrack.Length (in secondi).
Restituisce la posizione nel tempo in secondi in cui un AnimationTrack è attraverso il riproduzione della sua animazionidi origine.Può essere impostato per far saltare la traccia a un momento specifico nell'animazioni.
Proprietà read-only che fornisce il peso attuale del AnimationTrack . Ha un valore predefinito di 1.
Proprietà read-only che fornisce il peso attuale del AnimationTrack .
Metodi
Cambia il AnimationTrack.Speed di un'animazioni. Un valore positivo per la velocità riproduce l'animazione in avanti, uno negativo la riproduce all'indietro e 0 la ferma.
Cambia il peso di un'animazioni, con il parametro fadeTime opzionale che determina quanto tempo ci vuole per AnimationTrack.WeightCurrent raggiungere AnimationTrack.WeightTarget .
Restituisce un event che si attiva quando un KeyframeMarker specificato è stato colpito in un animation .
Restituisce la posizione temporale del primo Keyframe del nome dato in un AnimationTrack .
Riproduce il AnimationTrack . Una volta chiamato un AnimationTrack riproducirà con il tempo di dissolvenza, il peso e la velocità specificati.
Ferma il AnimationTrack .
Eventi
Si accende quando un AnimationTrack loop sull'aggiornamento successivo segue la fine del precedente ciclo di animazione.
Si accende quando il AnimationTrack è completamente finito di spostare qualsiasi cosa nel Mondo.L'animazione ha finito di giocare, il "fade out" è finito e il soggetto è in una posa neutra.
Si attiva ogni volta che il riproduzione di un AnimationTrack raggiunge un Keyframe che non ha il nome predefinito - "Keyframe".
Si accende quando il AnimationTrack finisce di giocare.La traccia di animazione potrebbe ancora animare il soggetto mentre l'animazione "scompare".Per catturare quando l'AnimationTrack è completamente finito di spostare qualsiasi cosa nel Mondo, usa l'evento AnimationTrack.Ended.
Proprietà
Animation
L'oggetto Animation che è stato utilizzato per creare questo AnimationTrack .Per creare un AnimationTrack , devi caricare un oggetto Animation su un Animator utilizzando il metodo Animator:LoadAnimation().
Campioni di codice
The following code sample prints the name of an animation whenever an AnimationTrack plays on a Humanoid. This script can be placed in a model with a Humanoid child.
local humanoid = script.Parent:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
animator.AnimationPlayed:Connect(function(animationTrack)
local animationName = animationTrack.Animation.Name
print("Animation playing " .. animationName)
end)
IsPlaying
Una proprietà solo lettura che restituisce vero quando il AnimationTrack sta giocando.
Questa proprietà può essere utilizzata dagli sviluppatori per controllare se un'animazione è già in riproduzione prima di giocarci (in quanto ciò potrebbe causare il suo Ricomincia).Se uno sviluppatore desidera ottenere tutto il gioco AnimationTracks su un Animator o un Humanoid , dovrebbe usare Animator:GetPlayingAnimationTracks()
Campioni di codice
This code sample includes a simple function that will play an AnimationTrack if it is not playing, or otherwise adjust its speed and weight to match the new parameters given.
local function playOrAdjust(animationTrack, fadeTime, weight, speed)
if not animationTrack.IsPlaying then
animationTrack:Play(fadeTime, weight, speed)
else
animationTrack:AdjustSpeed(speed)
animationTrack:AdjustWeight(weight, fadeTime)
end
end
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://507765644"
local humanoid = script.Parent:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animationTrack = animator:LoadAnimation(animation)
playOrAdjust(animationTrack, 1, 0.6, 1)
Length
Una proprietà solo lettura che restituisce la lunghezza (in secondi) di un AnimationTrack .Questo restituirà 0 fino a quando l'animazione non sarà completamente caricata e quindi potrebbe non essere immediatamente disponibile.
Quando il AnimationTrack.Speed di un AnimationTrack è uguale a 1, l'animazione richiederà AnimationTrack.Length (in secondi) per completarsi.
Campioni di codice
The following function will play an AnimationTrack for a specific duration. This is done by changing the speed of the animation to the length of the animation divided by the desired playback duration. This could be used in situations where a developer wants to play a standard animation for different duration (for example, recharging different abilities).
local function playAnimationForDuration(animationTrack, duration)
local speed = animationTrack.Length / duration
animationTrack:Play()
animationTrack:AdjustSpeed(speed)
end
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://507765000"
local humanoid = script.Parent:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animationTrack = animator:LoadAnimation(animation)
playAnimationForDuration(animationTrack, 3)
Looped
Questa proprietà imposta se l'animazione si ripeterà dopo aver finito.Se viene cambiato durante il gioco, il risultato avrà effetto dopo che l'animazione finisce.
La proprietà Looped per AnimationTrack predefinisce il modo in cui è stata impostata nell'editor di animazione.Tuttavia, questa proprietà può essere cambiata, consentendo il controllo su AnimationTrack mentre il gioco è in esecuzione.Looped gestisce anche correttamente le animazioni riprodotte all'indietro (negativo AnimationTrack.Speed ).Dopo che viene raggiunto il primo keyframe, verrà riavviato all'ultimo Fotogramma chiave.
Questa proprietà consente allo sviluppatore di avere una variante di loop e non di loop dell'animazionistessa, senza dover caricare due versioni su Roblox.
Campioni di codice
The animation in this example normally loops. After the player and the animation are loaded the animation is played in a non-looped fashion then in a looped fashion.
local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
while not localPlayer.Character do
task.wait()
end
local character = localPlayer.Character
local humanoid = character:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://507770453"
local animationTrack = animator:LoadAnimation(animation)
animationTrack.Looped = false
task.wait(3)
animationTrack:Play()
task.wait(4)
animationTrack.Looped = true
animationTrack:Play()
The function in this code sample will play an AnimationTrack on a loop, for a specific number of loops, before stopping the animation.
In some cases the developer may want to stop a looped animation after a certain number of loops have completed, rather than after a certain amount of time. This is where the DidLoop event can be used.
local function playForNumberLoops(animationTrack, number)
animationTrack.Looped = true
animationTrack:Play()
local numberOfLoops = 0
local connection = nil
connection = animationTrack.DidLoop:Connect(function()
numberOfLoops = numberOfLoops + 1
print("loop: ", numberOfLoops)
if numberOfLoops >= number then
animationTrack:Stop()
connection:Disconnect() -- it's important to disconnect connections when they are no longer needed
end
end)
end
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://507765644"
local humanoid = script.Parent:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animationTrack = animator:LoadAnimation(animation)
playForNumberLoops(animationTrack, 5)
Priority
Questa proprietà imposta la priorità di un AnimationTrack .A seconda di ciò che è impostato, giocare a più animazioni contemporaneamente cercherà questa proprietà per capire quale Class.Keyframe``Class.Pose|Poses deve essere riprodotta sull'un l'altra.
La proprietà Priorità per AnimationTrack predefinisce come è stata impostata e pubblicata dall'Editor di Animazione di Studio.Usa Enum.AnimationPriority che ha 7 livelli di priorità:
- Action4 (priorità più alta)
- Azione3
- Azione2
- Azione
- Movimento
- Inattivo
- Core (priorità più bassa)
Impostare correttamente le priorità di animazione, attraverso l'editor o attraverso questa Proprietà, consente di far giocare più animazioni senza che si scontrino.Dove due animazioni di gioco dirigono il bersaglio a muovere la stessa artiglia in modi diversi, la AnimationTrack con la priorità più alta Mostrare.Se entrambe le animazioni hanno la stessa priorità, verranno utilizzati i pesi delle tracce per combinare le animazioni.
Questa proprietà consente inoltre al developer di riprodurre la stessa animazione a diverse priorità, senza dover caricare versioni aggiuntive su Roblox.
Speed
La velocità di un AnimationTrack è una proprietà di lettura solo che dà la velocità di riproduzione attuale del AnimationTrack .Questo ha un valore predefinito di 1.Quando la velocità è uguale a 1, la quantità di tempo che un'animazione richiede per completarsi è uguale a AnimationTrack.Length (in secondi).
Se la velocità viene regolata, poi il tempo effettivo che ci vorrà per giocare una traccia può essere calcolato dividendo la lunghezza per la velocità.La velocità è una quantità senza unità.
La velocità può essere utilizzata per collegare la lunghezza di un'animazione a diversi eventi di gioco (ad esempio ricaricare un'abilità) senza dover caricare diverse varianti della stessa animazioni.
Questa proprietà è solo letta e puoi cambiarla usando AnimationTrack:AdjustSpeed() .
Campioni di codice
In this example a player and an animation is loaded. The Length of an AnimationTrack determines how long the track would take to play if the speed is at 1. If the speed is adjusted, then the actual time it will take a track to play can be computed by dividing the length by the speed.
local ContentProvider = game:GetService("ContentProvider")
local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
while not localPlayer.Character do
task.wait()
end
local character = localPlayer.Character
local humanoid = character:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://507770453"
ContentProvider:PreloadAsync({ animation })
local animationTrack = animator:LoadAnimation(animation)
local normalSpeedTime = animationTrack.Length / animationTrack.Speed
animationTrack:AdjustSpeed(3)
local fastSpeedTime = animationTrack.Length / animationTrack.Speed
print("At normal speed the animation will play for", normalSpeedTime, "seconds")
print("At 3x speed the animation will play for", fastSpeedTime, "seconds")
The following function will play an AnimationTrack for a specific duration. This is done by changing the speed of the animation to the length of the animation divided by the desired playback duration. This could be used in situations where a developer wants to play a standard animation for different duration (for example, recharging different abilities).
local function playAnimationForDuration(animationTrack, duration)
local speed = animationTrack.Length / duration
animationTrack:Play()
animationTrack:AdjustSpeed(speed)
end
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://507765000"
local humanoid = script.Parent:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animationTrack = animator:LoadAnimation(animation)
playAnimationForDuration(animationTrack, 3)
TimePosition
Restituisce la posizione nel tempo in secondi in cui un AnimationTrack è attraverso il riproduzione della sua animazionidi origine.Può essere impostato per far saltare la traccia a un momento specifico nell'animazioni.
La posizione temporale può essere impostata per andare a un punto specifico nell'animazioni, ma il AnimationTrack deve essere in riproduzione per farlo.Può essere utilizzato anche in combinazione con AnimationTrack:AdjustSpeed() per congelare l'animazione a un punto desiderato (impostando la velocità a 0).
Campioni di codice
The following code sample includes two functions that demonstrate how AdjustSpeed and TimePosition can be used to freeze an animation at a particular point.
The first function freezes an animation at a particular point in time (defined in seconds). The second freezes at it at a percentage (between 0 or 100) by multiplying the percentage by the track length.
As TimePosition can not be used when an AnimationTrack is not playing, the functions check to make sure the animation is playing before proceeding.
function freezeAnimationAtTime(animationTrack, timePosition)
if not animationTrack.IsPlaying then
-- Play the animation if it is not playing
animationTrack:Play()
end
-- Set the speed to 0 to freeze the animation
animationTrack:AdjustSpeed(0)
-- Jump to the desired TimePosition
animationTrack.TimePosition = timePosition
end
function freezeAnimationAtPercent(animationTrack, percentagePosition)
if not animationTrack.IsPlaying then
-- Play the animation if it is not playing
animationTrack:Play()
end
-- Set the speed to 0 to freeze the animation
animationTrack:AdjustSpeed(0)
-- Jump to the desired TimePosition
animationTrack.TimePosition = (percentagePosition / 100) * animationTrack.Length
end
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://507765644"
local humanoid = script.Parent:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animationTrack = animator:LoadAnimation(animation)
freezeAnimationAtTime(animationTrack, 0.5)
freezeAnimationAtPercent(animationTrack, 50)
WeightCurrent
Quando il peso viene impostato in un AnimationTrack non cambia istantaneamente ma si sposta da WeightCurrent a AnimationTrack.WeightTarget .Il tempo necessario per farlo è determinato dal parametro fadeTime dato quando l'animazione viene riprodotta o il peso viene regolato.
WeightCurrent può essere controllato contro AnimationTrack.WeightTarget per vedere se il peso desiderato è stato raggiunto.Si noti che questi valori non devono essere controllati per l'uguaglianza con l'operatore ==, poiché entrambi questi valori sono float.Per vedere se WeightCurrent ha raggiunto il peso target, si consiglia di vedere se la distanza tra quei valori è sufficientemente piccola (vedi esempio di codice qui sotto).
Il sistema di bilanciamento dell'animazione viene utilizzato per determinare come AnimationTracks giocare con la stessa priorità vengono mescolati insieme.Il peso predefinito è uno e nessun movimento sarà visibile su un AnimationTrack con un peso di zero.La posa che viene mostrata in qualsiasi momento è determinata dalla media ponderata di tutti i Poses e dal PesoAttuale di ciascuno AnimationTrack .Nella maggior parte dei casi, le animazioni di fusione non sono richieste e l'utilizzo di AnimationTrack.Priority è più adatto.
Campioni di codice
This code sample loads two animations onto the local player's Humanoid and demonstrates how the fadeTime paramater in AnimationTrack.Play determines how long it takes for an AnimationTrack's WeightCurrent to reach it's WeightTarget.
As WeightCurrent and WeightTarget are floats the == operator cannot be used to compare, instead it is more appropriate to check that the difference between them is sufficiently small to assume the weight fade has completed.
local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
while not localPlayer.Character do
task.wait()
end
local character = localPlayer.Character
local humanoid = character:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animation1 = Instance.new("Animation")
animation1.AnimationId = "rbxassetid://507770453"
local animation2 = Instance.new("Animation")
animation2.AnimationId = "rbxassetid://507771019"
task.wait(3) -- arbitrary wait time to allow the character to fall into place
local animationTrack1 = animator:LoadAnimation(animation1)
local animationTrack2 = animator:LoadAnimation(animation2)
animationTrack1.Priority = Enum.AnimationPriority.Movement
animationTrack2.Priority = Enum.AnimationPriority.Action
animationTrack1:Play(0.1, 5, 1)
animationTrack2:Play(10, 3, 1)
local done = false
while not done and task.wait(0.1) do
if math.abs(animationTrack2.WeightCurrent - animationTrack2.WeightTarget) < 0.001 then
print("got there")
done = true
end
end
WeightTarget
AnimationTrack.WeightTarget è una proprietà read-only che fornisce il peso attuale del AnimationTrack .Ha un valore predefinito di 1 e viene impostato quando AnimationTrack:Play() , AnimationTrack:Stop() o AnimationTrack:AdjustWeight() viene chiamato.Quando il peso viene impostato in un AnimationTrack non cambia istantaneamente ma si sposta da WeightCurrent a AnimationTrack.WeightTarget.Il tempo necessario per farlo è determinato dal parametro fadeTime dato quando l'animazione viene riprodotta o il peso viene regolato.
WeightCurrent può essere controllato contro AnimationTrack.WeightTarget per vedere se il peso desiderato è stato raggiunto.Si noti che questi valori non devono essere controllati per l'uguaglianza con l'operatore ==, poiché entrambi questi valori sono float.Per vedere se WeightCurrent ha raggiunto il peso target, si consiglia di vedere se la distanza tra quei valori è sufficientemente piccola (vedi esempio di codice qui sotto).
Il sistema di bilanciamento dell'animazione viene utilizzato per determinare come AnimationTracks giocare con la stessa priorità vengono mescolati insieme.Il peso predefinito è uno e nessun movimento sarà visibile su un AnimationTrack con un peso di zero.La posa che viene mostrata in qualsiasi momento è determinata dalla media ponderata di tutti i Poses e dal PesoAttuale di ciascuno AnimationTrack .Nella maggior parte dei casi, le animazioni di fusione non sono richieste e l'utilizzo di AnimationTrack.Priority è più adatto.
Campioni di codice
This code sample loads two animations onto the local player's Humanoid and demonstrates how the fadeTime paramater in AnimationTrack.Play determines how long it takes for an AnimationTrack's WeightCurrent to reach it's WeightTarget.
As WeightCurrent and WeightTarget are floats the == operator cannot be used to compare, instead it is more appropriate to check that the difference between them is sufficiently small to assume the weight fade has completed.
local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
while not localPlayer.Character do
task.wait()
end
local character = localPlayer.Character
local humanoid = character:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animation1 = Instance.new("Animation")
animation1.AnimationId = "rbxassetid://507770453"
local animation2 = Instance.new("Animation")
animation2.AnimationId = "rbxassetid://507771019"
task.wait(3) -- arbitrary wait time to allow the character to fall into place
local animationTrack1 = animator:LoadAnimation(animation1)
local animationTrack2 = animator:LoadAnimation(animation2)
animationTrack1.Priority = Enum.AnimationPriority.Movement
animationTrack2.Priority = Enum.AnimationPriority.Action
animationTrack1:Play(0.1, 5, 1)
animationTrack2:Play(10, 3, 1)
local done = false
while not done and task.wait(0.1) do
if math.abs(animationTrack2.WeightCurrent - animationTrack2.WeightTarget) < 0.001 then
print("got there")
done = true
end
end
Metodi
AdjustSpeed
Questa funzione cambia il AnimationTrack.Speed di un'animazioni.Un valore positivo per la velocità riproduce l'animazione in avanti, uno negativo la riproduce all'indietro e 0 la interrompe.
La velocità iniziale di un AnimationTrack viene impostata come parametro in AnimationTrack:Play() .Tuttavia, la velocità di una traccia può essere cambiata durante la riproduzione, utilizzando AdjustSpeed.Quando la velocità è uguale a 1, la quantità di tempo che un'animazione richiede per completarsi è uguale a AnimationTrack.Length (in secondi).
Quando viene aggiustato, poi il tempo effettivo che ci vorrà per giocare una traccia può essere calcolato dividendo la lunghezza per la velocità. La velocità è una quantità senza unità.
La velocità può essere utilizzata per collegare la lunghezza di un'animazione a diversi eventi di gioco (ad esempio ricaricare un'abilità) senza dover caricare diverse varianti della stessa animazioni.
Parametri
La velocità di riproduzione dell'animazione deve essere cambiata.
Restituzioni
Campioni di codice
The following function will play an AnimationTrack for a specific duration. This is done by changing the speed of the animation to the length of the animation divided by the desired playback duration. This could be used in situations where a developer wants to play a standard animation for different duration (for example, recharging different abilities).
local function playAnimationForDuration(animationTrack, duration)
local speed = animationTrack.Length / duration
animationTrack:Play()
animationTrack:AdjustSpeed(speed)
end
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://507765000"
local humanoid = script.Parent:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animationTrack = animator:LoadAnimation(animation)
playAnimationForDuration(animationTrack, 3)
In this example a player and an animation is loaded. The Length of an AnimationTrack determines how long the track would take to play if the speed is at 1. If the speed is adjusted, then the actual time it will take a track to play can be computed by dividing the length by the speed.
local ContentProvider = game:GetService("ContentProvider")
local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
while not localPlayer.Character do
task.wait()
end
local character = localPlayer.Character
local humanoid = character:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://507770453"
ContentProvider:PreloadAsync({ animation })
local animationTrack = animator:LoadAnimation(animation)
local normalSpeedTime = animationTrack.Length / animationTrack.Speed
animationTrack:AdjustSpeed(3)
local fastSpeedTime = animationTrack.Length / animationTrack.Speed
print("At normal speed the animation will play for", normalSpeedTime, "seconds")
print("At 3x speed the animation will play for", fastSpeedTime, "seconds")
AdjustWeight
Cambia il peso di un'animazioni, con il parametro fadeTime opzionale che determina quanto tempo ci vuole per AnimationTrack.WeightCurrent raggiungere AnimationTrack.WeightTarget .
Quando il peso viene impostato in un AnimationTrack non cambia istantaneamente ma si sposta da WeightCurrent a AnimationTrack.WeightTarget .Il tempo necessario per farlo è determinato dal parametro fadeTime dato quando l'animazione viene riprodotta o il peso viene regolato.
WeightCurrent può essere controllato contro AnimationTrack.WeightTarget per vedere se il peso desiderato è stato raggiunto.Si noti che questi valori non devono essere controllati per l'uguaglianza con l'operatore ==, poiché entrambi questi valori sono float.Per vedere se WeightCurrent ha raggiunto il peso target, si consiglia di vedere se la distanza tra quei valori è sufficientemente piccola (vedi esempio di codice qui sotto).
Il sistema di bilanciamento dell'animazione viene utilizzato per determinare come AnimationTracks giocare con la stessa priorità vengono mescolati insieme.Il peso predefinito è uno e nessun movimento sarà visibile su un AnimationTrack con un peso di zero.La posa che viene mostrata in qualsiasi momento è determinata dalla media ponderata di tutti i Poses e dal PesoAttuale di ciascuno AnimationTrack .Vedi qui sotto per un esempio di fusione di animazione in pratica.Nella maggior parte dei casi, le animazioni di fusione non sono richieste e l'utilizzo di AnimationTrack.Priority è più adatto.
Parametri
Il peso che l'animazione deve essere cambiato.
La durata del tempo in cui l'animazione scomparirà tra il vecchio peso e il nuovo peso per.
Restituzioni
Campioni di codice
This code sample includes a function that changes the weight of an AnimationTrack and yields until the weight has changed to the new target weight.
The purpose of this sample is to demonstrate how the fadeTime parameter of AnimationTrack.AdjustWeight works. In most cases, if a developer wishes to yield over the fadeTime it is recommended they use wait(fadeTime).
local function changeWeight(animationTrack, weight, fadeTime)
animationTrack:AdjustWeight(weight, fadeTime)
local startTime = tick()
while math.abs(animationTrack.WeightCurrent - weight) > 0.001 do
task.wait()
end
print("Time taken to change weight " .. tostring(tick() - startTime))
end
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://507765644"
local humanoid = script.Parent:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animationTrack = animator:LoadAnimation(animation)
changeWeight(animationTrack, 0.6, 1)
GetMarkerReachedSignal
Questa funzione restituisce un event simile all'evento AnimationTrack.KeyframeReached, ma si attiva solo quando un KeyframeMarker specificato viene colpito in un animation .La differenza consente un maggiore controllo su quando l'evento verrà Lanciare.
Per saperne di più sull'utilizzo di questa funzione, vedi Eventi di animazione nell'articolo Editor di animazione.
Vedi anche:
Parametri
Il nome del segnale KeyframeMarker viene creato per. Non confondersi con il nome del Keyframe .
Restituzioni
Il segnale creato e sparato quando l'animazione raggiunge il creato KeyframeMarker . Non confondersi con il nome del Keyframe .
Campioni di codice
This LocalScript code waits for the local player's Humanoid object to load, then it creates a new Animation instance with the proper Animation.AnimationId. The animation is then loaded onto the humanoid, creating an AnimationTrack, and the track is played with AnimationTrack:Play(). Following that, the AnimationTrack:GetMarkerReachedSignal() function detects when the "KickEnd" marker is hit.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.Character:Wait()
local humanoid = character:WaitForChild("Humanoid")
-- Create new "Animation" instance
local kickAnimation = Instance.new("Animation")
-- Set its "AnimationId" to the corresponding animation asset ID
kickAnimation.AnimationId = "rbxassetid://2515090838"
-- Load animation onto the humanoid
local kickAnimationTrack = humanoid:LoadAnimation(kickAnimation)
-- Play animation track
kickAnimationTrack:Play()
-- If a named event was defined for the animation, connect it to "GetMarkerReachedSignal()"
kickAnimationTrack:GetMarkerReachedSignal("KickEnd"):Connect(function(paramString)
print(paramString)
end)
GetTimeOfKeyframe
Restituisce la posizione temporale del primo Keyframe del nome dato in un AnimationTrack .Se più Keyframes condividono lo stesso nome, restituirà l'animazionipiù antica.
Questa funzione restituirà un errore se viene utilizzata con un nome di keyframe non valido (uno che non esiste ad esempio) o se il sottostante Animation non è ancora stato caricato.Per affrontare questo assicurati di utilizzare solo nomi di keyframe corretti e l'animazione sia stata caricata prima di chiamare questa funzione.
Per controllare se l'animazione è stata caricata, verifica che il AnimationTrack.Length è maggiore di zero.
Parametri
Restituzioni
Campioni di codice
This sample includes a function that will jump to the first keyframe of a specified name in an AnimationTrack.
As AnimationTrack.TimePosition cannot be set while the animation is not playing the function first checks to see if the animation is playing.
This sample will only work once an Animation has loaded.
local function jumpToKeyframe(animationTrack, keyframeName)
local timePosition = animationTrack:GetTimeOfKeyframe(keyframeName)
if not animationTrack.IsPlaying then
animationTrack:Play()
end
animationTrack.TimePosition = timePosition
end
local ANIMATION_ID = 0
local KEYFRAME_NAME = "Test"
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://" .. ANIMATION_ID
local humanoid = script.Parent:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animationTrack = animator:LoadAnimation(animation)
jumpToKeyframe(animationTrack, KEYFRAME_NAME)
Play
Quando AnimationTrack:Play() viene chiamata l'animazione della traccia inizierà a giocare e il peso dell'animazione aumenterà da 0 a quello specificato (predefinito 1) durante il tempo di transizione specificato (predefinito 0.1).
La velocità a cui il AnimationTrack giocherà è determinata dal parametro di velocità (predefinito 1).Quando la velocità è uguale a 1 il numero di secondi che la traccia impiegherà per completarsi è uguale alla Proprietàdella traccia AnimationTrack.Length .Ad esempio, una velocità di 2 farà giocare alla traccia due volte più velocemente.
Il peso e la velocità dell'animazione possono anche essere modificati dopo che l'animazione ha iniziato a giocare utilizzando i metodi AnimationTrack:AdjustWeight() e AnimationTrack:AdjustSpeed().
Se lo sviluppatore vuole avviare l'animazione a un punto specifico utilizzando AnimationTrack.TimePosition, è importante che l'animazione venga riprodotta prima che ciò sia fatto.
Parametri
La durata del tempo in cui il peso dell'animazionidovrebbe essere sbiadito.
Il peso dell'animazione da riprodurre.
La velocità di riproduzione dell'animazioni.
Restituzioni
Campioni di codice
The following function will play an AnimationTrack for a specific duration. This is done by changing the speed of the animation to the length of the animation divided by the desired playback duration. This could be used in situations where a developer wants to play a standard animation for different duration (for example, recharging different abilities).
local function playAnimationForDuration(animationTrack, duration)
local speed = animationTrack.Length / duration
animationTrack:Play()
animationTrack:AdjustSpeed(speed)
end
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://507765000"
local humanoid = script.Parent:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animationTrack = animator:LoadAnimation(animation)
playAnimationForDuration(animationTrack, 3)
The following code sample includes two functions that demonstrate how AdjustSpeed and TimePosition can be used to freeze an animation at a particular point.
The first function freezes an animation at a particular point in time (defined in seconds). The second freezes at it at a percentage (between 0 or 100) by multiplying the percentage by the track length.
As TimePosition can not be used when an AnimationTrack is not playing, the functions check to make sure the animation is playing before proceeding.
function freezeAnimationAtTime(animationTrack, timePosition)
if not animationTrack.IsPlaying then
-- Play the animation if it is not playing
animationTrack:Play()
end
-- Set the speed to 0 to freeze the animation
animationTrack:AdjustSpeed(0)
-- Jump to the desired TimePosition
animationTrack.TimePosition = timePosition
end
function freezeAnimationAtPercent(animationTrack, percentagePosition)
if not animationTrack.IsPlaying then
-- Play the animation if it is not playing
animationTrack:Play()
end
-- Set the speed to 0 to freeze the animation
animationTrack:AdjustSpeed(0)
-- Jump to the desired TimePosition
animationTrack.TimePosition = (percentagePosition / 100) * animationTrack.Length
end
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://507765644"
local humanoid = script.Parent:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animationTrack = animator:LoadAnimation(animation)
freezeAnimationAtTime(animationTrack, 0.5)
freezeAnimationAtPercent(animationTrack, 50)
SetTargetInstance
Parametri
Restituzioni
Stop
Ferma il AnimationTrack .Una volta chiamata, il peso dell'animazione si sposterà verso lo zero nel corso di un periodo di tempo specificato dal parametro opzionale fadeTime.Ad esempio, se Stop() viene chiamato con un fadeTime di 2 , ci vorranno due secondi per raggiungere lo zero del peso della traccia e i suoi effetti Terminarecompletamente.Si prega di notare che questo sarà il caso indipendentemente dal peso iniziale dell'animazioni.
Non è consigliato utilizzare un fadeTime di 0 in un tentativo di annullare questo effetto e terminare l'animazione immediatamente per Motor6Ds che hanno il loro Motor.MaxVelocity impostato a zero, poiché ciò causa il congelamento delle articolazioni in Posto.Se deve terminare immediatamente, assicurati che il Motor.MaxVelocity di Motor6Ds nel tuo rig sia abbastanza alto per garantire loro uno scatto adeguato.
Parametri
Il tempo, in secondi, per cui il peso dell'animazione deve essere dissipato.
Restituzioni
Campioni di codice
This code sample includes a function that stops an AnimationTrack with a specific fadeTime, and yields until the fade is completed and the weight of the AnimationTrack is equal to zero.
The purpose of this sample is to demonstrate how the fadeTime parameter of AnimationTrack.Stop works. In most cases, if a developer wishes to yield over the fadeTime it is recommended they use wait(fadeTime).
local function fadeOut(animationTrack, fadeTime)
animationTrack:Stop(fadeTime)
local startTime = tick()
while animationTrack.WeightCurrent > 0 do
task.wait()
end
local timeTaken = tick() - startTime
print("Time taken for weight to reset: " .. tostring(timeTaken))
end
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://507765644"
local humanoid = script.Parent:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animationTrack = animator:LoadAnimation(animation)
animationTrack:Play()
fadeOut(animationTrack, 1)
Eventi
DidLoop
Questo evento si attiva ogni volta che un ciclo AnimationTrack completa un ciclo, nell'Aggiornarmentosuccessivo.
Attualmente può anche sparare alla fine esatta di una traccia di animazione non loopata ma questo comportamento non dovrebbe essere affidato.
Campioni di codice
The function in this code sample will play an AnimationTrack on a loop, for a specific number of loops, before stopping the animation.
In some cases the developer may want to stop a looped animation after a certain number of loops have completed, rather than after a certain amount of time. This is where the DidLoop event can be used.
local function playForNumberLoops(animationTrack, number)
animationTrack.Looped = true
animationTrack:Play()
local numberOfLoops = 0
local connection = nil
connection = animationTrack.DidLoop:Connect(function()
numberOfLoops = numberOfLoops + 1
print("loop: ", numberOfLoops)
if numberOfLoops >= number then
animationTrack:Stop()
connection:Disconnect() -- it's important to disconnect connections when they are no longer needed
end
end)
end
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://507765644"
local humanoid = script.Parent:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animationTrack = animator:LoadAnimation(animation)
playForNumberLoops(animationTrack, 5)
Ended
Si accende quando il AnimationTrack è completamente finito di spostare qualsiasi cosa nel Mondo.L'animazione ha finito di giocare, il "fade out" è finito e il soggetto è in una posa neutra.
Puoi usarlo per agire quando il soggetto della traccia di animazione è tornato in una posa neutra che non è influenzata dal AnimationTrack o per pulire il AnimationTrack .o qualsiasi connessione associata.
Campioni di codice
The function in this code sample plays an animationTrack and yields until it has stopped and ended, printing at each step along the way.
local InsertService = game:GetService("InsertService")
local Players = game:GetService("Players")
-- Create an NPC model to animate.
local npcModel = Players:CreateHumanoidModelFromUserId(129687796)
npcModel.Name = "JoeNPC"
npcModel.Parent = workspace
npcModel:MoveTo(Vector3.new(0, 15, 4))
local humanoid = npcModel:WaitForChild("Humanoid")
-- Load an animation.
local animationModel = InsertService:LoadAsset(2510238627)
local animation = animationModel:FindFirstChildWhichIsA("Animation", true)
local animator = humanoid:WaitForChild("Animator")
local animationTrack = animator:LoadAnimation(animation)
-- Connect to Stopped event. This fires when animation stops of
-- it's own accord, or we explicitly call Stop.
animationTrack.Stopped:Connect(function()
print("Animation stopped")
end)
-- Connect to Ended event. This fires when when animation is completely
-- finished affecting the world. In this case it will fire 3 seconds
-- after we call animationTrack:Stop because we pass in a 3
-- second fadeOut.
animationTrack.Ended:Connect(function()
print("Animation ended")
animationTrack:Destroy()
end)
-- Run, give it a bit to play, then stop.
print("Calling Play")
animationTrack:Play()
task.wait(10)
print("Calling Stop")
animationTrack:Stop(3)
KeyframeReached
Si attiva ogni volta che il riproduzione di un AnimationTrack raggiunge un Keyframe che non ha il nome predefinito - "Keyframe".
Questo evento consente a un sviluppatore di eseguire il codice a punti predefiniti in un'animazione (impostati da Keyframe nomi).Questo consente alla funzionalità predefinita delle animazioni di Roblox di essere estesa aggiungendo Sounds o ParticleEffects a punti diversi in un'animazione.
Keyframe i nomi non devono essere unici.Ad esempio, se un'Animazione ha tre keyframe chiamati "Particelle" l'evento KeyframeReached verrà attivato ogni volta che viene raggiunto uno di questi keyframe.
Keyframe i nomi possono essere impostati nell'Editor di animazione Roblox quando si crea o modifica un'animazioni.Non possono tuttavia essere impostati da un Script su un'animazione esistente prima di giocarci.
Parametri
Stopped
Si accende ogni volta che il AnimationTrack finisce di giocare.
Questo evento ha una serie di usi.Può essere utilizzato per aspettare fino a quando un AnimationTrack non si è fermato prima di continuare (ad esempio, se incatenare una serie di animazioni da riprodurre dopo l'una l'altra).Può essere utilizzato anche per pulire qualsiasi Instances creato durante il riproduzione dell'animazione.
Campioni di codice
The function in this code sample will play an animationTrack and yield until it has stopped, before printing.
local function yieldPlayAnimation(animationTrack, fadeTime, weight, speed)
animationTrack:Play(fadeTime, weight, speed)
animationTrack.Stopped:Wait()
print("Animation has stopped")
end
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://507765644"
local humanoid = script.Parent:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")
local animationTrack = animator:LoadAnimation(animation)
yieldPlayAnimation(animationTrack, 1, 0.6, 1)