Skip to content

Instantly share code, notes, and snippets.

@valkyrienyanko
Created May 28, 2023 17:47
Show Gist options
  • Save valkyrienyanko/3f7a5f3a78ee83f2829a622866d0955d to your computer and use it in GitHub Desktop.
Save valkyrienyanko/3f7a5f3a78ee83f2829a622866d0955d to your computer and use it in GitHub Desktop.
public class State
{
public Action Enter { get; set; } = () => { };
public Action Update { get; set; } = () => { };
public Action Exit { get; set; } = () => { };
public void Switch(ref State curState, State newState)
{
Exit();
curState = newState;
newState.Enter();
}
}
public partial class Frog : Monster
{
State idle = new();
State preJump = new();
State jump = new();
State curState;
public override void _Ready()
{
base._Ready();
// idle
idle.Enter = () =>
{
sprite.Play("idle");
Switch(delay: 2, preJump);
};
// pre jump
preJump.Enter = () =>
{
sprite.Play("jump_pre");
Switch(delay: 0.75, jump);
};
preJump.Update = () =>
{
double strength = 0.4;
sprite.Offset = new Vector2((float)GD.RandRange(-strength, strength), 0);
};
preJump.Exit = () =>
{
sprite.Offset = Vector2.Zero;
};
// jump
jump.Enter = () =>
{
sprite.Play("jump_start");
};
curState = idle;
curState.Enter();
}
void Switch(double delay, State newState) =>
Global.CreateTimer(delay, () => curState.Switch(ref curState, newState));
public override void _PhysicsProcess(double delta)
{
base._PhysicsProcess(delta);
curState.Update();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment