GTweens-Godot

repository·main·Indexed 42 days ago

https://github.com/guillemsc/gtweensgodot

A lightweight, versatile tweening library for Godot 4 using C#. It provides a node-independent API for creating complex animations, sequences, and transitions, featuring extension methods for common Godot nodes, async support via PlayAsync, and a sequence builder (GTweenSequenceBuilder) for chaining animations and callbacks.

Tokens
3.1K
Snippets
8
Records
13
Agent score
4%

What's inside GTweens-Godot

  1. Create complex animation sequences with GTweenSequenceBuilder

    main

    Use GTweenSequenceBuilder to chain multiple animations, delays, and callbacks together.

    • .Append(): Adds a tween that starts after the previous one finishes.
    • .Join(): Adds a tween that runs concurrently with the previous one.
    • .AppendTime(float): Adds a delay in the sequence.
    • .JoinCallback(Action) / .AppendCallback(Action): Executes a callback at a specific point in the timeline.
    public partial class PlayTweenSequenceExample : Node
    {
        [Export] public Node2D Target;
        
        public override void _Ready()
        {
            GTween tween = GTweenSequenceBuilder.New()
                .Append(Target.TweenPositionX(100f, 0.5f))
                    .Join(Target.TweenScale(new Vector2(2f, 2f), 1f))
                .AppendTime(0.5f)
                    .JoinCallback(() => GD.Print("I'm waiting some time!"))
                .Append(Target.TweenPositionX(0f, 1f))
                    .AppendCallback(() => GD.Print("I'm finished!"))
                .Build();
    
            tween.SetEasing(Easing.InOutCubic);
            tween.Play();
        }
    }
  2. Understand GTweensGodot nomenclature and prefixes

    main

    To effectively use IntelliSense and understand the API, follow these naming conventions:

    • Tween: Refers to the animation of one or multiple values.
    • Sequence: A group of tweens animated together.

    API Prefixes:

    • Tween: Used for shortcuts that start directly from a known object (e.g., Node2D, Control).
    • Set: Used for configuration methods that can be chained to a tween (e.g., SetLoops, SetEasing).
    • On: Used for callback methods that can be chained to a tween (e.g., OnStart, OnComplete).
  3. Install GTweens-Godot from Releases

    main

    To install manually from a zip file:

    1. Download the latest GTweensGodot.zip from the GitHub releases page.
    2. Unpack the contents into your Godot project's root folder.
    3. Go to Project/Project Settings/Autoload (or Globals/Autoload).
    4. Select GTweensGodot/Godot/Source/Contexts/GodotGTweensContextNode.cs and add it as an autoload.
    WARNING

    Do not rename the extracted folder or change the internal paths, as this will break scene references.

  4. Install GTweens-Godot via NuGet

    main

    To use the library as a NuGet package:

    1. Install the GTweensGodot NuGet package in your Godot project.
    2. Create a new C# script anywhere in your project named GTweensGodotUpdater.cs with the following content:
      public partial class GTweensGodotUpdater : GodotGTweensContextNode
      {
      }
    3. Go to Project/Project Settings/Autoload (or Globals/Autoload) and add your newly created GTweensGodotUpdater.cs as an autoload.
    public partial class GTweensGodotUpdater : GodotGTweensContextNode
    {
      
    }
  5. Install GTweens-Godot via Godot Asset Library

    main

    Follow these steps to install the library directly within the Godot editor:

    1. Open the AssetLib tab in Godot.
    2. Search for and select "GTweens (C#)".
    3. Download and install the asset. Crucial: Ensure the "Ignore asset root" tick is disabled.
    4. Go to Project/Project Settings/Autoload (or Globals/Autoload).
    5. Select GTweensGodot/Godot/Source/Contexts/GodotGTweensContextNode.cs and add it as an autoload.
  6. Basic Tweening with Extension Methods

    main

    GTweens-Godot provides intuitive C# extension methods on Godot nodes (like Node2D) to create simple animations. You can chain methods like .SetEasing() and call .Play() to start the animation.

    public partial class TweenExample : Node
    {
        [Export] public Node2D Target;
        
        public override void _Ready()
        {
            Target.TweenPosition(new Vector2(100, 0), 3)
                .SetEasing(Easing.InOutCubic)
                .Play();
        }
    }
  7. Use Async support and Godot Pause handling

    main

    GTweens integrates with C# asynchronous patterns and Godot's pause system:

    • Async: Use await tween.PlayAsync(CancellationToken) to wait for a tween to complete within an async Task.
    • Pause Behavior:
      • tween.Play(): Follows the standard Godot pause state (stops when GetTree().Paused is true).
      • tween.PlayUnpausable(): Continues running even if the game is paused.
    // Async support
    async Task RunSomething(CancellationToken cancellationToken)
    {
        await tween1.PlayAsync(cancellationToken);
        await tween2.PlayAsync(cancellationToken);
    }
    
    // Pause support
    tween.Play(); // Pauses with GetTree().Paused
    tween.PlayUnpausable(); // Ignores GetTree().Paused
  8. Control and manage GTween instances

    main

    Once a tween is created, you can control its playback and lifecycle using the following methods:

    Playback:

    • Play(): Runs the tween on _Process. Pauses if the Godot tree is paused.
    • PlayConfigured(...): Plays with custom configuration (process mode, pause behavior, or instantly to skip to the end).
    • PlayAsync(...): Returns a Task that completes when the tween is killed or finished. Supports CancellationToken.
    • PlayConfiguredAsync(...): Returns a Task with custom configuration and CancellationToken support.

    Lifecycle & State:

    • Kill(): Stops the tween immediately at its current state.
    • Complete(): Instantly jumps to the final state and stops.
    • Reset(): Returns to the initial state and stops.
    • AwaitCompleteOrKill(): Returns a Task that waits for the tween to finish or be killed.

    Configuration:

    • SetLoops(int): Sets the number of loops.
    • SetEasing(Easing): Sets the easing curve (applies to all child tweens if it is a sequence).
    • SetTimeScale(float): Sets the playback speed (default is 1).
  9. Use generic tweening for any value

    main

    Generic tweening is the most flexible method, allowing you to animate almost any property by providing a getter and a setter delegate.

    • Use GTweenExtensions.Tween for standard C# types (int, float, etc.).
    • Use GTweenGodotExtensions.Tween for Godot-specific types (Vector2, Vector3, etc.).

    Parameters:

    • Getter: A delegate () => value that returns the current property value.
    • Setter: A delegate x => value = x that sets the property value.
    • To: The target end value.
    • Duration: The time in seconds.
    • Validation (optional): A delegate () => bool that checks every update if the tween should continue running.
    // For default C# values
    GTween tween = GTweenExtensions.Tween(
        () => Target.SomeFloat, // Getter
        x => Target.SomeFloat = x, // Setter
        100f, // To
        1 // Duration
    );
    
    // For Godot specific values
    GTween tween = GTweenGodotExtensions.Tween(
        () => Target.Position, // Getter
        x => Target.Position = x, // Setter
        new Vector2(100f, 100f), // To
        1 // Duration
    );
  10. Configure Looping and Easing

    main

    You can control how a tween repeats and its movement curve:

    • Looping: Use .SetLoops(int loops) to repeat the animation. Passing a specific count controls the number of iterations.
    • Easing: Use .SetEasing(Easing easing) or .SetEasing(Curve curve) to define the acceleration/deceleration profile of the animation.
    // Looping example
    GTween tween = Target.TweenPositionX(150, 1);
    tween.SetLoops(Loops);
    tween.Play();
    
    // Easing with Curve example
    GTween tween2 = Target2.TweenPositionX(100, 3);
    tween2.SetEasing(Easing2); // Easing2 is a Godot Curve
    tween2.Play();
  11. Create complex animations with Sequences

    main

    Sequences allow you to group multiple tweens and animate them as a single unit. You can nest sequences within other sequences indefinitely. Use the GTweenSequenceBuilder to construct them.

    Builder Methods:

    • GTweenSequenceBuilder.New(): Starts a new sequence.
    • Append(tween): Adds a tween to the end of the sequence (plays after previous tweens finish).
    • Join(tween): Adds a tween to play simultaneously with the last added tween.
    • AppendTime(seconds): Adds a delay to the sequence.
    • AppendCallback(action): Adds a callback to execute at that point in the sequence.
    • AppendSequence(action): Nests a new sequence using a builder provided via an action.
    • Build(): Finalizes and returns the GTween sequence object.
     GTween tween = GTweenSequenceBuilder.New()
        .Append(Target.TweenPositionX(100, 0.5f))
            .Join(Target.TweenScale(new Vector2(2, 2), 1))
        .Append(Target.TweenPositionY(100, 1))
        .AppendTime(0.5f)
        .Append(Target.TweenPositionX(0, 1))
        .AppendSequence(s => s
            .AppendTime(0.5f)
            .Append(Target.TweenPositionX(1, 1))
            )
        .AppendCallback(() => GD.Print("I'm finished!"))
        .Build();
            
    tween.SetEasing(Easing.InOutCubic);
    tween.Play();
  12. Use shortcut tweening for Godot nodes

    main

    GTweensGodot provides extension methods (shortcuts) for common Godot objects, allowing you to start a tween directly from a node reference.

    Examples:

    • node2D.TweenPositionX(100f, 1f);
    • control.TweenSizeY(200f, 2f);
    • node3D.TweenScale(new Vector3(2f, 2f, 2f), 1f);
    node2D.TweenPositionX(100f, 1f);
    node3D.TweenScale(new Vector3(2f, 2f, 2f), 1f);
    control.TweenSizeY(200f, 2f);