Class Tween
- Namespace
- Godot
- Assembly
- GodotSharp.dll
Tweens are mostly useful for animations requiring a numerical property to be interpolated over a range of values. The name tween comes from in-betweening, an animation technique where you specify keyframes and the computer interpolates the frames that appear between them. Animating something with a Tween is called tweening.
Tween is more suited than AnimationPlayer for animations where you don't know the final values in advance. For example, interpolating a dynamically-chosen camera zoom value is best done with a Tween; it would be difficult to do the same thing with an AnimationPlayer node. Tweens are also more light-weight than AnimationPlayer, so they are very much suited for simple animations or general tasks that don't require visual tweaking provided by the editor. They can be used in a "fire-and-forget" manner for some logic that normally would be done by code. You can e.g. make something shoot periodically by using a looped CallbackTweener with a delay.
A Tween can be created by using either CreateTween() or CreateTween(). Tweens created manually (i.e. by using Tween.new()
) are invalid and can't be used for tweening values.
A tween animation is created by adding Tweeners to the Tween object, using TweenProperty(GodotObject, NodePath, Variant, double), TweenInterval(double), TweenCallback(Callable) or TweenMethod(Callable, Variant, Variant, double):
Tween tween = GetTree().CreateTween();
tween.TweenProperty(GetNode("Sprite"), "modulate", Colors.Red, 1.0f);
tween.TweenProperty(GetNode("Sprite"), "scale", Vector2.Zero, 1.0f);
tween.TweenCallback(Callable.From(GetNode("Sprite").QueueFree));
This sequence will make the $Sprite
node turn red, then shrink, before finally calling QueueFree() to free the sprite. Tweeners are executed one after another by default. This behavior can be changed using Parallel() and SetParallel(bool).
When a Tweener is created with one of the tween_*
methods, a chained method call can be used to tweak the properties of this Tweener. For example, if you want to set a different transition type in the above example, you can use SetTrans(TransitionType):
Tween tween = GetTree().CreateTween();
tween.TweenProperty(GetNode("Sprite"), "modulate", Colors.Red, 1.0f).SetTrans(Tween.TransitionType.Sine);
tween.TweenProperty(GetNode("Sprite"), "scale", Vector2.Zero, 1.0f).SetTrans(Tween.TransitionType.Bounce);
tween.TweenCallback(Callable.From(GetNode("Sprite").QueueFree));
Most of the Tween methods can be chained this way too. In the following example the Tween is bound to the running script's node and a default transition is set for its Tweeners:
var tween = GetTree().CreateTween().BindNode(this).SetTrans(Tween.TransitionType.Elastic);
tween.TweenProperty(GetNode("Sprite"), "modulate", Colors.Red, 1.0f);
tween.TweenProperty(GetNode("Sprite"), "scale", Vector2.Zero, 1.0f);
tween.TweenCallback(Callable.From(GetNode("Sprite").QueueFree));
Another interesting use for Tweens is animating arbitrary sets of objects:
Tween tween = CreateTween();
foreach (Node sprite in GetChildren())
tween.TweenProperty(sprite, "position", Vector2.Zero, 1.0f);
In the example above, all children of a node are moved one after another to position (0, 0).
You should avoid using more than one Tween per object's property. If two or more tweens animate one property at the same time, the last one created will take priority and assign the final value. If you want to interrupt and restart an animation, consider assigning the Tween to a variable:
private Tween _tween;
public void Animate()
{
if (_tween != null)
_tween.Kill(); // Abort the previous animation
_tween = CreateTween();
}
Some Tweeners use transitions and eases. The first accepts a Tween.TransitionType constant, and refers to the way the timing of the animation is handled (see easings.net for some examples). The second accepts an Tween.EaseType constant, and controls where the trans_type
is applied to the interpolation (in the beginning, the end, or both). If you don't know which transition and easing to pick, you can try different Tween.TransitionType constants with InOut, and use the one that looks best.
Tween easing and transition types cheatsheet
Note: Tweens are not designed to be re-used and trying to do so results in an undefined behavior. Create a new Tween for each animation and every time you replay an animation from start. Keep in mind that Tweens start immediately, so only create a Tween when you want to start animating.
Note: The tween is processed after all of the nodes in the current frame, i.e. node's _Process(double) method would be called before the tween (or _PhysicsProcess(double) depending on the value passed to SetProcessMode(TweenProcessMode)).
public class Tween : RefCounted, IDisposable
- Inheritance
-
Tween
- Implements
- Inherited Members
Constructors
Tween()
public Tween()
Methods
BindNode(Node)
Binds this Tween with the given node
. Tweens are processed directly by the SceneTree, so they run independently of the animated nodes. When you bind a Node with the Tween, the Tween will halt the animation when the object is not inside tree and the Tween will be automatically killed when the bound object is freed. Also Bound will make the pausing behavior dependent on the bound node.
For a shorter way to create and bind a Tween, you can use CreateTween().
public Tween BindNode(Node node)
Parameters
node
Node
Returns
Chain()
Used to chain two Tweeners after SetParallel(bool) is called with true
.
Tween tween = CreateTween().SetParallel(true);
tween.TweenProperty(...);
tween.TweenProperty(...); // Will run parallelly with above.
tween.Chain().TweenProperty(...); // Will run after two above are finished.
public Tween Chain()
Returns
CustomStep(double)
Processes the Tween by the given delta
value, in seconds. This is mostly useful for manual control when the Tween is paused. It can also be used to end the Tween animation immediately, by setting delta
longer than the whole duration of the Tween animation.
Returns true
if the Tween still has Tweeners that haven't finished.
public bool CustomStep(double delta)
Parameters
delta
double
Returns
GetLoopsLeft()
Returns the number of remaining loops for this Tween (see SetLoops(int)). A return value of -1
indicates an infinitely looping Tween, and a return value of 0
indicates that the Tween has already finished.
public int GetLoopsLeft()
Returns
GetTotalElapsedTime()
Returns the total time in seconds the Tween has been animating (i.e. the time since it started, not counting pauses etc.). The time is affected by SetSpeedScale(float), and Stop() will reset it to 0
.
Note: As it results from accumulating frame deltas, the time returned after the Tween has finished animating will be slightly greater than the actual Tween duration.
public double GetTotalElapsedTime()
Returns
HasGodotClassMethod(in godot_string_name)
Check if the type contains a method with the given name. This method is used by Godot to check if a method exists before invoking it. Do not call or override this method.
protected override bool HasGodotClassMethod(in godot_string_name method)
Parameters
method
godot_string_nameName of the method to check for.
Returns
HasGodotClassSignal(in godot_string_name)
Check if the type contains a signal with the given name. This method is used by Godot to check if a signal exists before raising it. Do not call or override this method.
protected override bool HasGodotClassSignal(in godot_string_name signal)
Parameters
signal
godot_string_nameName of the signal to check for.
Returns
InterpolateValue(Variant, Variant, double, double, TransitionType, EaseType)
This method can be used for manual interpolation of a value, when you don't want Tween to do animating for you. It's similar to @GlobalScope.lerp
, but with support for custom transition and easing.
initialValue
is the starting value of the interpolation.
deltaValue
is the change of the value in the interpolation, i.e. it's equal to final_value - initial_value
.
elapsedTime
is the time in seconds that passed after the interpolation started and it's used to control the position of the interpolation. E.g. when it's equal to half of the duration
, the interpolated value will be halfway between initial and final values. This value can also be greater than duration
or lower than 0, which will extrapolate the value.
duration
is the total time of the interpolation.
Note: If duration
is equal to 0
, the method will always return the final value, regardless of elapsedTime
provided.
public static Variant InterpolateValue(Variant initialValue, Variant deltaValue, double elapsedTime, double duration, Tween.TransitionType transType, Tween.EaseType easeType)
Parameters
initialValue
VariantdeltaValue
VariantelapsedTime
doubleduration
doubletransType
Tween.TransitionTypeeaseType
Tween.EaseType
Returns
InvokeGodotClassMethod(in godot_string_name, NativeVariantPtrArgs, out godot_variant)
Invokes the method with the given name, using the given arguments. This method is used by Godot to invoke methods from the engine side. Do not call or override this method.
protected override bool InvokeGodotClassMethod(in godot_string_name method, NativeVariantPtrArgs args, out godot_variant ret)
Parameters
method
godot_string_nameName of the method to invoke.
args
NativeVariantPtrArgsArguments to use with the invoked method.
ret
godot_variantValue returned by the invoked method.
Returns
IsRunning()
Returns whether the Tween is currently running, i.e. it wasn't paused and it's not finished.
public bool IsRunning()
Returns
IsValid()
Returns whether the Tween is valid. A valid Tween is a Tween contained by the scene tree (i.e. the array from GetProcessedTweens() will contain this Tween). A Tween might become invalid when it has finished tweening, is killed, or when created with Tween.new()
. Invalid Tweens can't have Tweeners appended.
public bool IsValid()
Returns
Kill()
Aborts all tweening operations and invalidates the Tween.
public void Kill()
Parallel()
Makes the next Tweener run parallelly to the previous one.
Example:
Tween tween = CreateTween();
tween.TweenProperty(...);
tween.Parallel().TweenProperty(...);
tween.Parallel().TweenProperty(...);
All Tweeners in the example will run at the same time.
You can make the Tween parallel by default by using SetParallel(bool).
public Tween Parallel()
Returns
Pause()
Pauses the tweening. The animation can be resumed by using Play().
Note: If a Tween is paused and not bound to any node, it will exist indefinitely until manually started or invalidated. If you lose a reference to such Tween, you can retrieve it using GetProcessedTweens().
public void Pause()
Play()
Resumes a paused or stopped Tween.
public void Play()
SetEase(EaseType)
Sets the default ease type for PropertyTweeners and MethodTweeners animated by this Tween.
If not specified, the default value is InOut.
public Tween SetEase(Tween.EaseType ease)
Parameters
Returns
SetLoops(int)
Sets the number of times the tweening sequence will be repeated, i.e. set_loops(2)
will run the animation twice.
Calling this method without arguments will make the Tween run infinitely, until either it is killed with Kill(), the Tween's bound node is freed, or all the animated objects have been freed (which makes further animation impossible).
Warning: Make sure to always add some duration/delay when using infinite loops. To prevent the game freezing, 0-duration looped animations (e.g. a single CallbackTweener with no delay) are stopped after a small number of loops, which may produce unexpected results. If a Tween's lifetime depends on some node, always use BindNode(Node).
public Tween SetLoops(int loops = 0)
Parameters
loops
int
Returns
SetParallel(bool)
If parallel
is true
, the Tweeners appended after this method will by default run simultaneously, as opposed to sequentially.
Note: Just like with Parallel(), the tweener added right before this method will also be part of the parallel step.
tween.tween_property(self, "position", Vector2(300, 0), 0.5)
tween.set_parallel()
tween.tween_property(self, "modulate", Color.GREEN, 0.5) # Runs together with the position tweener.
public Tween SetParallel(bool parallel = true)
Parameters
parallel
bool
Returns
SetPauseMode(TweenPauseMode)
Determines the behavior of the Tween when the SceneTree is paused. Check Tween.TweenPauseMode for options.
Default value is Bound.
public Tween SetPauseMode(Tween.TweenPauseMode mode)
Parameters
mode
Tween.TweenPauseMode
Returns
SetProcessMode(TweenProcessMode)
Determines whether the Tween should run after process frames (see _Process(double)) or physics frames (see _PhysicsProcess(double)).
Default value is Idle.
public Tween SetProcessMode(Tween.TweenProcessMode mode)
Parameters
mode
Tween.TweenProcessMode
Returns
SetSpeedScale(float)
Scales the speed of tweening. This affects all Tweeners and their delays.
public Tween SetSpeedScale(float speed)
Parameters
speed
float
Returns
SetTrans(TransitionType)
Sets the default transition type for PropertyTweeners and MethodTweeners animated by this Tween.
If not specified, the default value is Linear.
public Tween SetTrans(Tween.TransitionType trans)
Parameters
trans
Tween.TransitionType
Returns
Stop()
Stops the tweening and resets the Tween to its initial state. This will not remove any appended Tweeners.
Note: If a Tween is stopped and not bound to any node, it will exist indefinitely until manually started or invalidated. If you lose a reference to such Tween, you can retrieve it using GetProcessedTweens().
public void Stop()
TweenCallback(Callable)
Creates and appends a CallbackTweener. This method can be used to call an arbitrary method in any object. Use Callable.bind
to bind additional arguments for the call.
Example: Object that keeps shooting every 1 second:
Tween tween = GetTree().CreateTween().SetLoops();
tween.TweenCallback(Callable.From(Shoot)).SetDelay(1.0f);
Example: Turning a sprite red and then blue, with 2 second delay:
Tween tween = GetTree().CreateTween();
Sprite2D sprite = GetNode<Sprite2D>("Sprite");
tween.TweenCallback(Callable.From(() => sprite.Modulate = Colors.Red)).SetDelay(2.0f);
tween.TweenCallback(Callable.From(() => sprite.Modulate = Colors.Blue)).SetDelay(2.0f);
public CallbackTweener TweenCallback(Callable callback)
Parameters
callback
Callable
Returns
TweenInterval(double)
Creates and appends an IntervalTweener. This method can be used to create delays in the tween animation, as an alternative to using the delay in other Tweeners, or when there's no animation (in which case the Tween acts as a timer). time
is the length of the interval, in seconds.
Example: Creating an interval in code execution:
// ... some code
await ToSignal(CreateTween().TweenInterval(2.0f), Tween.SignalName.Finished);
// ... more code
Example: Creating an object that moves back and forth and jumps every few seconds:
Tween tween = CreateTween().SetLoops();
tween.TweenProperty(GetNode("Sprite"), "position:x", 200.0f, 1.0f).AsRelative();
tween.TweenCallback(Callable.From(Jump));
tween.TweenInterval(2.0f);
tween.TweenProperty(GetNode("Sprite"), "position:x", -200.0f, 1.0f).AsRelative();
tween.TweenCallback(Callable.From(Jump));
tween.TweenInterval(2.0f);
public IntervalTweener TweenInterval(double time)
Parameters
time
double
Returns
TweenMethod(Callable, Variant, Variant, double)
Creates and appends a MethodTweener. This method is similar to a combination of TweenCallback(Callable) and TweenProperty(GodotObject, NodePath, Variant, double). It calls a method over time with a tweened value provided as an argument. The value is tweened between from
and to
over the time specified by duration
, in seconds. Use Callable.bind
to bind additional arguments for the call. You can use SetEase(EaseType) and SetTrans(TransitionType) to tweak the easing and transition of the value or SetDelay(double) to delay the tweening.
Example: Making a 3D object look from one point to another point:
Tween tween = CreateTween();
tween.TweenMethod(Callable.From((Vector3 target) => LookAt(target, Vector3.Up)), new Vector3(-1.0f, 0.0f, -1.0f), new Vector3(1.0f, 0.0f, -1.0f), 1.0f); // Use lambdas to bind additional arguments for the call.
Example: Setting the text of a Label, using an intermediate method and after a delay:
public override void _Ready()
{
base._Ready();
Tween tween = CreateTween();
tween.TweenMethod(Callable.From<int>(SetLabelText), 0.0f, 10.0f, 1.0f).SetDelay(1.0f);
}
private void SetLabelText(int value)
{
GetNode<Label>("Label").Text = $"Counting {value}";
}
public MethodTweener TweenMethod(Callable method, Variant from, Variant to, double duration)
Parameters
Returns
TweenProperty(GodotObject, NodePath, Variant, double)
Creates and appends a PropertyTweener. This method tweens a property
of an object
between an initial value and finalVal
in a span of time equal to duration
, in seconds. The initial value by default is the property's value at the time the tweening of the PropertyTweener starts.
Example:
Tween tween = CreateTween();
tween.TweenProperty(GetNode("Sprite"), "position", new Vector2(100.0f, 200.0f), 1.0f);
tween.TweenProperty(GetNode("Sprite"), "position", new Vector2(200.0f, 300.0f), 1.0f);
will move the sprite to position (100, 200) and then to (200, 300). If you use From(Variant) or FromCurrent(), the starting position will be overwritten by the given value instead. See other methods in PropertyTweener to see how the tweening can be tweaked further.
Note: You can find the correct property name by hovering over the property in the Inspector. You can also provide the components of a property directly by using "property:component"
(eg. position:x
), where it would only apply to that particular component.
Example: Moving an object twice from the same position, with different transition types:
Tween tween = CreateTween();
tween.TweenProperty(GetNode("Sprite"), "position", Vector2.Right * 300.0f, 1.0f).AsRelative().SetTrans(Tween.TransitionType.Sine);
tween.TweenProperty(GetNode("Sprite"), "position", Vector2.Right * 300.0f, 1.0f).AsRelative().FromCurrent().SetTrans(Tween.TransitionType.Expo);
public PropertyTweener TweenProperty(GodotObject @object, NodePath property, Variant finalVal, double duration)
Parameters
object
GodotObjectproperty
NodePathfinalVal
Variantduration
double
Returns
Events
Finished
Emitted when the Tween has finished all tweening. Never emitted when the Tween is set to infinite looping (see SetLoops(int)).
public event Action Finished
Event Type
LoopFinished
Emitted when a full loop is complete (see SetLoops(int)), providing the loop index. This signal is not emitted after the final loop, use Finished instead for this case.
public event Tween.LoopFinishedEventHandler LoopFinished
Event Type
StepFinished
Emitted when one step of the Tween is complete, providing the step index. One step is either a single Tweener or a group of Tweeners running in parallel.
public event Tween.StepFinishedEventHandler StepFinished