TweenService

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
Serviço

TweenService é usado para criar Tweens que interpolam ou interseçãoas propriedades das instâncias.Tweens pode ser usado em qualquer objeto com tipos de propriedade compatíveis, incluindo:

TweenService:Create() , a função de construtor primário, toma TweenInfo especificações sobre o pré-adolescente e gera o objeto Tween que pode então ser usado para jogar o interseção.

Observe que Tweens pode interpolar várias propriedades ao mesmo tempo, mas elas não devem estar interpolando a mesma propriedade.Se dois adolescentes tentarem modificar a mesma propriedade, o tween inicial será cancelado e substituído pelo interseçãomais recente.

Amostras de código

In this example a Tween is created to animate the position and color of a Part. Because the position and color are part of the same tween, they will change at the exact same rate and will reach their goal at the same time.

Tween Creation

local TweenService = game:GetService("TweenService")
local part = Instance.new("Part")
part.Position = Vector3.new(0, 10, 0)
part.Color = Color3.new(1, 0, 0)
part.Anchored = true
part.Parent = game.Workspace
local goal = {}
goal.Position = Vector3.new(10, 10, 0)
goal.Color = Color3.new(0, 1, 0)
local tweenInfo = TweenInfo.new(5)
local tween = TweenService:Create(part, tweenInfo, goal)
tween:Play()

This code sample includes an example of how a looped tween can be created. A part is instanced in the Workspace and a Tween is created using TweenService:Create() that is set to animate its position along the Y axis.

The looped effect is achieved by modifying the TweenInfo used in TweenService:Create(). Specifically, when RepeatCount is set to less than 0, the tween will play indefinitely. Also, setting Reverses to true will cause the tween to play in reverse once it has reached its destination. In combination this creates a looped effect.

The correct way to make a tween play indefinitely is to set RepeatCount to -1. You should avoid using large numbers or math.huge() as a substitute as this is unstable and may stop working at any point.

Looping a Tween

local TweenService = game:GetService("TweenService")
local part = Instance.new("Part")
part.Position = Vector3.new(0, 10, 0)
part.Anchored = true
part.Parent = workspace
local tweenInfo = TweenInfo.new(
2, -- Time
Enum.EasingStyle.Linear, -- EasingStyle
Enum.EasingDirection.Out, -- EasingDirection
-1, -- RepeatCount (when less than zero the tween will loop indefinitely)
true, -- Reverses (tween will reverse once reaching its goal)
0 -- DelayTime
)
local tween = TweenService:Create(part, tweenInfo, { Position = Vector3.new(0, 30, 0) })
tween:Play()
task.wait(10)
tween:Cancel() -- cancel the animation after 10 seconds

This sample demonstrates how the playback of a tween can be paused and resumed.

A part is instanced in the Workspace and a tween is setup that will move it 50 studs along the X axis. However during playback the tween is briefly paused, then resumed. To further illustrate this the BrickColor of the part changes from red to green while it is paused.

Pausing a Tween

local TweenService = game:GetService("TweenService")
local part = Instance.new("Part")
part.Position = Vector3.new(0, 10, 0)
part.Anchored = true
part.BrickColor = BrickColor.new("Bright green")
part.Parent = workspace
local goal = {}
goal.Position = Vector3.new(50, 10, 0)
local tweenInfo = TweenInfo.new(10, Enum.EasingStyle.Linear)
local tween = TweenService:Create(part, tweenInfo, goal)
tween:Play()
task.wait(3)
part.BrickColor = BrickColor.new("Bright red")
tween:Pause()
task.wait(2)
part.BrickColor = BrickColor.new("Bright green")
tween:Play()

Resumo

Métodos

Propriedades

Métodos

Create

Este construtor cria um novo Tween de três argumentos: o objeto para interseção, as especificações TweenInfo específicas e uma tabela que contém as propriedades para transicionar e os valores para transicionar.

O parâmetro propertyTable precisa ser um dicionário onde as chaves são os nomes das strings da propriedade (por exemplo Position , Transparency ou Color ), e os valores são os alvos da propriedade no final do interseção.

O Tween criado usando essa função é único para o objeto dado como o parâmetro instance.Para aplicar o mesmo pré-adolescente a outro Objeto, chame novamente essa função com o novo Objeto.

Parâmetros

instance: Instance

O Instance cujas propriedades devem ser transicionadas.

Valor Padrão: ""
tweenInfo: TweenInfo

O TweenInfo a ser usado.

Valor Padrão: ""
propertyTable: Dictionary

Um dicionário de propriedades e seus valores alvo, para serem transicionados.

Valor Padrão: ""

Devolução

Amostras de código

In this example a Tween is created to animate the position and color of a Part. Because the position and color are part of the same tween, they will change at the exact same rate and will reach their goal at the same time.

Tween Creation

local TweenService = game:GetService("TweenService")
local part = Instance.new("Part")
part.Position = Vector3.new(0, 10, 0)
part.Color = Color3.new(1, 0, 0)
part.Anchored = true
part.Parent = game.Workspace
local goal = {}
goal.Position = Vector3.new(10, 10, 0)
goal.Color = Color3.new(0, 1, 0)
local tweenInfo = TweenInfo.new(5)
local tween = TweenService:Create(part, tweenInfo, goal)
tween:Play()

This code sample includes an example of how a looped tween can be created. A part is instanced in the Workspace and a Tween is created using TweenService:Create() that is set to animate its position along the Y axis.

The looped effect is achieved by modifying the TweenInfo used in TweenService:Create(). Specifically, when RepeatCount is set to less than 0, the tween will play indefinitely. Also, setting Reverses to true will cause the tween to play in reverse once it has reached its destination. In combination this creates a looped effect.

The correct way to make a tween play indefinitely is to set RepeatCount to -1. You should avoid using large numbers or math.huge() as a substitute as this is unstable and may stop working at any point.

Looping a Tween

local TweenService = game:GetService("TweenService")
local part = Instance.new("Part")
part.Position = Vector3.new(0, 10, 0)
part.Anchored = true
part.Parent = workspace
local tweenInfo = TweenInfo.new(
2, -- Time
Enum.EasingStyle.Linear, -- EasingStyle
Enum.EasingDirection.Out, -- EasingDirection
-1, -- RepeatCount (when less than zero the tween will loop indefinitely)
true, -- Reverses (tween will reverse once reaching its goal)
0 -- DelayTime
)
local tween = TweenService:Create(part, tweenInfo, { Position = Vector3.new(0, 30, 0) })
tween:Play()
task.wait(10)
tween:Cancel() -- cancel the animation after 10 seconds

GetValue

Retorna um novo valor alfa para interpolação usando o valor alfa dado, Enum.EasingStyle e Enum.EasingDirection.O valor fornecido alpha será clampado entre 0 e 1.

Parâmetros

alpha: number

Um valor de interpolação entre 0 e 1.

Valor Padrão: ""
easingStyle: Enum.EasingStyle

O estilo de relaxamento para usar.

Valor Padrão: ""
easingDirection: Enum.EasingDirection

A direção de relaxamento para usar.

Valor Padrão: ""

Devolução

Um novo valor alfa gerado a partir do estilo e direção de alívio dados.

SmoothDamp

Escrever Parallel

Retorna um tuple que permite suavizar um valor em direção a um alvo, simulando uma mola críticamente amortecida.Suporta Vector2 , Vector3 , CFrame e número.

Parâmetros

current: Variant

A posição atual.

Valor Padrão: ""
target: Variant

A posição alvo.

Valor Padrão: ""
velocity: Variant

A velocidade inicial em que a posição atual deve se aproximar da posição alvo.

Valor Padrão: ""
smoothTime: number

A duração em que a operação de suavização total deve local.

Valor Padrão: ""
maxSpeed: number

A velocidade máxima em que a posição atual deve se aproximar da posição alvo.

Valor Padrão: ""
dt: number

A taxa em que a operação de suavização deve ser aplicada.

Valor Padrão: ""

Devolução

A nova posição e velocidade calculada a partir da operação de suavização.

Eventos