refactored player input handling

This commit is contained in:
Lilith Schier 2026-07-16 19:08:43 +02:00
parent 2088037606
commit 761389116a
9 changed files with 216 additions and 235 deletions

View file

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Chickensoft.LogicBlocks;
using Chickensoft.LogicBlocks.Auto;
namespace Dancer;
@ -37,15 +33,15 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
public float WaterAccel { get; set; } = 1200.0f;
[Export(PropertyHint.None, "suffix:s")]
public float JumpAscentMaxTime { get; set; } = 0.25f;
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 LateJumpTimeLimit { get; set; } = 0.1f;
public float LateJumpLimitDuration { get; set; } = 0.1f;
[Export(PropertyHint.None, "suffix:s")]
[Export(PropertyHint.None, "suffix:px/s")]
public float SlashSpeedBoost { get; set; } = 90.0f;
[Export(PropertyHint.None, "suffix:s")]
@ -72,22 +68,22 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
[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; }
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;
private bool _isFacingRight = true;
public bool IsFacingRight { get; private set; } = true;
private AnimationNodeStateMachinePlayback _playback = null!;
private List<BufferedInput> _inputBuffer = [];
private bool _isInWater;
public bool IsInWater { get; private set; }
private float PlatformIgnoreTime { get; set; }
private float WaterJumpAllowedTime { get; set; }
private Ticker DashTicker { get; set; } = new();
private Ticker DashCooldown { get; set; } = new();
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; }
[Node] private AnimationTree AnimationTree { get; set; } = null!;
@ -101,6 +97,8 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
_playback = AnimationTree.Get("parameters/playback").As<AnimationNodeStateMachinePlayback>();
DashTicker.Duration = DashDuration;
DashCooldown.Duration = DashCooldownDuration;
JumpAllowedTicker.Duration = LateJumpLimitDuration;
WaterJumpAllowedTicker.Duration = LateJumpLimitDuration;
}
public override void _UnhandledInput(InputEvent @event)
@ -109,27 +107,27 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
return;
if (
@event.IsAction("move_left")
|| @event.IsAction("move_right")
|| @event.IsAction("move_up")
|| @event.IsAction("move_down"))
@event.IsAction(ActionName.MoveLeft)
|| @event.IsAction(ActionName.MoveRight)
|| @event.IsAction(ActionName.MoveUp)
|| @event.IsAction(ActionName.MoveDown))
{
_currentDirection = To8DirectionVector(Input.GetVector(
"move_left",
"move_right",
"move_up",
"move_down"));
ActionName.MoveLeft,
ActionName.MoveRight,
ActionName.MoveUp,
ActionName.MoveDown));
}
if (@event.IsAction("jump") || @event.IsAction("attack") || @event.IsAction("dash"))
if (Action.TryFromEvent(@event, out var action))
{
_inputBuffer.Add(new()
{
Direction = _currentDirection,
Event = @event,
Action = action,
IsPressed = @event.IsPressed(),
Time = Time.GetTicksUsec(),
});
HandleBufferedInputs();
}
}
@ -143,7 +141,7 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
if (CanTurn) AdjustFacing();
// Water movement
if (_isInWater)
if (IsInWater)
{
if (DashTicker.IsRunning)
{
@ -178,14 +176,13 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
}
// Move up while holding jump
if (JumpAscentRemainingTime > 0)
if (JumpTicker.IsRunning)
{
velocity.Y = -JumpAscentSpeed;
JumpAscentRemainingTime -= deltaF;
if (JumpAscentRemainingTime < 0)
velocity += GetGravity() * -JumpAscentRemainingTime;
var overflow = JumpTicker.TickWithOverflow(deltaF);
velocity += GetGravity() * overflow;
}
else if (!IsOnFloor() && !_isInWater && !DashTicker.IsRunning)
else if (!IsOnFloor() && !IsInWater && !DashTicker.IsRunning)
{
velocity += GetGravity() * deltaF;
}
@ -193,12 +190,12 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
if (!DashTicker.IsRunning)
{
// Drag in water
if (_isInWater)
if (IsInWater)
{
velocity += Physics.DragForce(-velocity, 0.02f) * deltaF;
}
// Drag while in air
else if (!IsOnFloor() && JumpAscentRemainingTime <= 0)
else if (!IsOnFloor() && !JumpTicker.IsRunning)
{
velocity += Physics.DragForce(-velocity, 0.009f) * deltaF;
}
@ -207,7 +204,7 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
if (IsHoldingWall())
{
velocity.Y = Mathf.Min(velocity.Y, 5.0f);
_isFacingRight = Mathf.Sign(GetWallNormal().X) > 0;
IsFacingRight = Mathf.Sign(GetWallNormal().X) > 0;
}
Velocity = velocity;
@ -223,39 +220,34 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
MoveAndSlide();
JumpAllowedTime = Mathf.Max(0, JumpAllowedTime - deltaF);
JumpAllowedTicker.Tick(deltaF);
if (IsOnFloor())
JumpAllowedTime = LateJumpTimeLimit;
WaterJumpAllowedTime = Mathf.Max(0, WaterJumpAllowedTime - deltaF);
JumpAllowedTicker.Start();
WaterJumpAllowedTicker.Tick(deltaF);
DashTicker.Tick(deltaF);
DashCooldown.Tick(deltaF);
if (IsOnCeiling())
{
IsJumping = false;
JumpAscentRemainingTime = 0.0f;
}
if (IsOnCeiling()) JumpTicker.Reset();
}
public void EnteredWater(Node2D body) => _isInWater = true;
public void EnteredWater(Node2D body) => IsInWater = true;
public void LeftWater(Node2D body)
{
if (!_isInWater || SubmersedSensor.HasOverlappingBodies()) return;
_isInWater = false;
WaterJumpAllowedTime = LateJumpTimeLimit;
if (!IsInWater || SubmersedSensor.HasOverlappingBodies()) return;
IsInWater = false;
WaterJumpAllowedTicker.Start();
}
private void AdjustFacing()
{
if (_currentDirection.X < 0)
_isFacingRight = false;
IsFacingRight = false;
else if (_currentDirection.X > 0)
_isFacingRight = true;
IsFacingRight = true;
}
private Vector2 FacingVector => _isFacingRight ? Vector2.Right : Vector2.Left;
private Vector2 FacingVector => IsFacingRight ? Vector2.Right : Vector2.Left;
private bool IsHoldingWall()
{
@ -268,12 +260,26 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
public override void _Process(double delta)
{
GetNode<Node2D>("%Body").Scale = new(_isFacingRight ? 1 : -1, 1);
GetNode<Node2D>("%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 inputFound = false;
var currentTime = Time.GetTicksUsec();
// Clear expired input buffer items
@ -287,54 +293,7 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
// 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)
&& !_isInWater)
{
inputFound = true;
GroundJump();
}
else if (input.Event.IsPressed() && IsOnWall())
{
inputFound = true;
WallJump();
}
else if (input.Event.IsPressed() && WaterJumpAllowedTime > 0)
{
inputFound = true;
WaterExitJump();
}
else if (input.Event.IsReleased() && IsJumping)
{
JumpCut();
}
}
else if (input.Event.IsActionPressed("attack"))
{
inputFound = true;
Attack();
}
else if (input.Event.IsActionPressed("dash"))
{
if (_isInWater && !DashCooldown.IsRunning)
{
inputFound = true;
Dash();
}
}
if (inputFound)
if (MatchInput(_inputBuffer[i]))
{
_inputBuffer = _inputBuffer.GetRange(i + 1, _inputBuffer.Count - i - 1);
break;
@ -342,6 +301,56 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
}
}
/// <summary>
/// Select an action based on a buffered input.
/// </summary>
/// <param name="input"></param>
/// <returns>true if inputs up to this one should be consumed.</returns>
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)
&& !IsInWater:
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 (IsInWater && !DashCooldown.IsRunning):
Dash();
return true;
default:
return false;
}
}
private void DropDown()
{
PlatformIgnoreTime = 0.1f;
@ -350,23 +359,22 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
private void GroundJump()
{
AdjustFacing();
JumpAllowedTime = 0.0f;
JumpAscentRemainingTime = JumpAscentMaxTime;
IsJumping = true;
JumpAllowedTicker.Reset();
JumpTicker.Duration = JumpAscentMaxDuration;
JumpTicker.Start();
}
private void WallJump()
{
AdjustFacing();
JumpAllowedTime = 0.0f;
JumpAllowedTicker.Reset();
Velocity += GetWallNormal() * 200.0f;
Velocity = Velocity with { Y = Mathf.Min(0, Velocity.Y) };
}
private void JumpCut()
{
IsJumping = false;
JumpAscentRemainingTime = 0.0f;
JumpTicker.Reset();
// Jump cut only once, if we're still moving up
if (Velocity.Y < 0)
Velocity = Velocity with { Y = Velocity.Y * 0.1f };
@ -375,16 +383,16 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
private void Attack()
{
AdjustFacing();
Velocity += (_isFacingRight ? Vector2.Right : Vector2.Left) * SlashSpeedBoost;
Velocity += (IsFacingRight ? Vector2.Right : Vector2.Left) * SlashSpeedBoost;
_playback.Travel("front_kick");
}
private void WaterExitJump()
{
AdjustFacing();
JumpAllowedTime = 0.0f;
JumpAscentRemainingTime = JumpAscentMaxTime * 1.5f;
IsJumping = true;
WaterJumpAllowedTicker.Reset();
JumpTicker.Duration = JumpAscentMaxDuration * 1.5f;
JumpTicker.Start();
}
private void Dash()
@ -401,35 +409,15 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
private static Vector2 To8DirectionVector(Vector2 input)
{
if (input.IsZeroApprox()) 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;
}
const float tan225 = 0.4142135623730950488f; // tan(22.5°) = √2 - 1
float ax = Mathf.Sign(input.X), ay = Mathf.Abs(input.Y);
float sx = Mathf.Sign(input.X), sy = Mathf.Sign(input.Y);
private bool IsInputVecSide(Vector2 vec)
{
return vec.Length() > 0.01f
&& (Mathf.Abs(vec.AngleTo(Vector2.Left)) < SideInputAngle
|| Mathf.Abs(vec.AngleTo(Vector2.Right)) < SideInputAngle);
return
ay < ax * tan225 ? new(sx, 0) :
ax < ay * tan225 ? new(0, sy) :
new(sx, sy);
}
private void OnEnemyHit(Hitbox hitbox, Node2D enemy)
@ -448,65 +436,37 @@ public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner,
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<IHitboxOwner>.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),
];
[Meta]
public sealed partial class Logic : AutoBlock
extension(Player.Action)
{
public sealed record Data
public static bool TryFromEvent(
InputEvent @event,
out Player.Action result
)
{
}
public Logic()
{
Set(new Data());
Preallocate<Root>();
}
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<Input.OnPhysicsProcess>
{
public Type On(in Input.OnPhysicsProcess input)
foreach (var (actionName, action) in Actions)
if (@event.IsAction(actionName))
{
throw new NotImplementedException();
result = action;
return true;
}
}
[Meta]
public sealed partial record Airborne : Root, IGet<Input.OnPhysicsProcess>
{
public Type On(in Input.OnPhysicsProcess input)
{
throw new NotImplementedException();
}
}
[Meta]
public sealed partial record Diving : Root, IGet<Input.OnPhysicsProcess>
{
public Type On(in Input.OnPhysicsProcess input)
{
throw new NotImplementedException();
}
}
result = default;
return false;
}
}
}