AnimationTrack

Mostrar obsoleto

*Este contenido se traduce usando la IA (Beta) y puede contener errores. Para ver esta página en inglés, haz clic en aquí.

No creable

Controla la reproducción de una animación en un Animator. Este objeto no se puede crear, en su lugar se devuelve por el método Animator:LoadAnimation().

Resumen

Propiedades

  • Solo lectura
    No replicado
    Leer paralelo

    El objeto Animation que se utilizó para crear este AnimationTrack.

  • Solo lectura
    No replicado
    Leer paralelo

    Una propiedad solo de lectura que devuelve verdadero cuando el AnimationTrack está jugando.

  • Solo lectura
    No replicado
    Leer paralelo

    Una propiedad de solo lectura que devuelve la longitud (en segundos) de un AnimationTrack .Esto devolverá 0 hasta que la animación se haya cargado completamente y, por lo tanto, puede que no esté disponible de inmediato.

  • Leer paralelo

    Establece si la animación se repetirá después de terminar. Si se cambia mientras se reproduce el resultado entrará en vigor después de que la animación termine.

  • Establece la prioridad de un AnimationTrack .Dependiendo de lo que esté configurado, jugar múltiples animaciones a la vez buscará esta propiedad para averiguar qué Class.Keyframe``Class.Pose|Poses debe reproducirse sobre la otra.

  • Solo lectura
    No replicado
    Leer paralelo

    La velocidad de un AnimationTrack es una propiedad de solo lectura que proporciona la velocidad de reproducción actual del AnimationTrack .Esto tiene un valor predeterminado de 1.Cuando la velocidad es igual a 1, la cantidad de tiempo que tarda una animación en completarse es igual a AnimationTrack.Length (en segundos).

  • No replicado
    Leer paralelo

    Devuelve la posición en el tiempo en segundos que un AnimationTrack está a través de jugar su animacionesfuente.Se puede configurar para hacer que la pista salte a un momento específico de la animaciones.

  • Solo lectura
    No replicado
    Leer paralelo

    Propiedad solo de lectura que proporciona el peso actual del AnimationTrack . Tiene un valor predeterminado de 1.

  • Solo lectura
    No replicado
    Leer paralelo

    Propiedad solo de lectura que proporciona el peso actual del AnimationTrack .

Métodos

Eventos

Propiedades

Animation

Solo lectura
No replicado
Leer paralelo

El objeto Animation que se utilizó para crear este AnimationTrack.Para crear un AnimationTrack , debe cargar un objeto Animation en un Animator usando el método Animator:LoadAnimation().

Muestras de código

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

Solo lectura
No replicado
Leer paralelo

Una propiedad solo de lectura que devuelve verdadero cuando el AnimationTrack está jugando.

Esta propiedad se puede usar por los desarrolladores para verificar si una animación ya se está reproduciendo antes de jugarla (ya que eso la haría reiniciar).Si un desarrollador desea obtener todo el juego AnimationTracks en un Animator o un Humanoid, debería usar Animator:GetPlayingAnimationTracks()

Muestras de código

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

Solo lectura
No replicado
Leer paralelo

Una propiedad de solo lectura que devuelve la longitud (en segundos) de un AnimationTrack .Esto devolverá 0 hasta que la animación se haya cargado completamente y, por lo tanto, puede que no esté disponible de inmediato.

Cuando el AnimationTrack.Speed de un AnimationTrack es igual a 1, la animación tardará AnimationTrack.Length (en segundos) en completarse.

Muestras de código

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

Leer paralelo

Esta propiedad establece si la animación se repetirá después de terminar.Si se cambia mientras se reproduce el resultado entrará en vigor después de que termine la animación.

La propiedad Looped para AnimationTrack predeterminada es cómo se estableció en el editor de animaciones.Sin embargo, esta propiedad se puede cambiar, permitiendo el control sobre el AnimationTrack mientras se ejecuta el juego.Looped también maneja correctamente las animaciones reproducidas en reversa (negativo AnimationTrack.Speed ).Después de que se alcance el primer marco clave, se reiniciará en el último fotograma clave.

Esta propiedad permite al desarrollador tener una variante de bucle y sin bucle de la misma animaciones, sin necesidad de subir dos versiones a Roblox.

Muestras de código

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)
Leer paralelo

Esta propiedad establece la prioridad de un AnimationTrack .Dependiendo de lo que esté configurado, jugar múltiples animaciones a la vez buscará esta propiedad para averiguar qué Class.Keyframe``Class.Pose|Poses debe reproducirse sobre la otra.

La propiedad de prioridad para AnimationTrack predeterminada es cómo se configuró y publicó desde el Editor de animación de Studio.Utiliza Enum.AnimationPriority que tiene 7 niveles de prioridad:

  1. Acción4 (prioridad más alta)
  2. Acción3
  3. Acción2
  4. Acción
  5. Movimiento
  6. Inactivo
  7. Núcleo ( prioridad más baja)

Establecer adecuadamente las prioridades de animación, ya sea a través del editor o a través de esta propiedad, permite que se reproducen múltiples animaciones sin que choquen.Cuando dos animaciones de reproducción dirijan al objetivo a mover la misma extremidad de diferentes maneras, la AnimationTrack con la mayor prioridad se mostrará.Si ambas animaciones tienen la misma prioridad, se usarán los pesos de las pistas para combinar las animaciones.

Esta propiedad también permite al desarrollador reproducir la misma animación en diferentes prioridades, sin necesidad de subir versiones adicionales a Roblox.

Speed

Solo lectura
No replicado
Leer paralelo

La velocidad de un AnimationTrack es una propiedad de solo lectura que proporciona la velocidad de reproducción actual del AnimationTrack .Esto tiene un valor predeterminado de 1.Cuando la velocidad es igual a 1, la cantidad de tiempo que tarda una animación en completarse es igual a AnimationTrack.Length (en segundos).

Si se ajusta la velocidad, entonces el tiempo real que tomará una pista para jugar se puede calcular dividiendo la longitud por la velocidad.La velocidad es una cantidad sin unidad.

La velocidad se puede utilizar para enlazar la duración de una animación a diferentes eventos del juego (por ejemplo, recargar una habilidad) sin tener que subir diferentes variantes de la misma animaciones.

Esta propiedad es solo de lectura y puedes cambiarla usando AnimationTrack:AdjustSpeed().

Muestras de código

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

No replicado
Leer paralelo

Devuelve la posición en el tiempo en segundos que un AnimationTrack está a través de jugar su animacionesfuente.Se puede configurar para hacer que la pista salte a un momento específico de la animaciones.

La posición del tiempo se puede establecer para ir a un punto específico de la animaciones, pero el AnimationTrack debe estar jugando para hacerlo.También se puede usar en combinación con AnimationTrack:AdjustSpeed() para congelar la animación en un punto deseado (al establecer la velocidad en 0).

Muestras de código

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

Solo lectura
No replicado
Leer paralelo

Cuando se establece el peso en un AnimationTrack no cambia instantáneamente, pero se mueve de WeightCurrent a AnimationTrack.WeightTarget .El tiempo que se tarda en hacer esto se determina por el parámetro fadeTime dado cuando se reproduce la animación o se ajusta el peso.

WeightCurrent se puede comprobar contra AnimationTrack.WeightTarget para ver si se ha alcanzado el peso deseado.Tenga en cuenta que estos valores no deben ser verificados por igualdad con el operador ==, ya que ambos de estos valores son flotantes.Para ver si WeightCurrent ha alcanzado el peso objetivo, se recomienda ver si la distancia entre esos valores es lo suficientemente pequeña (ver muestra de código a continuación).

El sistema de peso de animación se usa para determinar cómo AnimationTracks jugar con la misma prioridad se mezcla juntos.El peso predeterminado es uno, y no se verá movimiento en un AnimationTrack con un peso de cero.La postura que se muestra en cualquier momento se determina por el promedio ponderado de todos los Poses y el peso actual de cada AnimationTrack .En la mayoría de los casos, las animaciones de mezcla no son necesarias y usar AnimationTrack.Priority es más adecuado.

Muestras de código

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

Solo lectura
No replicado
Leer paralelo

AnimationTrack.WeightTarget es una propiedad de solo lectura que proporciona el peso actual del AnimationTrack .Tiene un valor predeterminado de 1 y se establece cuando se llama AnimationTrack:Play() , AnimationTrack:Stop() o AnimationTrack:AdjustWeight() .Cuando se establece el peso en un AnimationTrack no cambia instantáneamente, pero se mueve de WeightCurrent a AnimationTrack.WeightTarget .El tiempo que se tarda en hacer esto se determina por el parámetro fadeTime dado cuando se reproduce la animación o se ajusta el peso.

WeightCurrent se puede comprobar contra AnimationTrack.WeightTarget para ver si se ha alcanzado el peso deseado.Tenga en cuenta que estos valores no deben ser verificados por igualdad con el operador ==, ya que ambos de estos valores son flotantes.Para ver si WeightCurrent ha alcanzado el peso objetivo, se recomienda ver si la distancia entre esos valores es lo suficientemente pequeña (ver muestra de código a continuación).

El sistema de peso de animación se usa para determinar cómo AnimationTracks jugar con la misma prioridad se mezcla juntos.El peso predeterminado es uno, y no se verá movimiento en un AnimationTrack con un peso de cero.La postura que se muestra en cualquier momento se determina por el promedio ponderado de todos los Poses y el peso actual de cada AnimationTrack .En la mayoría de los casos, las animaciones de mezcla no son necesarias y usar AnimationTrack.Priority es más adecuado.

Muestras de código

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étodos

AdjustSpeed

()

Esta función cambia el AnimationTrack.Speed de una animaciones.Un valor positivo para la velocidad reproduce la animación hacia adelante, uno negativo la reproducen hacia atrás y 0 la detiene.

La velocidad inicial de una pista de animación se establece como un parámetro en AnimationTrack:Play() .Sin embargo, la velocidad de una pista se puede cambiar durante la reproducción, usando AdjustSpeed.Cuando la velocidad es igual a 1, la cantidad de tiempo que tarda una animación en completarse es igual a AnimationTrack.Length (en segundos).

Cuándo se ajusta, entonces el tiempo real que tomará una pista para jugar se puede calcular dividiendo la longitud por la velocidad. La velocidad es una cantidad sin unidad.

La velocidad se puede utilizar para enlazar la duración de una animación a diferentes eventos de juego (por ejemplo, recargar una habilidad) sin tener que subir diferentes variantes de la misma animaciones.

Parámetros

speed: number

La velocidad de reproducción que la animación debe cambiarse a.

Valor predeterminado: 1

Devuelve

()

Muestras de código

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

()

Cambia el peso de una animaciones, con el parámetro opcional fadeTime determinando cuánto tiempo tarda AnimationTrack.WeightCurrent en llegar a AnimationTrack.WeightTarget .

Cuando se establece el peso en un AnimationTrack no cambia instantáneamente, pero se mueve de WeightCurrent a AnimationTrack.WeightTarget .El tiempo que se tarda en hacer esto se determina por el parámetro fadeTime dado cuando se reproduce la animación o se ajusta el peso.

WeightCurrent se puede comprobar contra AnimationTrack.WeightTarget para ver si se ha alcanzado el peso deseado.Tenga en cuenta que estos valores no deben ser verificados por igualdad con el operador ==, ya que ambos de estos valores son flotantes.Para ver si WeightCurrent ha alcanzado el peso objetivo, se recomienda ver si la distancia entre esos valores es lo suficientemente pequeña (ver muestra de código a continuación).

El sistema de peso de animación se usa para determinar cómo AnimationTracks jugar con la misma prioridad se mezcla juntos.El peso predeterminado es uno, y no se verá movimiento en un AnimationTrack con un peso de cero.La postura que se muestra en cualquier momento se determina por el promedio ponderado de todos los Poses y el peso actual de cada AnimationTrack .Vea a continuación un ejemplo de mezcla de animación en la práctica.En la mayoría de los casos, las animaciones de mezcla no son necesarias y usar AnimationTrack.Priority es más adecuado.

Parámetros

weight: number

El peso que la animación debe cambiar a.

Valor predeterminado: 1
fadeTime: number

La duración del tiempo que la animación desaparecerá entre el peso antiguo y el nuevo peso por.

Valor predeterminado: 0.100000001

Devuelve

()

Muestras de código

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

Esta función devuelve un event similar al evento AnimationTrack.KeyframeReached, excepto que solo se activa cuando se ha golpeado un KeyframeMarker específico en un animation .La diferencia permite un mayor control de cuándo se desencadenarel evento.

Para aprender más sobre el uso de esta función, vea Eventos de animación en el artículo Editor de animación.

Más sobre marcos clave

nombres se pueden establecer en el Editor de animaciones de Roblox cuando se crea o edita una animación.Sin embargo, no se pueden configurar por un Script en una animación existente antes de jugarla.

Keyframe los nombres no necesitan ser únicos.Por ejemplo, si un Animation tiene tres marcos clave llamados "EmitParticles", el evento conectado devuelto por esta función se disparará cada vez que se alcance uno de estos marcos clave.

Vea también:

Parámetros

name: string

El nombre del KeyFrameMarker la señal está siendo creado para.

Valor predeterminado: ""

Devuelve

La señal creada y disparada cuando la animación llega al creado KeyFrameMarker .

Muestras de código

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

Parámetros

name: string
Valor predeterminado: ""

Devuelve

GetTargetNames


Devuelve

GetTimeOfKeyframe

Devuelve la posición del tiempo del primer Keyframe del nombre dado en un AnimationTrack .Si varios Keyframes comparten el mismo nombre, devolverá el más antiguo en la animaciones.

Esta función devolverá un error si se usa con un nombre de marco de clave inválido (uno que no existe por ejemplo) o si el subyacente Animation no se ha cargado aún.Para abordar esto, asegúrese de que solo se usen nombres de marco de clave correctos y que la animación se haya cargado antes de llamar a esta función.

Para verificar si la animación se ha cargado, verifique que el AnimationTrack.Length es mayor que cero.

Parámetros

keyframeName: string

El nombre asociado con el Keyframe para encontrar.

Valor predeterminado: ""

Devuelve

El tiempo, en segundos, el Keyframe ocurre a la velocidad de reproducción normal.

Muestras de código

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

()

Cuando AnimationTrack:Play() se llama la animación de la pista comenzará a reproducirse y el peso de la animación aumentará de 0 a el peso especificado (默认值为 1) durante el tiempo de desaparición especificado (默认值为 0.1).

La velocidad a la que jugará el AnimationTrack se determina por el parámetro de velocidad (默认值为 1).Cuando la velocidad es igual a 1, el número de segundos que tomará completar la pista es igual a la propiedad AnimationTrack.Length de la pista.Por ejemplo, una velocidad de 2 causará que la pista se reproduzca el doble de rápido.

El peso y la velocidad de la animación también se pueden cambiar después de que la animación haya comenzado a jugar usando los métodos AnimationTrack:AdjustWeight() y AnimationTrack:AdjustSpeed().

Si el desarrollador quiere comenzar la animación en un punto específico usando AnimationTrack.TimePosition, es importante que la animación se reproduzca antes de que esto se haga.

Parámetros

fadeTime: number

La duración del tiempo que el peso de la animacionesdebe desaparecer durante.

Valor predeterminado: 0.100000001
weight: number

El peso que la animación debe jugar.

Valor predeterminado: 1
speed: number

La velocidad de reproducción de la animaciones.

Valor predeterminado: 1

Devuelve

()

Muestras de código

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

()

Parámetros

name: string
Valor predeterminado: ""
target: Instance
Valor predeterminado: ""

Devuelve

()

Stop

()

Detiene el AnimationTrack.Una vez llamado, el peso de la animación se moverá hacia cero durante un período de tiempo especificado por el parámetro opcional fadeTime.Por ejemplo, si Stop() se llama con un fadeTime de 2 , tomará dos segundos que el peso de la pista llegue a cero y sus efectos finalizarcompletamente.Tenga en cuenta que este será el caso independientemente del peso inicial de la animaciones.

No se recomienda usar un fadeTime de 0 en un intento de anular este efecto y terminar la animación inmediatamente para Motor6Ds que tengan su Motor.MaxVelocity establecido a cero, ya que esto hace que las articulaciones se congelen en su lugar.Si debe terminar inmediatamente, asegúrese de que el Motor.MaxVelocity de Motor6Ds en su rig sea lo suficientemente alto como para que se ajusten correctamente.

Parámetros

fadeTime: number

El tiempo, en segundos, para el cual se debe difuminar el peso de la animación.

Valor predeterminado: 0.100000001

Devuelve

()

Muestras de código

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)

Eventos

DidLoop

Este evento se activa cada vez que un bucle AnimationTrack completa un bucle, en la próxima actualización.

Actualmente también puede disparar al final exacto de una pista de animación no repetitiva, pero este comportamiento no debe confiarse.


Muestras de código

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

Se enciende cuando el AnimationTrack está completamente terminado de mover cualquier cosa en el mundo.La animación ha terminado de jugar, la "desaparición" está terminada y el tema está en una posición neutral.

Puedes usar esto para tomar acción cuando el sujeto de la pista de animación regrese en una posición neutral que no sea afectada por el AnimationTrack o para limpiar el AnimationTrack .o cualquier conexión asociada.


Muestras de código

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

Se incendia cada vez que se reproduce un AnimationTrack que alcanza un Keyframe que no tiene el nombre predeterminado - "Keyframe".

Este evento permite que un desarrollador ejecute código en puntos predefinidos en una animación (definidos por Keyframe nombres).Esto permite que la funcionalidad predeterminada de las animaciones de Roblox se expanda agregando Sounds o ParticleEffects en diferentes puntos de una animación.

Keyframe los nombres no necesitan ser únicos.Por ejemplo, si una animación tiene tres marcos clave llamados "Partículas", el evento KeyframeReached se disparará cada vez que se alcance uno de estos marcos clave.

Keyframe los nombres se pueden establecer en el Editor de animación de Roblox al crear o editar una animaciones.Sin embargo, no se pueden establecer por un Script en una animación existente antes de jugarla.

Parámetros

keyframeName: string

Se ha alcanzado el nombre de la Keyframe alcanzada.


Stopped

Se enciende cada vez que el AnimationTrack termina de jugar.

Este evento tiene una serie de usos.Se puede usar para esperar hasta que un AnimationTrack haya terminado antes de continuar (por ejemplo, si encadena una serie de animaciones para jugar después de unas otras).También se puede usar para limpiar cualquier Instances creado durante la reproducción de la animación.


Muestras de código

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)