kidscancode / godot_recipes

Lessons, tutorials, and guides for game development using the Godot game engine.
MIT License
240 stars 37 forks source link

[Discussion] UI: Floating combat text #61

Open cbscribe opened 3 years ago

cbscribe commented 3 years ago

Discussion for http://godotrecipes.com/ui/floating_text/

Allov commented 3 years ago

I ported the example to C# if anyone wants the code:

Label

using Godot;

public class DamageText : Label
{
    private Tween Tween;
    [Export] public Color CritColor;

    public override void _Ready()
    {
        Tween = GetNodeOrNull<Tween>("Tween");
    }

    // https://kidscancode.org/godot_recipes/ui/floating_text/
    public async void ShowValue(int value, Vector2 travel, float duration, float spread, bool crit = false)
    {
        Text = value.ToString();
        var movement = travel.Rotated((float)GD.RandRange(-spread / 2f, spread / 2f));
        RectPivotOffset = RectSize / 2f;

        Tween.InterpolateProperty(this, "rect_position",
                RectPosition, RectPosition + movement,
                duration, Tween.TransitionType.Linear, Tween.EaseType.InOut);
        Tween.InterpolateProperty(this, "modulate:a",
                1.0f, 0.0f, duration,
                Tween.TransitionType.Linear, Tween.EaseType.InOut);

        if (crit)
        {
            Modulate = CritColor;
            Tween.InterpolateProperty(this, "rect_scale",
                RectScale * 2, RectScale,
                0.4f, Tween.TransitionType.Back, Tween.EaseType.In);
        }

        Tween.Start();
        await ToSignal(Tween, "tween_all_completed");
        QueueFree();
    }
}

Manager

using Godot;

public class DamageTextManager : Node2D
{
    [Export] public PackedScene DamageTextScene;
    [Export] public Vector2 Travel = new Vector2(0, -80);
    [Export] public float Duration = 2f;
    [Export] public float Spread = Mathf.Pi / 2f;

    public void ShowValue(int value, bool crit = false)
    {
        var damageText = DamageTextScene.Instance() as DamageText;
        AddChild(damageText);
        damageText.ShowValue(value, Travel, Duration, Spread, crit);
    }
}