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 AnimationController . 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à di lettura che restituisce vero quando il AnimationTrack sta giocando.
Una proprietà di 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 ripetrà dopo aver finito. Se viene cambiato mentre si gioca il risultato avrà effetto dopo la finzione dell'animazione.
Imposta la priorità di un AnimationTrack . Dipendendo da ciò che questo è impostato, giocare più animazioni contemporaneamente visualizzerà questa proprietà per determinare quale Class.Keyframe``Class.Pose|Poses dovrebbe essere giocato uno sull'altro.
La velocità di un AnimationTrack è una proprietà di lettura 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 richiede l'animazione per completare è uguale a AnimationTrack.Length (in secondi).
Restituisce la posizione nel tempo in secondi che un AnimationTrack è attraverso giocare la sua animazionidi origine. Può essere impostato per fare il salto della traccia in un momento specifico nell'animazioni.
Proprietà di proprietà che fornisce il peso attuale del AnimationTrack . Ha un valore predefinito di 1.
Proprietà di proprietà 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, un valore negativo la riproduce in avanti e 0 la riproduce.
Cambia il peso di un'animazioni, con il parametro opzionale fadeTime che determina quanto tempo ci vuole per AnimationTrack.WeightCurrent per raggiungere AnimationTrack.WeightTarget .
Restituisce un event che si attiva quando un KeyframeMarker specificato è stato colpito in una animation .
Restituisce la posizione temporale del primo Keyframe del nome specificato in un AnimationTrack .
Gioca il AnimationTrack. Una volta chiamato un AnimationTrack giocherà con il tempo di persistenza specificato, il peso e la velocità.
Interrompe la riproduzione del AnimationTrack. Una volta chiamato il playback del AnimationTrack, si fermerà e il peso dell'animazione si sposterà verso zero per un'area di tempo specificata dal parametro di fusione opzionale.
Eventi
Si attiva quando un AnimationTrack loop su l'aggiornamento successivo alla fine del precedente loop animazione.
Si attiva quando il AnimationTrack è completamente finito di spostare qualcosa nel Mondo. L'animazione ha finito di giocare, il "fade out" è finito e il soggetto è in una posa neutra.
Fa ogni volta che il riproduzione di un AnimationTrack raggiunge un Keyframe che non ha il nome predefinito - "Keyframe.".
Si attiva quando il AnimationTrack finisce di giocare. L'AnimationTrack potrebbe ancora animare il soggetto mentre l'animazione "fade out" finisce. Per catturare quando l'AnimationTrack è completamente finito di spostare qualcosa 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 2>Class.Animation2> su un 5>Class.Animator:LoadAnimation() 8> usando il metodo 9>Class.Animator:LoadAnimation()9>.
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à di lettura che restituisce vero quando il AnimationTrack sta giocando.
Questa proprietà può essere utilizzata dai developer per controllare se un'animazione sta già giocando prima di giocarlo (poiché ciò avrebbe causato il suo Ricomincia). Se un developer vuole ottenere tutte le giocando AnimationTracks su un Humanoid o AnimationController dovrebbe usare 1> Class.
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à di 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 è pari a 1, l'animazione richiederà AnimationTrack.Length (in secondi) per completarla.
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 ripetrà dopo aver finito. Se viene cambiata mentre si gioca l'animazione avrà effetto dopo la finzione dell'animazione.
La proprietà Looped per AnimationTrack predefinita come impostata nell'animatore. Tuttavia, questa proprietà può essere cambiata, consentendo di controllare la AnimationTrack mentre viene eseguito il gioco. Looped gestisce anche le animazioni prodotte in modo inversivo (AnimationTrack.Speed negativo). Dopo il primo keyframe, riavrà avvio al primo Fotogramma chiave.
Questa proprietà consente al sviluppatore di avere una variante looping e non looping della stessa animazioni, 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 questo è impostato su, giocare più animazioni contemporaneamente sembrerà a questa proprietà per determinare quale Class.Keyframe``Class.Pose|Poses dovrebbe essere giocato uno sull'altro.
La proprietà priorità per AnimationTrack predefinita come è stata impostata e pubblicata dal Editor di animazione di Studio . Utilizza Enum.AnimationPriority che ha 7 livelli di priorità:
- Action4 (priorità più alta)
- Azione3
- Azione2
- Azione
- Movimento
- Inattivo
- Nucleo (riorità più bassa)
Imposta correttamente le priorità di animazione, sia attraverso l'editor che attraverso questa Proprietà, consentono più animazioni di essere giocati senza che siano in conflitto. Dove due animazioni di animazione diretta il target di muovere lo stesso limbo in differenti modi, il AnimationTrack con la priorità più alta Mostrare. Se entrambe le animazioni hanno la stessa priorità, i pesi delle tracce saranno utilizzati per combinare le animazioni.
Questa proprietà consente anche al sviluppatore di giocare la stessa animazione a diverse priorità, senza dover caricare versioni aggiuntive su Roblox.
Speed
La velocità di un AnimationTrack è una proprietà di lettura 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 richiede l'animazione per completare è uguale a AnimationTrack.Length (in secondi).
Se la velocità viene regolata, allora il tempo effettivo richiesto per riprodurre un traccia può essere calcolato dividendo la lunghezza per la velocità. La velocità è una quantità non unica.
La velocità può essere utilizzata per associare la lunghezza di un'animazione a diversi eventi di gioco (per esempio ricaricare una capacità) senza dover caricare le diverse varianti della stessa animazioni.
Questa proprietà è letta solo, e puoi cambiarlo 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 che un AnimationTrack è attraverso giocare la sua animazionidi origine. Può essere impostato per fare il salto della traccia in un momento specifico nell'animazioni.
TimePosition può essere impostato per andare a un punto specifico nell'animazioni, ma il AnimationTrack deve essere in gioco per farlo. Può essere utilizzato anche in combinazione con AnimationTrack:AdjustSpeed() per congelare l'animazione al 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 è impostato in un AnimationTrack il peso non cambia istantaneamente ma si muove da WeightCurrent a AnimationTrack.WeightTarget . Il tempo richiesto per fare questo è determinato dal parametro fadeTime quando l'animazione viene giocata, o il peso viene regolato.
WeightCurrent può essere controllato contro AnimationTrack.WeightTarget per vedere se il peso desiderato è stato raggiunto. Nota che questi valori non dovrebbero essere controllati per l'uguaglianza con l'operatore == , poiché entrambi questi valori sono float. Per vedere se WeightCurrent ha raggiunto il peso desiderato, è raccomandato vedere se la distanza tra questi valori è abbastanza piccola (vedi esempio di codice sotto).
Il sistema di peso dell'animazione viene utilizzato per determinare in che modo AnimationTracks che giocano alla stessa priorità vengono mescolati insieme. Il peso predefinito è uno, e nessun
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à di lettura che dà il peso attuale del AnimationTrack . Ha un valore predefinito di 1 e viene imp
WeightCurrent può essere controllato contro AnimationTrack.WeightTarget per vedere se il peso desiderato è stato raggiunto. Nota che questi valori non dovrebbero essere controllati per l'uguaglianza con l'operatore == , poiché entrambi questi valori sono float. Per vedere se WeightCurrent ha raggiunto il peso desiderato, è raccomandato vedere se la distanza tra questi valori è abbastanza piccola (vedi esempio di codice sotto).
Il sistema di peso dell'animazione viene utilizzato per determinare in che modo AnimationTracks che giocano alla stessa priorità vengono mescolati insieme. Il peso predefinito è uno, e nessun
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à la riproduce in avanti, un valore negativo la riproduce in avanti e 0 la riproduce.
La velocità iniziale di un AnimationTrack è impostata come un parametro in AnimationTrack:Play() . Tuttavia, la velocità di un traccia può essere cambiata durante il playback, utilizzando AdjustSpeed. Quando la velocità è pari a 1, la quantità di tempo che un'animazione richiede per completarsi è pari a AnimationTrack.Length (in secondi).
Quando viene regolato, allora il tempo reale richiesto per riprodurre una traccia può essere calcolato dividendo la lunghezza per la velocità. La velocità è una quantità non unica.
La velocità può essere utilizzata per associare la lunghezza di un'animazione a diversi eventi di gioco (per esempio ricaricare una capacità) senza dover caricare le diverse varianti della stessa animazioni.
Parametri
La velocità di riproduzione l'animazione è da cambiare.
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 opzionale fadeTime che determina quanto tempo ci vuole per AnimationTrack.WeightCurrent per raggiungere AnimationTrack.WeightTarget .
Quando il peso è impostato in un AnimationTrack il peso non cambia istantaneamente ma si muove da WeightCurrent a AnimationTrack.WeightTarget . Il tempo richiesto per fare questo è determinato dal parametro fadeTime quando l'animazione viene giocata, o il peso viene regolato.
WeightCurrent può essere controllato contro AnimationTrack.WeightTarget per vedere se il peso desiderato è stato raggiunto. Nota che questi valori non dovrebbero essere controllati per l'uguaglianza con l'operatore == , poiché entrambi questi valori sono float. Per vedere se WeightCurrent ha raggiunto il peso desiderato, è raccomandato vedere se la distanza tra questi valori è abbastanza piccola (vedi esempio di codice sotto).
Il sistema di peso dell'animazione viene utilizzato per determinare in che modo AnimationTracks che giocano alla stessa priorità sono mescolati insieme. Il peso
Parametri
Il peso che l'animazione è destinata a essere cambiata.
La durata del tempo che l'animazione svanisce 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 , ad eccezione che si attiva solo quando un KeyframeMarker specificato viene colpito in un 1> Class.Animation|animation1> . La differenza consente un controllo maggiore su quando l'evento si Lanciare.
Per saperne di più sull'utilizzo di questa funzione, vedi Eventi di animazione nell'articolo Editor di animazione.
Più su Keyframes
Keyframe i nomi possono essere impostati nell'animatore Roblox Anima quando si crea o si modifica un'animazioni. Non possono, tuttavia, essere impostati da un Script su un'animazione esistente prima di giocarci.
Keyframe i nomi non devono essere unici. Ad esempio, se un Animation ha tre keyframe chiamati "EmitParticles", l'evento connesso restituito da questa funzione attiva ogni volta che uno di questi keyframe viene raggiunto.
Vedi anche:
Parametri
Il nome del KeyFrameMarker il segnale è in corso di creazione.
Restituzioni
Il segnale viene creato e sparato quando l'animazione raggiunge il creato KeyFrameMarker .
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 della prima Keyframe del nome specificato in un AnimationTrack . Se più Keyframes condividono lo stesso nome, restituirà l'ultimo in animazioni.
Questa funzione restituirà un errore se viene utilizzata con un nome di keyframe non valido (come quello che non esiste per esempio) o se l'animazione sottostante Animation non è ancora caricata. Per affrontare questo, assicurati che vengano utilizzati solo i nomi dei keyframe e che l'animazione sia stata caricata prima di chiamare questa funzione.
Per controllare se l'animazione è stata caricata, verifica che il AnimationTrack.Length sia 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 chiamato, l'animazione della traccia inizierà a giocare e il peso dell'animazione aumenterà da 0 a 0,5 (il peso predefinito è 1) al tempo di fusione specificato (predefinito 0,1).
La velocità con cui AnimationTrack si esibirà è determinata dal parametro di velocità (predefinito 1). Quando la velocità è uguale a 1, il numero di secondi che il track completa è uguale alla ProprietàAnimationTrack.Length del track. Ad esempio, una velocità di 2 farà in modo che il track si esibisca 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 iniziare l'animazione a un punto specifico utilizzando AnimationTrack.TimePosition , è importante che l'animazione venga giocata prima di questo.
Parametri
La durata del tempo che il peso dell'animazionidovrebbe svanire per.
Il peso che l'animazione deve essere giocata.
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)
Stop
Interrompe la riproduzione del AnimationTrack. Una volta chiamato il playback del AnimationTrack, si fermerà e il peso dell'animazione si sposterà verso zero per un'area di tempo specificata dal parametro di fusione opzionale.
Ad esempio, se Stop viene chiamato con un tempo di fusione di 2 secondi, ci vorranno due secondi per il peso della AnimationTrack per raggiungere zero e i suoi effetti completamente Terminare. Nota che questo sarà il caso indipendentemente dal peso iniziale dell'animazioni.
Non è raccomandato utilizzare un tempo di fusione di 0 secondi per tentare di sovrascrivere questo effetto e terminare l'animazione immediatamente come presente, questo causa le posizioni AnimationTrack a congelamento.
Parametri
Il tempo, in secondi, per cui il peso dell'animazione deve essere svanito.
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 quando un AnimationTrack a loop completa, nel prossimo Aggiornarmento.
Attualmente potrebbe anche attivarsi all'esatta fine di una non scriptata animazione track 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 attiva quando il AnimationTrack è completamente finito di spostare qualcosa nel Mondo. L'animazione ha finito di giocare, il "fade out" è finito e il soggetto è in una posa neutra.
Puoi usarlo per prendere azione quando il soggetto della pista di animazione è tornato in una posa neutra che non è influenzata dalla AnimationTrack o per pulire la 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
Fa 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 (impostata da Keyframe nomi) . Ciò consente che la funzionalità predefinita delle animazioni Roblox venga espansa aggiungendo Sounds o ParticleEffects a diversi punti in un'animazione.
Keyframe i nomi non devono essere unici. Ad esempio, se un'animazione ha tre keyframe chiamati "Particles" l'evento KeyframeReached attiverà ogni volta che uno di questi keyframe viene raggiunto.
Keyframe i nomi possono essere impostati nell'Editor Animation Roblox quando si crea o si modifica un'animazioni. Tuttavia, non possono essere impostati da un Script su un'animazione esistente prima di giocarci.
Parametri
Stopped
Si attiva quando il AnimationTrack finisce di giocare.
Questo evento ha un certo numero di utilizzi. Può essere utilizzato per attendere fino a quando un AnimationTrack non ha smesso prima di continuare (per esempio, se si tratta di una serie di animazioni da riprodurre dopo di loro). Può anche essere utilizzato per pulire qualsiasi Instances creato durante il playback 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)