AnimationTrack

Afficher les obsolètes

*Ce contenu est traduit en utilisant l'IA (Beta) et peut contenir des erreurs. Pour consulter cette page en anglais, clique ici.

Création impossible

Contrôle la lecture d'une animation sur un Animator. Cet objet ne peut pas être créé, il est plutôt retourné par la méthode Animator:LoadAnimation().

Résumé

Propriétés

  • Lecture uniquement
    Non répliqué
    Lecture parallèle

    L'objet Animation qui a été utilisé pour créer ce AnimationTrack.

  • Lecture uniquement
    Non répliqué
    Lecture parallèle

    Une propriété de lecture seule qui retourne vrai lorsque le AnimationTrack est en train de jouer.

  • Lecture uniquement
    Non répliqué
    Lecture parallèle

    Une propriété de lecture seule qui renvoie la longueur (en secondes) d'un AnimationTrack .Cela retournera 0 jusqu'à ce que l'animation soit entièrement chargée et donc peut ne pas être immédiatement disponible.

  • Lecture parallèle

    Définit si l'animation se répétera après avoir terminé. Si elle est modifiée pendant le jeu, l'effet prendra effet après la fin de l'animation.

  • Définit la priorité d'un AnimationTrack.Selon ce qui est défini, jouer plusieurs animations à la fois cherchera cette propriété pour déterminer laquelle Class.Keyframe``Class.Pose|Poses devrait être jouée sur l'autre.

  • Lecture uniquement
    Non répliqué
    Lecture parallèle

    La vitesse d'un AnimationTrack est une propriété de lecture seule qui donne la vitesse de lecture actuelle du AnimationTrack .Cela a une valeur par défaut de 1.Lorsque la vitesse est égale à 1, la quantité de temps qu'une animation prend pour se terminer est égale à AnimationTrack.Length (en secondes).

  • Non répliqué
    Lecture parallèle

    Renvoie la position dans le temps en secondes qu'un AnimationTrack est à travers la lecture de son animationssource.Peut être défini pour faire sauter la piste à un moment spécifique de l'animations.

  • Lecture uniquement
    Non répliqué
    Lecture parallèle

    Propriété de lecture seule qui donne le poids actuel du AnimationTrack . Il a une valeur par défaut de 1.

  • Lecture uniquement
    Non répliqué
    Lecture parallèle

    Propriété de lecture seule qui donne le poids actuel du AnimationTrack .

Méthodes

Évènements

Propriétés

Animation

Lecture uniquement
Non répliqué
Lecture parallèle

L'objet Animation qui a été utilisé pour créer ce AnimationTrack.Pour créer un AnimationTrack , vous devez charger un objet Animation sur un Animator en utilisant la méthode Animator:LoadAnimation().

Échantillons de code

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.

Listen For New Animations

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

Lecture uniquement
Non répliqué
Lecture parallèle

Une propriété de lecture seule qui retourne vrai lorsque le AnimationTrack est en train de jouer.

Cette propriété peut être utilisée par les développeurs pour vérifier si une animation est déjà en train de jouer avant de la jouer (car cela la ferait redémarrer).Si un développeur souhaite obtenir tout le jeu AnimationTracks sur un Animator ou un Humanoid, il devrait utiliser Animator:GetPlayingAnimationTracks()

Échantillons de code

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.

AnimationTrack IsPlaying

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

Lecture uniquement
Non répliqué
Lecture parallèle

Une propriété de lecture seule qui renvoie la longueur (en secondes) d'un AnimationTrack .Cela retournera 0 jusqu'à ce que l'animation soit entièrement chargée et donc peut ne pas être immédiatement disponible.

Lorsque le AnimationTrack.Speed d'un AnimationTrack est égal à 1, l'animation prendra AnimationTrack.Length (en secondes) pour se terminer.

Échantillons de code

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).

Playing Animation for a Specific Duration

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

Lecture parallèle

Cette propriété détermine si l'animation se répétera après avoir terminé.Si elle est modifiée pendant le jeu, la modification prendra effet après la fin de l'animation.

La propriété Looped pour AnimationTrack par défaut à la façon dont elle a été définie dans l'éditeur d'animation.Cependant, cette propriété peut être modifiée, ce qui permet de contrôler le AnimationTrack pendant que le jeu est en cours d'exécution.Looped gère également correctement les animations jouées en arrière (négatives AnimationTrack.Speed ).Après que la première clé ait été atteinte, elle redémarrera à la dernière image-clé.

Cette propriété permet au développeur d'avoir une variante de boucle et de non boucle de la même animations, sans avoir à télécharger deux versions sur Roblox.

Échantillons de code

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.

Animation Looping

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.

Play AnimationTrack for a Number of Loops

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)
Lecture parallèle

Cette propriété définit la priorité d'un AnimationTrack .Selon ce qui est défini, jouer plusieurs animations à la fois cherchera cette propriété pour déterminer laquelle Class.Keyframe``Class.Pose|Poses devrait être jouée sur l'autre.

La propriété priorité pour par défaut à la façon dont elle a été définie et publiée dans l'éditeur d'animation de Studio .Il utilise Enum.AnimationPriority qui a 7 niveaux de priorité :

  1. Action4 (priorité la plus élevée)
  2. Action3
  3. Action2
  4. Action
  5. Mouvement
  6. Inactif
  7. Cœur (priorité la plus basse)

Définir correctement les priorités d'animation, soit via l'éditeur, soit via cette propriété, permet de jouer plusieurs animations sans qu'elles ne se heurtent.Lorsque deux animations de jeu dirigent la cible pour déplacer la même extrémité de manière différente, l'AnimationTrack avec la plus haute priorité s'affichera.Si les deux animations ont la même priorité, les poids des pistes seront utilisés pour combiner les animations.

Cette propriété permet également au développeur de jouer la même animation à différentes priorités, sans avoir à télécharger de nouvelles versions sur Roblox.

Speed

Lecture uniquement
Non répliqué
Lecture parallèle

La vitesse d'un AnimationTrack est une propriété de lecture seule qui donne la vitesse de lecture actuelle du AnimationTrack .Cela a une valeur par défaut de 1.Lorsque la vitesse est égale à 1, la quantité de temps qu'une animation prend pour se terminer est égale à AnimationTrack.Length (en secondes).

Si la vitesse est ajustée, alors le temps réel qu'il faudra pour jouer une piste peut être calculé en divisant la longueur par la vitesse.La vitesse est une quantité sans unité.

La vitesse peut être utilisée pour lier la durée d'une animation à différents événements de jeu (par exemple, recharger une capacité) sans avoir à télécharger différentes variantes de la même animations.

Cette propriété est seulement lue et vous pouvez la modifier en utilisant AnimationTrack:AdjustSpeed().

Échantillons de code

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.

Animation 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).

Playing Animation for a Specific Duration

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

Non répliqué
Lecture parallèle

Renvoie la position dans le temps en secondes qu'un AnimationTrack est à travers la lecture de son animationssource.Peut être défini pour faire sauter la piste à un moment spécifique de l'animations.

La position dans le temps peut être définie pour aller à un point spécifique de l'animations, mais le AnimationTrack doit être en train de jouer pour le faire.Il peut également être utilisé en combinaison avec AnimationTrack:AdjustSpeed() pour geler l'animation à un point souhaité (en définissant la vitesse à 0).

Échantillons de code

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.

Freeze Animation at Position

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

Lecture uniquement
Non répliqué
Lecture parallèle

Lorsque le poids est défini dans un AnimationTrack, il ne change pas instantanément mais se déplace de WeightCurrent à AnimationTrack.WeightTarget.Le temps qu'il faut pour le faire est déterminé par le paramètre fadeTime donné lorsque l'animation est jouée, ou le poids est ajusté.

WeightCurrent peut être vérifié contre AnimationTrack.WeightTarget pour voir si le poids souhaité a été atteint.Notez que ces valeurs ne doivent pas être vérifiées pour l'égalité avec l'opérateur ==, car ces deux valeurs sont des flottants.Pour voir si WeightCurrent a atteint le poids cible, il est recommandé de vérifier si la distance entre ces valeurs est suffisamment petite (voir échantillon de code ci-dessous).

Le système de pondération des animations est utilisé pour déterminer comment les AnimationTracks jouant à la même priorité sont mélangés ensemble.Le poids par défaut est un, et aucun mouvement ne sera visible sur un AnimationTrack avec un poids de zéro.La pose qui est montrée à tout moment est déterminée par la moyenne pondérée de tous les Poses et le poids actuel de chacun AnimationTrack .Dans la plupart des cas, les animations de mélange ne sont pas requises et l'utilisation de AnimationTrack.Priority est plus appropriée.

Échantillons de code

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.

WeightCurrent and WeightTarget

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

Lecture uniquement
Non répliqué
Lecture parallèle

AnimationTrack.WeightTarget est une propriété de lecture seule qui donne le poids actuel du AnimationTrack.Il a une valeur par défaut de 1 et est défini lorsque AnimationTrack:Play() , AnimationTrack:Stop() ou AnimationTrack:AdjustWeight() est appelé.Lorsque le poids est défini dans un AnimationTrack il ne change pas instantanément mais se déplace de WeightCurrent à AnimationTrack.WeightTarget.Le temps qu'il faut pour le faire est déterminé par le paramètre fadeTime donné lorsque l'animation est jouée, ou le poids est ajusté.

WeightCurrent peut être vérifié contre AnimationTrack.WeightTarget pour voir si le poids souhaité a été atteint.Notez que ces valeurs ne doivent pas être vérifiées pour l'égalité avec l'opérateur ==, car ces deux valeurs sont des flottants.Pour voir si WeightCurrent a atteint le poids cible, il est recommandé de vérifier si la distance entre ces valeurs est suffisamment petite (voir échantillon de code ci-dessous).

Le système de pondération des animations est utilisé pour déterminer comment les AnimationTracks jouant à la même priorité sont mélangés ensemble.Le poids par défaut est un, et aucun mouvement ne sera visible sur un AnimationTrack avec un poids de zéro.La pose qui est montrée à tout moment est déterminée par la moyenne pondérée de tous les Poses et le poids actuel de chacun AnimationTrack .Dans la plupart des cas, les animations de mélange ne sont pas requises et l'utilisation de AnimationTrack.Priority est plus appropriée.

Échantillons de code

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.

WeightCurrent and WeightTarget

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

Méthodes

AdjustSpeed

()

Cette fonction modifie le AnimationTrack.Speed d'une animations.Une valeur positive pour la vitesse joue l'animation en avant, une négative la joue en arrière, et 0 la met en pause.

La vitesse initiale d'une piste d'animation est définie comme un paramètre dans AnimationTrack:Play() .Cependant, la vitesse d'une piste peut être modifiée pendant la lecture, en utilisant AdjustSpeed.Lorsque la vitesse est égale à 1, la quantité de temps qu'une animation prend pour se terminer est égale à AnimationTrack.Length (en secondes).

Quand est ajusté, le temps réel qu'il faudra pour qu'une piste soit jouée peut être calculé en divisant la longueur par la vitesse. La vitesse est une quantité sans unité.

La vitesse peut être utilisée pour lier la durée d'une animation à différents événements de jeu (par exemple, recharger une capacité) sans avoir à télécharger différentes variantes de la même animations.

Paramètres

speed: number

La vitesse de lecture de l'animation doit être modifiée.

Valeur par défaut : 1

Retours

()

Échantillons de code

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).

Playing Animation for a Specific Duration

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.

Animation 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

()

Change le poids d'une animations, avec le paramètre facultatif fadeTime qui détermine la durée pendant laquelle AnimationTrack.WeightCurrent atteint AnimationTrack.WeightTarget.

Lorsque le poids est défini dans un AnimationTrack, il ne change pas instantanément mais se déplace de WeightCurrent à AnimationTrack.WeightTarget.Le temps qu'il faut pour le faire est déterminé par le paramètre fadeTime donné lorsque l'animation est jouée, ou le poids est ajusté.

WeightCurrent peut être vérifié contre AnimationTrack.WeightTarget pour voir si le poids souhaité a été atteint.Notez que ces valeurs ne doivent pas être vérifiées pour l'égalité avec l'opérateur ==, car ces deux valeurs sont des flottants.Pour voir si WeightCurrent a atteint le poids cible, il est recommandé de vérifier si la distance entre ces valeurs est suffisamment petite (voir échantillon de code ci-dessous).

Le système de pondération des animations est utilisé pour déterminer comment les AnimationTracks jouant à la même priorité sont mélangés ensemble.Le poids par défaut est un, et aucun mouvement ne sera visible sur un AnimationTrack avec un poids de zéro.La pose qui est montrée à tout moment est déterminée par la moyenne pondérée de tous les Poses et le poids actuel de chacun AnimationTrack .Voir ci-dessous pour un exemple de fusion d'animation en pratique.Dans la plupart des cas, les animations de mélange ne sont pas requises et l'utilisation de AnimationTrack.Priority est plus appropriée.

Paramètres

weight: number

Le poids que l'animation doit être modifié.

Valeur par défaut : 1
fadeTime: number

La durée du temps pendant lequel l'animation disparaîtra entre le poids ancien et le nouveau poids pour.

Valeur par défaut : 0.100000001

Retours

()

Échantillons de code

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).

AnimationTrack Change Weight

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

Cette fonction renvoie une event similaire à l'événement AnimationTrack.KeyframeReached, sauf qu'elle ne se déclenche que lorsqu'un événement spécifié KeyframeMarker a été frappé dans un animation .La différence permet une plus grande maîtrise du moment où l'événement se lancer.

Pour en savoir plus sur l'utilisation de cette fonction, voir événements d'animation dans l'article éditeur d'animation.

Plus sur les cadres clés

les noms peuvent être définis dans l'éditeur d'animation Roblox lors de la création ou de l'édition d'une animations.Ils ne peuvent cependant pas être définis par un Script sur une animation existante avant de la jouer.

Keyframe les noms n'ont pas besoin d'être uniques.Par exemple, si un Animation a trois keyframes nommés "EmitParticles", l'événement connecté retourné par cette fonction se déclenchera chaque fois qu'un de ces keyframes est atteint.

Voir aussi :

Paramètres

name: string

Le nom du signal KeyFrameMarker est en cours de création.

Valeur par défaut : ""

Retours

Le signal créé et tiré lorsque l'animation atteint le créé KeyFrameMarker.

Échantillons de code

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.

Listening to Keyframe Markers

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)

GetTargetInstance

Paramètres

name: string
Valeur par défaut : ""

Retours

GetTargetNames


Retours

GetTimeOfKeyframe

Renvoie la position temporelle du premier Keyframe du nom donné dans un AnimationTrack .Si plusieurs Keyframes partagent le même nom, il retournera le plus ancien dans l'animations.

Cette fonction renverra une erreur si elle est utilisée avec un nom de cadre clé non valide (celui qui n'existe pas par exemple) ou si le sous-jacent Animation n'a pas encore été chargé.Pour résoudre ce problème, assurez-vous que seuls les noms de cadre clé corrects sont utilisés et que l'animation a été chargée avant d'appeler cette fonction.

Pour vérifier si l'animation a été chargée, vérifiez que le AnimationTrack.Length est supérieur à zéro.

Paramètres

keyframeName: string

Le nom associé à la Keyframe à trouver.

Valeur par défaut : ""

Retours

Le temps, en secondes, le Keyframe se produit à la vitesse de lecture normale.

Échantillons de code

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.

Jump To Keyframe

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

()

Lorsque AnimationTrack:Play() est appelé, l'animation de la piste commencera à jouer et le poids de l'animation augmentera de 0 à la poids spécifié (défaut de 1) au cours du temps de fondu de spécifié (défaut de 0.1).

La vitesse à laquelle le AnimationTrack jouera est déterminée par le paramètre de vitesse (défaut de 1).Lorsque la vitesse est égale à 1, le nombre de secondes que la piste prendra pour se terminer est égal à la propriété de la piste AnimationTrack.Length.Par exemple, une vitesse de 2 provoquera que la piste se joue deux fois plus rapidement.

Le poids et la vitesse de l'animation peuvent également être modifiés après que l'animation ait commencé à jouer en utilisant les méthodes AnimationTrack:AdjustWeight() et AnimationTrack:AdjustSpeed().

Si le développeur veut démarrer l'animation à un point spécifique en utilisant AnimationTrack.TimePosition, il est important que l'animation soit jouée avant que cela soit fait.

Paramètres

fadeTime: number

La durée du temps au cours de laquelle le poids de l'animationsdevrait disparaître.

Valeur par défaut : 0.100000001
weight: number

Le poids de l'animation à jouer.

Valeur par défaut : 1
speed: number

La vitesse de lecture de l'animations.

Valeur par défaut : 1

Retours

()

Échantillons de code

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).

Playing Animation for a Specific Duration

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.

Freeze Animation at Position

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

()

Paramètres

name: string
Valeur par défaut : ""
target: Instance
Valeur par défaut : ""

Retours

()

Stop

()

Arrête le AnimationTrack.Une fois appelé, le poids de l'animation se déplacera vers zéro au fil du temps spécifié par le paramètre facultatif fadeTime optionnel.Par exemple, si Stop() est appelé avec un fadeTime de 2 , il faudra deux secondes pour que le poids de la piste atteigne zéro et ses effets se terminercomplètement.Veuillez noter que ce sera le cas, indépendamment du poids initial de l'animations.

Il n'est pas recommandé d'utiliser un fadeTime de 0 dans une tentative d'annuler cet effet et de mettre fin à l'animation immédiatement pour Motor6Ds ceux qui ont leur Motor.MaxVelocity défini à zéro, car cela fait geler les jointures en emplacement.Si elle doit se terminer immédiatement, assurez-vous que le Motor.MaxVelocity de Motor6Ds dans votre rig est suffisamment élevé pour qu'ils s'accrochent correctement.

Paramètres

fadeTime: number

Le temps, en secondes, pour lequel le poids de l'animation doit être estompé.

Valeur par défaut : 0.100000001

Retours

()

Échantillons de code

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).

AnimationTrack Stop

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)

Évènements

DidLoop

Cet événement se déclenche chaque fois qu'une boucle AnimationTrack bouclée termine une boucle, lors de la prochaine mise à jour.

Actuellement, il peut également tirer à la fin exacte d'une piste d'animation non bouclée, mais ce comportement ne doit pas être utilisé.


Échantillons de code

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.

Play AnimationTrack for a Number of Loops

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

S'enflamme lorsque le AnimationTrack est complètement terminé de déplacer quoi que ce soit dans le monde.L'animation a fini de jouer, la « disparition » est terminée et le sujet est dans une position neutre.

Vous pouvez l'utiliser pour agir lorsque le sujet de la piste d'animation est de retour dans une position neutre qui n'est pas affectée par le AnimationTrack ou pour nettoyer le AnimationTrack .ou toute connexion associée.


Échantillons de code

The function in this code sample plays an animationTrack and yields until it has stopped and ended, printing at each step along the way.

AnimationTrack Ended

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

Il se déclenche chaque fois que la lecture d'un AnimationTrack atteint un Keyframe qui n'a pas le nom par défaut - "Keyframe".

Cet événement permet à un développeur d'exécuter du code à des points prédéfinis dans une animation (définis par Keyframe noms).Cela permet d'étendre la fonctionnalité par défaut des animations Roblox en ajoutant Sounds ou ParticleEffects à différents points dans une animation.

Keyframe les noms n'ont pas besoin d'être uniques.Par exemple, si une animation a trois keyframes nommés « Particles », l'événement KeyframeReached se déclenchera chaque fois qu'un de ces keyframes sera atteint.

Keyframe les noms peuvent être définis dans l'éditeur d'animation Roblox lors de la création ou de l'édition d'une animations.Cependant, elles ne peuvent pas être définies par un Script sur une animation existante avant de la jouer.

Paramètres

keyframeName: string

Le nom du Keyframe atteint.


Stopped

S'enflamme chaque fois que la AnimationTrack finit de jouer.

Cet événement a plusieurs utilisations.Il peut être utilisé pour attendre jusqu'à ce qu'un AnimationTrack ait cessé avant de continuer (par exemple, si vous chaînez une série d'animations pour jouer après les unes les autres).Il peut également être utilisé pour nettoyer tout Instances créé pendant la lecture de l'animation.


Échantillons de code

The function in this code sample will play an animationTrack and yield until it has stopped, before printing.

AnimationTrack Stopped

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)