using System; using System.Collections.Generic; using System.Diagnostics; using Chickensoft.LogicBlocks; using Chickensoft.LogicBlocks.Auto; 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 JumpAscentMaxTime { get; set; } = 0.25f; [Export(PropertyHint.None, "suffix:px/s")] public float JumpAscentSpeed { get; set; } = 200.0f; [Export(PropertyHint.None, "suffix:s")] public float LateJumpTimeLimit { get; set; } = 0.1f; [Export(PropertyHint.None, "suffix:s")] public float SlashSpeedBoost { get; set; } = 90.0f; /// 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 TileMapLayer WaterTileMap { get; set; } = null!; private ulong MaxInputBufferTimeMicroseconds => (ulong)(MaxInputBufferTime * 1_000_000); public float JumpAscentRemainingTime { get; private set; } public bool IsJumping { get; private set; } public float JumpAllowedTime { get; private set; } /// The direction the player is currently holding. /// This vectors components should always be -1/0/1. private Vector2 _currentDirection = Vector2.Zero; private bool _isFacingRight = true; private AnimationNodeStateMachinePlayback _playback = null!; private List _inputBuffer = []; private bool _isInWater; private float PlatformIgnoreTime { 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(); } public override void _UnhandledInput(InputEvent @event) { if (@event.IsEcho()) return; if ( @event.IsAction("move_left") || @event.IsAction("move_right") || @event.IsAction("move_up") || @event.IsAction("move_down")) { _currentDirection = To8DirectionVector(Input.GetVector( "move_left", "move_right", "move_up", "move_down")); } if (@event.IsAction("jump") || @event.IsAction("attack")) { _inputBuffer.Add(new() { Direction = _currentDirection, Event = @event, Time = Time.GetTicksUsec(), }); HandleBufferedInputs(); } } public void OnPhysicsProcess(double delta) { var deltaF = (float)delta; // Temporary copy of the velocity for easier editing. var velocity = Velocity; if (CanTurn) AdjustFacing(); // Water movement 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 (JumpAscentRemainingTime > 0) { velocity.Y = -JumpAscentSpeed; JumpAscentRemainingTime -= deltaF; if (JumpAscentRemainingTime < 0) velocity += GetGravity() * -JumpAscentRemainingTime; } else if (!IsOnFloor() && !_isInWater) { velocity += GetGravity() * deltaF; } // Drag in water if (_isInWater) { velocity += Physics.DragForce(-velocity, 0.02f) * deltaF; } // Drag while in air else if (!IsOnFloor() && JumpAscentRemainingTime <= 0) { 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(); JumpAllowedTime = Mathf.Max(0, JumpAllowedTime - deltaF); if (IsOnFloor()) JumpAllowedTime = LateJumpTimeLimit; if (IsOnCeiling()) { IsJumping = false; JumpAscentRemainingTime = 0.0f; } } public void EnteredWater(Node2D body) { if (_isInWater) return; _isInWater = true; GD.Print("Entered water!"); } public void LeftWater(Node2D body) { if (!_isInWater || SubmersedSensor.HasOverlappingBodies()) return; GD.Print("Left water!"); _isInWater = false; } private void AdjustFacing() { if (_currentDirection.X < 0) _isFacingRight = false; else if (_currentDirection.X > 0) _isFacingRight = true; } private bool IsHoldingWall() { return !IsOnFloor() && IsOnWall() && Mathf.Sign(GetWallNormal().X) != Mathf.Sign(_currentDirection.X) && _currentDirection.X != 0; } public override void _Process(double delta) { HandleBufferedInputs(); GetNode("%Body").Scale = new(_isFacingRight ? 1 : -1, 1); } private void HandleBufferedInputs() { var inputFound = false; 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++) { var input = _inputBuffer[i]; if (input.Event.IsAction("jump")) { if (input.Event.IsPressed() && input.Direction.Y > 0 && IsOnFloor()) { inputFound = true; DropDown(); } else if ( input.Event.IsPressed() && JumpAllowedTime > 0 && (!IsOnFloor() || input.Direction.Y <= 0)) { inputFound = true; GroundJump(); } else if (input.Event.IsPressed() && IsOnWall()) { inputFound = true; WallJump(); } else if (input.Event.IsReleased() && IsJumping) { JumpCut(); } } else if (input.Event.IsActionPressed("attack")) { inputFound = true; Attack(); } if (inputFound) { _inputBuffer = _inputBuffer.GetRange(i + 1, _inputBuffer.Count - i - 1); break; } } } private void DropDown() { PlatformIgnoreTime = 0.1f; } private void GroundJump() { AdjustFacing(); JumpAllowedTime = 0.0f; JumpAscentRemainingTime = JumpAscentMaxTime; IsJumping = true; } private void WallJump() { AdjustFacing(); JumpAllowedTime = 0.0f; Velocity += GetWallNormal() * 200.0f; Velocity = Velocity with { Y = Mathf.Min(0, Velocity.Y) }; } private void JumpCut() { IsJumping = false; JumpAscentRemainingTime = 0.0f; // 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 bool IsAtWaterSurface() { throw new NotImplementedException(); } private void WaterExitJump() { throw new NotImplementedException(); } private static Vector2 To8DirectionVector(Vector2 input) { if (input.IsEqualApprox(Vector2.Zero)) return Vector2.Zero; var angle = input.Angle(); const float eighthCircle = float.Pi / 4; const float sixteenthCircle = float.Pi / 8; var sector = Mathf.FloorToInt((angle + sixteenthCircle) / eighthCircle) % 8; if (sector < 0) sector += 8; return sector switch { 0 => Vector2.Right, 1 => Vector2.Right + Vector2.Down, 2 => Vector2.Down, 3 => Vector2.Down + Vector2.Left, 4 => Vector2.Left, 5 => Vector2.Left + Vector2.Up, 6 => Vector2.Up, 7 => Vector2.Up + Vector2.Right, _ => throw new UnreachableException(), }; } private bool IsInputVecDown(Vector2 vec) { return Mathf.Abs(vec.AngleTo(Vector2.Down)) < DownInputAngle && vec.Length() > 0.01f; } private bool IsInputVecSide(Vector2 vec) { return vec.Length() > 0.01f && (Mathf.Abs(vec.AngleTo(Vector2.Left)) < SideInputAngle || Mathf.Abs(vec.AngleTo(Vector2.Right)) < SideInputAngle); } 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 class BufferedInput { public Vector2 Direction { get; init; } public required InputEvent Event { get; init; } public ulong Time { get; init; } } public void OnHitboxAdded(Hitbox hitbox) => hitbox.BodyHit += OnEnemyHit; public void OnHitboxRemoved(Hitbox hitbox) => hitbox.BodyHit -= OnEnemyHit; IHitboxOwner IProvide.Value() => this; [Meta] public sealed partial class Logic : AutoBlock { public sealed record Data { } public Logic() { Set(new Data()); Preallocate(); } public static class Input { public readonly record struct OnPhysicsProcess(double Delta); } [Meta, StateDiagram] public abstract partial record Root : LogicBlockState { [Meta] public sealed partial record Grounded : Root, IGet { public Type On(in Input.OnPhysicsProcess input) { throw new NotImplementedException(); } } [Meta] public sealed partial record Airborne : Root, IGet { public Type On(in Input.OnPhysicsProcess input) { throw new NotImplementedException(); } } [Meta] public sealed partial record Diving : Root, IGet { public Type On(in Input.OnPhysicsProcess input) { throw new NotImplementedException(); } } } } }