rokojori_action_library/Runtime/Animation/ActionAnimationPlayer.cs

110 lines
2.1 KiB
C#

using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;
using Godot;
using Rokojori.Extensions;
namespace Rokojori;
[Tool]
[GlobalClass]
public partial class ActionAnimationPlayer:AnimationPlayer
{
#if TOOLS
[Export]
public bool callActionsInEditor = false;
float lastPosition = 0;
public override void _Ready()
{
base._Ready();
AnimationStarted += ( a ) =>{ GetTimedActions(); };
}
public override void _Process(double delta)
{
base._Process( delta );
if ( IsPlaying() )
{
if ( callActionsInEditor )
{
CheckForActions();
}
lastPosition = (float) CurrentAnimationPosition;
}
}
public class TimedActionKeys
{
public Action action;
public List<float> keys = [];
public void TriggerAction( float start, float end )
{
for ( int i = 0; i < keys.Count; i++ )
{
if ( start < keys[ i ] && keys[ i ] <= end )
{
action.Trigger();
return;
}
}
}
}
List<TimedActionKeys> timedActions = [];
Node GetTrackNode( Animation animation, int trackIndex )
{
var path = GetParent().GetPath() + "/" + animation.TrackGetPath( trackIndex );
return GetNode( path );
}
void GetTimedActions()
{
var animation = GetAnimation( CurrentAnimation );
for ( int i = 0; i < animation.GetTrackCount(); i++ )
{
var type = animation.TrackGetType( i );
if ( Animation.TrackType.Method != type )
{
continue;
}
var node = GetTrackNode( animation, i );
if ( ! ( node is Action ) )
{
continue;
}
var timedAction = new TimedActionKeys();
timedAction.action = node as Action;
var keys = animation.TrackGetKeyCount( i );
for ( int k = 0; k < keys; k++ )
{
var time = animation.TrackGetKeyTime( i, k );
timedAction.keys.Add( (float) time );
}
}
}
void CheckForActions()
{
var position = (float) CurrentAnimationPosition;
timedActions.ForEach( ta => ta.TriggerAction( lastPosition, position ) );
}
#endif
}