rokojori_action_library/Runtime/Actions/Audio/TweenMusicVolume.cs

94 lines
2.0 KiB
C#
Raw Normal View History

2025-12-11 14:47:57 +00:00
using System;
using Godot;
2026-05-22 12:25:02 +00:00
using Rokojori.Extensions;
2025-12-11 14:47:57 +00:00
namespace Rokojori
{
[Tool]
[GlobalClass, Icon("res://addons/rokojori_action_library/Icons/Tween.svg")]
public partial class TweenMusicVolume:SequenceAction
{
[Export]
public AudioStreamPlayer target;
[Export]
public float endVolume = 0;
public enum VolumeUnit
{
Linear,
Decibel
}
[Export]
public VolumeUnit volumeUnit = VolumeUnit.Linear;
[Export]
public TweenType tweenType = new TweenTimeCurve();
[Export]
public bool cacheEndPositionOnStart = true;
[Export]
2026-05-22 12:25:02 +00:00
public Timeline timeLine;
2025-12-11 14:47:57 +00:00
protected override void _OnTrigger()
{
if ( target == null )
{
return;
}
2026-05-22 12:25:02 +00:00
var tl = TimelineManager.Ensure( timeLine );
2025-12-11 14:47:57 +00:00
var start = tl.position;
var fromVolume = target.VolumeDb;
var toVolume = volumeUnit == VolumeUnit.Linear ? MathAudio.AmplitudeToDecibels( endVolume ) : endVolume;
var sequenceID = DispatchStart();
var tweenType = this.tweenType;
if ( tweenType == null )
{
tweenType = TweenTimeCurve.defaultCurve;
}
2026-05-22 12:25:02 +00:00
TimelineManager.ScheduleSpanIn( tl, 0, tweenType.GetTweenDuration(),
2025-12-11 14:47:57 +00:00
( span, type )=>
{
if ( ! GodotObject.IsInstanceValid( target ) )
{
DispatchEnd( sequenceID );
return;
}
var timeNow = tl.position;
var elapsed = timeNow - start;
var state = tweenType.GetTweenPhaseForPhase( span.phase );
if ( ! cacheEndPositionOnStart )
{
var toScale = volumeUnit == VolumeUnit.Linear ? MathAudio.AmplitudeToDecibels( endVolume ) : endVolume;;
}
var lerpedVolume = Mathf.Lerp( fromVolume, toVolume, state );
target.VolumeDb = lerpedVolume;
2026-05-22 12:25:02 +00:00
if ( type == TimelineSpanUpdateType.End )
2025-12-11 14:47:57 +00:00
{
DispatchEnd( sequenceID );
}
},
this
);
}
}
}