using System.Collections.Generic; namespace Dancer; [Meta(typeof(IAutoNode))] public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner, IProvide { public override void _Notification(int what) => this.Notify(what); [Export(PropertyHint.None, "suffix:s")] public float MaxInputBufferTime { get; set; } = 0.15f; /// /// The speed decay used when the player continues movement in the direction they're going. /// [Export(PropertyHint.None, "suffix:s⁻¹")] public float GroundedSpeedDecay { get; set; } = 0.3f; [Export(PropertyHint.None, "suffix:s⁻¹")] public float GroundedSpeedStopDecay { get; set; } = 0.005f; [Export(PropertyHint.None, "suffix:px/s")] public float WalkMaxSpeed { get; set; } = 110.0f; [Export(PropertyHint.None, "suffix:px/s²")] public float WalkAccel { get; set; } = 800.0f; [Export(PropertyHint.None, "suffix:px/s²")] public float AirAccel { get; set; } = 180.0f; [Export(PropertyHint.None, "suffix:px/s²")] public float WaterAccel { get; set; } = 1200.0f; [Export(PropertyHint.None, "suffix:s")] public float JumpAscentMaxDuration { get; set; } = 0.25f; [Export(PropertyHint.None, "suffix:px/s")] public float JumpAscentSpeed { get; set; } = 200.0f; [Export(PropertyHint.None, "suffix:s")] public float LateJumpLimitDuration { get; set; } = 0.1f; [Export(PropertyHint.None, "suffix:px/s")] public float SlashSpeedBoost { get; set; } = 90.0f; [Export(PropertyHint.None, "suffix:s")] public float DashDuration { get; set; } = 0.15f; [Export(PropertyHint.None, "suffix:px/s")] public float DashSpeed { get; set; } = 400.0f; [Export(PropertyHint.None, "suffix:s")] public float DashCooldownDuration { get; set; } = 0.6f; /// The angle difference from perfect left/right that still counts. [Export(PropertyHint.Range, "0,360,0.1,radians_as_degrees")] public float SideInputAngle { get; set; } = Mathf.Pi / 4; /// The angle difference from perfect down that still counts. [Export(PropertyHint.Range, "0,360,0.1,radians_as_degrees")] public float DownInputAngle { get; set; } = Mathf.Pi / 4; [Export] public float MaxHealth { get; set; } = 5f; [Export] public float Health { get; set; } [Export] public bool CanTurn { get; set; } = true; [Export] public float MaxDashPoints { get; set; } = 2f; private ulong MaxInputBufferTimeMicroseconds => (ulong)(MaxInputBufferTime * 1_000_000); public bool IsJumping => JumpTicker.IsRunning; /// The direction the player is currently holding. /// This vectors components should always be -1/0/1. private Vector2 _currentDirection = Vector2.Zero; public bool IsFacingRight { get; private set; } = true; private AnimationNodeStateMachinePlayback _playback = null!; private List _inputBuffer = []; public bool IsInWater { get; private set; } private float PlatformIgnoreTime { get; set; } public Ticker JumpAllowedTicker { get; } = new(); private Ticker WaterJumpAllowedTicker { get; } = new(); private Ticker DashTicker { get; } = new(); private Ticker DashCooldown { get; } = new(); private Ticker JumpTicker { get; } = new(); private Vector2 DashDirection { get; set; } public float DashPoints { get; set; } [Node] private AnimationTree AnimationTree { get; set; } = null!; [Node] private Area2D SubmersedSensor { get; set; } = null!; public void OnReady() { this.Provide(); SetPhysicsProcess(true); Health = MaxHealth; _playback = AnimationTree.Get("parameters/playback").As(); DashTicker.Duration = DashDuration; DashCooldown.Duration = DashCooldownDuration; JumpAllowedTicker.Duration = LateJumpLimitDuration; WaterJumpAllowedTicker.Duration = LateJumpLimitDuration; } public override void _UnhandledInput(InputEvent @event) { if (@event.IsEcho()) return; if ( @event.IsAction(ActionName.MoveLeft) || @event.IsAction(ActionName.MoveRight) || @event.IsAction(ActionName.MoveUp) || @event.IsAction(ActionName.MoveDown)) { _currentDirection = To8DirectionVector(Input.GetVector( ActionName.MoveLeft, ActionName.MoveRight, ActionName.MoveUp, ActionName.MoveDown)); } if (Action.TryFromEvent(@event, out var action)) { _inputBuffer.Add(new() { Direction = _currentDirection, Action = action, IsPressed = @event.IsPressed(), Time = Time.GetTicksUsec(), }); } } public void OnPhysicsProcess(double delta) { HandleBufferedInputs(); var deltaF = (float)delta; // Temporary copy of the velocity for easier editing. var velocity = Velocity; if (CanTurn) AdjustFacing(); if (DashTicker.HasFinishedLastTick) velocity *= 0.6f; if (DashTicker.IsRunning) { velocity = DashDirection * DashSpeed; } // Water movement else if (IsInWater) { velocity += _currentDirection.Normalized() * WaterAccel * deltaF; } // Walking on the floor else if (IsOnFloor()) { var walkInput = _currentDirection.X; if (Mathf.Sign(velocity.X) != Mathf.Sign(walkInput)) velocity.X *= Mathf.Pow(GroundedSpeedStopDecay, deltaF); else velocity.X *= Mathf.Pow(GroundedSpeedDecay, deltaF); var targetVelX = Mathf.Sign(walkInput) * WalkMaxSpeed; var isWalking = targetVelX != 0; if (!isWalking || Mathf.Abs(velocity.X) < WalkMaxSpeed) { velocity.X = Mathf.MoveToward(velocity.X, targetVelX, WalkAccel * deltaF); } } // Air control else { velocity.X += Mathf.Sign(_currentDirection.X) * AirAccel * deltaF; } // Move up while holding jump if (JumpTicker.IsRunning) { velocity.Y = -JumpAscentSpeed; var overflow = JumpTicker.TickWithOverflow(deltaF); velocity += GetGravity() * overflow; } else if (!IsOnFloor() && !IsInWater && !DashTicker.IsRunning) { velocity += GetGravity() * deltaF; } if (!DashTicker.IsRunning) { // Drag in water if (IsInWater) { velocity += Physics.DragForce(-velocity, 0.02f) * deltaF; } // Drag while in air else if (!IsOnFloor() && !JumpTicker.IsRunning) { velocity += Physics.DragForce(-velocity, 0.009f) * deltaF; } } if (IsHoldingWall()) { velocity.Y = Mathf.Min(velocity.Y, 5.0f); IsFacingRight = Mathf.Sign(GetWallNormal().X) > 0; } Velocity = velocity; if (PlatformIgnoreTime > 0f) { CollisionMask = 0b1; PlatformIgnoreTime = Mathf.Max(0f, PlatformIgnoreTime - deltaF); } else { CollisionMask = 0b0100_0001; } MoveAndSlide(); JumpAllowedTicker.Tick(deltaF); if (IsOnFloor()) JumpAllowedTicker.Start(); WaterJumpAllowedTicker.Tick(deltaF); DashTicker.Tick(deltaF); DashCooldown.Tick(deltaF); if (IsInWater) DashPoints = Mathf.Min(MaxDashPoints, DashPoints + 3f * deltaF); if (IsOnCeiling()) JumpTicker.Reset(); } public void EnteredWater(Node2D body) => IsInWater = true; public void LeftWater(Node2D body) { if (!IsInWater || SubmersedSensor.HasOverlappingBodies()) return; IsInWater = false; WaterJumpAllowedTicker.Start(); } private void AdjustFacing() { if (_currentDirection.X < 0) IsFacingRight = false; else if (_currentDirection.X > 0) IsFacingRight = true; } private Vector2 FacingVector => IsFacingRight ? Vector2.Right : Vector2.Left; private bool IsHoldingWall() { return !IsOnFloor() && IsOnWall() && Mathf.Sign(GetWallNormal().X) != Mathf.Sign(_currentDirection.X) && _currentDirection.X != 0; } public override void _Process(double delta) { GetNode("%Body").Scale = new(IsFacingRight ? 1 : -1, 1); } public readonly struct BufferedInput { public Vector2 Direction { get; init; } public required Action Action { get; init; } public required bool IsPressed { get; init; } public ulong Time { get; init; } } public enum Action { Jump, Attack, Dash, } private void HandleBufferedInputs() { var currentTime = Time.GetTicksUsec(); // Clear expired input buffer items while ( _inputBuffer.Count > 0 && _inputBuffer[0].Time + MaxInputBufferTimeMicroseconds < currentTime) { _inputBuffer.RemoveAt(0); } // Check new commands for (var i = 0; i < _inputBuffer.Count; i++) { if (MatchInput(_inputBuffer[i])) { _inputBuffer.RemoveRange(0, i + 1); break; } } } /// /// Select an action based on a buffered input. /// /// /// true if inputs up to this one should be consumed. private bool MatchInput(BufferedInput input) { switch (input) { case { Action: Action.Jump, IsPressed: true, Direction.Y: > 0f } when IsOnFloor(): DropDown(); return true; case { Action: Action.Jump, IsPressed: true } when JumpAllowedTicker.IsRunning && (!IsOnFloor() || input.Direction.Y <= 0): GroundJump(); return true; case { Action: Action.Jump, IsPressed: true } when IsOnWall(): WallJump(); return true; case { Action: Action.Jump, IsPressed: true } when WaterJumpAllowedTicker.IsRunning: WaterExitJump(); return true; case { Action: Action.Jump, IsPressed: false } when IsJumping: JumpCut(); return false; case { Action: Action.Attack, IsPressed: true }: Attack(); return true; case { Action: Action.Dash, IsPressed: true } when !DashCooldown.IsRunning && DashPoints >= 1f: Dash(); return true; default: return false; } } private void DropDown() { PlatformIgnoreTime = 0.1f; } private void GroundJump() { AdjustFacing(); JumpAllowedTicker.Reset(); JumpTicker.Duration = JumpAscentMaxDuration; JumpTicker.Start(); } private void WallJump() { AdjustFacing(); JumpAllowedTicker.Reset(); JumpTicker.Duration = JumpAscentMaxDuration; JumpTicker.Start(); var direction = new Vector2(Mathf.Sign(GetWallNormal().X), -.5f).Normalized(); Velocity = direction * 200.0f; } private void JumpCut() { JumpTicker.Reset(); // Jump cut only once, if we're still moving up if (Velocity.Y < 0) Velocity = Velocity with { Y = Velocity.Y * 0.1f }; } private void Attack() { AdjustFacing(); Velocity += (IsFacingRight ? Vector2.Right : Vector2.Left) * SlashSpeedBoost; _playback.Travel("front_kick"); } private void WaterExitJump() { AdjustFacing(); WaterJumpAllowedTicker.Reset(); JumpTicker.Duration = JumpAscentMaxDuration * 1.5f; JumpTicker.Start(); } private void Dash() { AdjustFacing(); DashPoints -= 1f; DashTicker.Start(); DashCooldown.Start(); DashDirection = (_currentDirection.IsZeroApprox() ? FacingVector : _currentDirection ).Normalized(); } private static Vector2 To8DirectionVector(Vector2 input) { if (input.IsZeroApprox()) return Vector2.Zero; const float tan225 = 0.414213562373f; // tan(22.5°) Vector2 a = input.Abs(), s = input.Sign(); return a.Y < a.X * tan225 ? new(s.X, 0) : a.X < a.Y * tan225 ? new(0, s.Y) : s; } private void OnEnemyHit(Hitbox hitbox, Node2D enemy) { if (enemy is not IAttackable attackable) return; attackable.GetAttacked(new() { Attacker = this, Damage = 1.0f, Impulse = Vector2.Up * 1000.0f + (enemy.Position - Position).Normalized() * 1000.0f, }); } public void GetAttacked(in Attack attack) { Health -= attack.Damage; } public void OnHitboxAdded(Hitbox hitbox) => hitbox.BodyHit += OnEnemyHit; public void OnHitboxRemoved(Hitbox hitbox) => hitbox.BodyHit -= OnEnemyHit; IHitboxOwner IProvide.Value() => this; } public static class GameActionExtensions { private static readonly List<(StringName actionName, Player.Action action)> Actions = [ (ActionName.Attack, Player.Action.Attack), (ActionName.Dash, Player.Action.Dash), (ActionName.Jump, Player.Action.Jump), ]; extension(Player.Action) { public static bool TryFromEvent( InputEvent @event, out Player.Action result ) { foreach (var (actionName, action) in Actions) if (@event.IsAction(actionName)) { result = action; return true; } result = default; return false; } } }