AnimationTrack

Mostrar obsoleto

*Este conteúdo é traduzido por IA (Beta) e pode conter erros. Para ver a página em inglês, clique aqui.

Não criável

Controla a reprodução de uma animação em um Animator . Este objeto não pode ser criado, em vez disso, é retornado pelo método Animator:LoadAnimation().

Resumo

Propriedades

  • Somente leitura
    Não replicado
    Ler Parallel

    O objeto Animation que foi usado para criar este AnimationTrack.

  • Somente leitura
    Não replicado
    Ler Parallel

    Uma propriedade apenas de leitura que retorna verdadeiro quando o AnimationTrack está tocando.

  • Somente leitura
    Não replicado
    Ler Parallel

    Uma propriedade apenas de leitura que retorna o comprimento (em segundos) de um AnimationTrack .Isso retornará 0 até que a animação tenha sido totalmente carregada e, portanto, pode não estar imediatamente disponível.

  • Ler Parallel

    Define se a animação vai se repetir após terminar. Se for alterada enquanto se joga, a animação terminará depois que o resultado entrar em vigor.

  • Define a prioridade de um AnimationTrack .Dependendo do que está definido, jogar várias animações de uma só vez buscará essa propriedade para descobrir qual Class.Keyframe``Class.Pose|Poses deve ser reproduzida sobre a outra.

  • Somente leitura
    Não replicado
    Ler Parallel

    A velocidade de um AnimationTrack é uma propriedade apenas de leitura que dá a velocidade de reprodução atual do AnimationTrack .Isso tem um valor padrão de 1.Quando a velocidade é igual a 1, a quantidade de tempo que uma animação leva para concluir é igual a AnimationTrack.Length (em segundos).

  • Não replicado
    Ler Parallel

    Retorna a posição no tempo em segundos que um AnimationTrack está através de jogar sua animaçõesde origem.Pode ser definido para fazer o pulo da trilha para um momento específico na animações.

  • Somente leitura
    Não replicado
    Ler Parallel

    Propriedade apenas de leitura que dá o peso atual do AnimationTrack. Tem um valor padrão de 1.

  • Somente leitura
    Não replicado
    Ler Parallel

    Propriedade apenas de leitura que dá o peso atual do AnimationTrack.

Métodos

Eventos

Propriedades

Animation

Somente leitura
Não replicado
Ler Parallel

O objeto Animation que foi usado para criar este AnimationTrack.Para criar um AnimationTrack , você deve carregar um objeto Animation em um Animator usando o método Animator:LoadAnimation().

Amostras 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

Somente leitura
Não replicado
Ler Parallel

Uma propriedade apenas de leitura que retorna verdadeiro quando o AnimationTrack está tocando.

Essa propriedade pode ser usada por desenvolvedores para verificar se uma animação já está sendo reproduzida antes de reproduzi-la (pois isso faria com que ela reiniciar).Se um desenvolvedor deseja obter todo o jogo AnimationTracks em um Animator ou um Humanoid, eles devem usar Animator:GetPlayingAnimationTracks()

Amostras 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

Somente leitura
Não replicado
Ler Parallel

Uma propriedade apenas de leitura que retorna o comprimento (em segundos) de um AnimationTrack .Isso retornará 0 até que a animação tenha sido totalmente carregada e, portanto, pode não estar imediatamente disponível.

Quando o AnimationTrack.Speed de um AnimationTrack é igual a 1, a animação levará AnimationTrack.Length (em segundos) para concluir.

Amostras 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

Ler Parallel

Essa propriedade define se a animação vai se repetir após terminar.Se for alterado enquanto se joga, o resultado terá efeito após a animação terminar.

A propriedade Looped para AnimationTrack padrão é como foi definida no editor de animação.No entanto, esta propriedade pode ser alterada, permitindo o controle sobre o AnimationTrack enquanto o jogo está em execução.Looped também lida corretamente as animações tocadas em reverso (negativo AnimationTrack.Speed ).Depois que o primeiro keyframe for alcançado, ele será reiniciado no último keyframe.

Essa propriedade permite que o desenvolvedor tenha uma variante de loop e não loop da mesma animações, sem precisar carregar duas versões no Roblox.

Amostras 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)
Ler Parallel

Essa propriedade define a prioridade de um AnimationTrack .Dependendo do que está definido, jogar várias animações de uma só vez buscará essa propriedade para descobrir qual Class.Keyframe``Class.Pose|Poses deve ser reproduzida sobre a outra.

A propriedade de prioridade para padrão é como foi definida e publicada no Editor de Animação do Studio .Ela usa Enum.AnimationPriority que tem 7 níveis de prioridade:

  1. Ação4 (maior prioridade)
  2. Ação3
  3. Ação2
  4. Ação
  5. Movimento
  6. Ocioso
  7. Núcleo (prioridade mais baixa)

Definir prioridades de animação adequadamente, seja através do editor ou através dessa propriedade, permite que várias animações sejam reproduzidas sem elas entrarem em conflito.Quando duas animações de reprodução direcionam o alvo para mover a mesma extremidade de maneiras diferentes, a AnimationTrack com a maior prioridade exibir / mostrar.Se ambas as animações tiverem a mesma prioridade, os pesos das faixas serão usados para combinar as animações.

Essa propriedade também permite que o desenvolvedor execute a mesma animação em diferentes prioridades, sem precisar carregar versões adicionais no Roblox.

Speed

Somente leitura
Não replicado
Ler Parallel

A velocidade de um AnimationTrack é uma propriedade apenas de leitura que dá a velocidade de reprodução atual do AnimationTrack .Isso tem um valor padrão de 1.Quando a velocidade é igual a 1, a quantidade de tempo que uma animação leva para concluir é igual a AnimationTrack.Length (em segundos).

Se a velocidade for ajustada, então o tempo real que levará para uma pista tocar pode ser calculado dividindo a duração pela velocidade.Velocidade é uma quantidade sem unidade.

A velocidade pode ser usada para vincular o comprimento de uma animação a diferentes eventos de jogo (por exemplo, recarregar uma habilidade) sem ter que carregar diferentes variantes da mesma animações.

Essa propriedade é apenas de leitura e você pode alterá-la usando AnimationTrack:AdjustSpeed().

Amostras 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

Não replicado
Ler Parallel

Retorna a posição no tempo em segundos que um AnimationTrack está através de jogar sua animaçõesde origem.Pode ser definido para fazer o pulo da trilha para um momento específico na animações.

A posição do tempo pode ser definida para ir a um ponto específico na animações, mas o AnimationTrack deve estar tocando para fazer isso.Também pode ser usado em combinação com AnimationTrack:AdjustSpeed() para congelar a animação em um ponto desejado (definindo a velocidade para 0).

Amostras 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

Somente leitura
Não replicado
Ler Parallel

Quando o peso é definido em um AnimationTrack não muda instantaneamente, mas move-se de PesoAtual para AnimationTrack.WeightTarget .O tempo que leva para fazer isso é determinado pelo parâmetro fadeTime dado quando a animação é reproduzida ou o peso é ajustado.

O WeightCurrent pode ser verificado contra AnimationTrack.WeightTarget para ver se o peso desejado foi atingido.Observe que esses valores não devem ser verificados por igualdade com o operador ==, pois ambos esses valores são flutuantes.Para ver se WeightCurrent atingiu o peso alvo, é recomendado verificar se a distância entre esses valores é suficientemente pequena (veja amostra de código abaixo).

O sistema de peso de animação é usado para determinar como AnimationTracks jogar com a mesma prioridade são misturados juntos.O peso padrão é um, e nenhum movimento será visível em um AnimationTrack com peso de zero.A posição que é mostrada em qualquer momento é determinada pela média ponderada de todos os Poses e o PesoAtual de cada AnimationTrack.Na maioria dos casos, não é necessário misturar animações e usar AnimationTrack.Priority é mais adequado.

Amostras 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

Somente leitura
Não replicado
Ler Parallel

AnimaçãoTrack.WeightTarget é uma propriedade de leitura somente que dá o peso atual do AnimationTrack.Ela tem um valor padrão de 1 e é definida quando AnimationTrack:Play() , AnimationTrack:Stop() ou AnimationTrack:AdjustWeight() é chamada.Quando o peso é definido em um AnimationTrack ele não muda instantaneamente, mas move-se de PesoAtual para AnimationTrack.WeightTarget.O tempo que leva para fazer isso é determinado pelo parâmetro fadeTime dado quando a animação é reproduzida ou o peso é ajustado.

O WeightCurrent pode ser verificado contra AnimationTrack.WeightTarget para ver se o peso desejado foi atingido.Observe que esses valores não devem ser verificados por igualdade com o operador ==, pois ambos esses valores são flutuantes.Para ver se WeightCurrent atingiu o peso alvo, é recomendado verificar se a distância entre esses valores é suficientemente pequena (veja amostra de código abaixo).

O sistema de peso de animação é usado para determinar como AnimationTracks jogar com a mesma prioridade são misturados juntos.O peso padrão é um, e nenhum movimento será visível em um AnimationTrack com peso de zero.A posição que é mostrada em qualquer momento é determinada pela média ponderada de todos os Poses e o PesoAtual de cada AnimationTrack.Na maioria dos casos, não é necessário misturar animações e usar AnimationTrack.Priority é mais adequado.

Amostras 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

()

Essa função altera o AnimationTrack.Speed de uma animações.Um valor positivo para velocidade joga a animação para frente, um negativo a faz avançar e 0 a pausa.

A velocidade inicial de uma Trilha de Animação é definida como um parâmetro em AnimationTrack:Play() .No entanto, a velocidade de uma faixa pode ser alterada durante a reprodução, usando AdjustSpeed.Quando a velocidade é igual a 1, a quantidade de tempo que uma animação leva para completar é igual a AnimationTrack.Length (em segundos).

Quando é ajustado, então o tempo real que levará para uma pista tocar pode ser calculado dividindo a duração pela velocidade. A velocidade é uma quantidade sem unidade.

A velocidade pode ser usada para vincular a duração de uma animação a diferentes eventos de jogabilidade (por exemplo, recarregar uma habilidade) sem ter que carregar diferentes variantes da mesma animações.

Parâmetros

speed: number

A velocidade de reprodução da animação que deve ser alterada.

Valor Padrão: 1

Devolução

()

Amostras 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

()

Muda o peso de uma animações, com o parâmetro fadeTime opcional determinando quanto tempo leva para AnimationTrack.WeightCurrent alcançar AnimationTrack.WeightTarget.

Quando o peso é definido em um AnimationTrack não muda instantaneamente, mas move-se de PesoAtual para AnimationTrack.WeightTarget .O tempo que leva para fazer isso é determinado pelo parâmetro fadeTime dado quando a animação é reproduzida ou o peso é ajustado.

O WeightCurrent pode ser verificado contra AnimationTrack.WeightTarget para ver se o peso desejado foi atingido.Observe que esses valores não devem ser verificados por igualdade com o operador ==, pois ambos esses valores são flutuantes.Para ver se WeightCurrent atingiu o peso alvo, é recomendado verificar se a distância entre esses valores é suficientemente pequena (veja amostra de código abaixo).

O sistema de peso de animação é usado para determinar como AnimationTracks jogar com a mesma prioridade são misturados juntos.O peso padrão é um, e nenhum movimento será visível em um AnimationTrack com peso de zero.A posição que é mostrada em qualquer momento é determinada pela média ponderada de todos os Poses e o PesoAtual de cada AnimationTrack.Veja abaixo um exemplo de fusão de animação na prática.Na maioria dos casos, não é necessário misturar animações e usar AnimationTrack.Priority é mais adequado.

Parâmetros

weight: number

O peso que a animação deve ser alterado para.

Valor Padrão: 1
fadeTime: number

A duração do tempo que a animação desaparecerá entre o peso antigo e o novo peso para.

Valor Padrão: 0.100000001

Devolução

()

Amostras 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

Essa função retorna um event semelhante ao evento AnimationTrack.KeyframeReached, exceto que só é acionada quando um KeyframeMarker especificado for atingido em um animation .A diferença permite um maior controle de quando o evento será Iniciar / executar.

Para aprender mais sobre o uso dessa função, veja Eventos de Animação no artigo Editor de Animação.

Mais sobre quadros-chave

Keyframe nomes podem ser definidos no Roblox Editor de Animação ao criar ou editar uma animaçõesentanto, eles não podem ser definidos por um Script em uma animação existente antes de tocá-la.

Keyframe nomes não precisam ser únicos.Por exemplo, se um Animation tiver três keyframes chamados "EmitParticles", o evento conectado retornado por essa função disparará sempre que um desses keyframes for alcançado.

Veja também:

Parâmetros

name: string

O nome do sinal KeyFrameMarker que está sendo criado.

Valor Padrão: ""

Devolução

O sinal criado e disparado quando a animação chegar ao criado KeyFrameMarker.

Amostras 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 Padrão: ""

Devolução

GetTargetNames


Devolução

GetTimeOfKeyframe

Retorna a posição do tempo do primeiro Keyframe do nome dado em um AnimationTrack .Se vários Keyframes compartilharem o mesmo nome, ele retornará o mais antigo na animações.

Essa função retornará um erro se for usada com um nome de quadro de chave inválido (um que não existe, por exemplo) ou se o subjacente Animation ainda não foi carregado.Para abordar isso, certifique-se de que apenas nomes de quadro de chave corretos são usados e a animação foi carregada antes de chamar essa função.

Para verificar se a animação foi carregada, verifique se o AnimationTrack.Length é maior que zero.

Parâmetros

keyframeName: string

O nome associado ao Keyframe a ser encontrado.

Valor Padrão: ""

Devolução

O tempo, em segundos, o Keyframe ocorre na velocidade de reprodução normal.

Amostras 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

()

Quando AnimationTrack:Play() é chamada, a animação da faixa começará a tocar e o peso da animação aumentará de 0 para o peso especificado (padrão é 1) sobre o tempo de desaparecimento especificado (padrão é 0.1).

A velocidade em que o AnimationTrack tocará é determinada pelo parâmetro de velocidade (padrão é 1).Quando a velocidade é igual a 1, o número de segundos que a faixa levará para completar é igual à propriedade da faixa AnimationTrack.Length .Por exemplo, uma velocidade de 2 fará com que a pista seja reproduzida duas vezes mais rápido.

O peso e a velocidade da animação também podem ser alterados após a animação começar a tocar usando os métodos AnimationTrack:AdjustWeight() e AnimationTrack:AdjustSpeed().

Se o desenvolvedor quiser iniciar a animação em um ponto específico usando AnimationTrack.TimePosition, é importante que a animação seja reproduzida antes que isso seja feito.

Parâmetros

fadeTime: number

A duração do tempo que o peso da animaçõesdeve desaparecer por.

Valor Padrão: 0.100000001
weight: number

O peso que a animação deve ser tocada.

Valor Padrão: 1
speed: number

A velocidade de reprodução da animações.

Valor Padrão: 1

Devolução

()

Amostras 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 Padrão: ""
target: Instance
Valor Padrão: ""

Devolução

()

Stop

()

Para o AnimationTrack.Uma vez chamada, o peso da animação se moverá para zero ao longo de um período de tempo especificado pelo parâmetro opcional fadeTime.Por exemplo, se Stop() for chamado com um fadeTime de 2 , levará dois segundos para o peso da trilha atingir zero e seus efeitos terminar/parar/saircompletamente.Observe que esse será o caso, independentemente do peso inicial da animações.

Não é recomendado usar um fadeTime de 0 em uma tentativa de anular esse efeito e terminar a animação imediatamente para Motor6Ds que têm seu Motor.MaxVelocity definido para zero, pois isso faz com que as articulações congelem no local.Se deve terminar imediatamente, garanta que o Motor.MaxVelocity de Motor6Ds em seu rig seja alto o suficiente para que eles se encaixem corretamente.

Parâmetros

fadeTime: number

O tempo, em segundos, para o qual o peso da animação deve ser desaparecido.

Valor Padrão: 0.100000001

Devolução

()

Amostras 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 dispara sempre que um ciclo AnimationTrack completa um ciclo, na próxima atualização.

Atualmente, também pode atirar no final exato de uma faixa de animação não loopada, mas esse comportamento não deve ser confiável.


Amostras 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

Incêndios quando o AnimationTrack está completamente feito de mover qualquer coisa no mundo.A animação terminou de tocar, o "desaparecimento" está terminado e o assunto está em uma posição neutra.

Você pode usar isso para tomar medidas quando o assunto da trilha de animação está de volta em uma posição neutra que não é afetada pelo AnimationTrack ou para limpar o AnimationTrack.ou quaisquer conexões associadas.


Amostras 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

Incêndios sempre que a reprodução de um AnimationTrack alcança um Keyframe que não tem o nome padrão - "Keyframe".

Este evento permite que um desenvolvedor execute código em pontos predefinidos em uma animação (definidos por Keyframe nomes).Isso permite que a funcionalidade padrão das animações do Roblox seja expandida adicionando Sounds ou ParticleEffects em diferentes pontos de uma animação.

Keyframe nomes não precisam ser únicos.Por exemplo, se uma Animação tiver três quadros-chave chamados "Partículas", o evento KeyframeReached será disparado sempre que um desses quadros-chave for alcançado.

Keyframe nomes podem ser definidos no Editor de Animação Roblox ao criar ou editar uma animações.No entanto, eles não podem ser definidos por um Script em uma animação existente antes de tocá-la.

Parâmetros

keyframeName: string

O nome do Keyframe alcançado.


Stopped

Incêndios sempre que o AnimationTrack termina de tocar.

Este evento tem uma série de usos.Pode ser usado para esperar até que um AnimationTrack tenha parado antes de continuar (por exemplo, se encadear uma série de animações para tocar após umas das outras).Também pode ser usado para limpar qualquer Instances criado durante a reprodução da animação.


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