dancer-godot/src/player/Player.cs
2026-08-28 16:44:15 +02:00

545 lines
15 KiB
C#

using System.Collections.Generic;
namespace Dancer;
[Meta(typeof(IAutoNode))]
public sealed partial class Player : CharacterBody2D, IAttackable, IHitboxOwner, IHurtboxOwner,
IProvide<IHitboxOwner>, IProvide<IHurtboxOwner>
{
public override void _Notification(int what) => this.Notify(what);
[Export(PropertyHint.None, "suffix:s")]
public float MaxInputBufferTime { get; set; } = 0.15f;
/// <summary>
/// The speed decay used when the player continues movement in the direction they're going.
/// </summary>
[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:px/s")]
public float JumpAscentSpeed { get; set; } = 200.0f;
[Export(PropertyHint.None, "suffix:px/s")]
public float SlashSpeedBoost { get; set; } = 90.0f;
[Export(PropertyHint.None, "suffix:px/s")]
public float DashSpeed { get; set; } = 400.0f;
/// <summary>The angle difference from perfect left/right that still counts.</summary>
[Export(PropertyHint.Range, "0,360,0.1,radians_as_degrees")]
public float SideInputAngle { get; set; } = Mathf.Pi / 4;
/// <summary>The angle difference from perfect down that still counts.</summary>
[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 => !JumpTimer.IsStopped();
/// The direction the player is currently holding.
/// This vectors components should always be -1/0/1.
private Vector2 _currentRawDirection = Vector2.Zero;
private Vector2 _currentDirection = Vector2.Zero;
public bool IsFacingRight { get; private set; } = true;
private AnimationNodeStateMachinePlayback _playback = null!;
public List<BufferedInput> InputBuffer { get; } = [];
public bool IsInWater { get; private set; }
public bool IsDashing => !DashTimer.IsStopped();
public Vector2 DashDirection { get; set; }
public float DashPoints { get; set; }
public float BankedDashPoints { get; set; }
[Node] private AnimationTree AnimationTree { get; set; } = null!;
[Node] private Area2D SubmersedSensor { get; set; } = null!;
[Node] private Hitbox DashHitbox { get; set; } = null!;
[Node] private Timer JumpTimer { get; set; } = null!;
[Node] private Timer JumpAllowedTimer { get; set; } = null!;
[Node] private Timer WaterJumpAllowedTimer { get; set; } = null!;
[Node] private Timer DashTimer { get; set; } = null!;
[Node] private Timer DashCooldownTimer { get; set; } = null!;
[Node] private Timer GlobalDamageImmunityTimer { get; set; } = null!;
[Node] private Timer PlatformIgnoreTimer { get; set; } = null!;
[Node] private Timer ParryTimer { get; set; } = null!;
public void OnReady()
{
this.Provide();
SetProcess(true);
SetPhysicsProcess(true);
Health = MaxHealth;
_playback = AnimationTree.Get("parameters/playback").As<AnimationNodeStateMachinePlayback>();
SubmersedSensor.BodyEntered += OnEnteredWater;
SubmersedSensor.AreaEntered += OnEnteredWater;
SubmersedSensor.BodyExited += OnLeftWater;
SubmersedSensor.AreaExited += OnLeftWater;
DashTimer.Timeout += () =>
{
Velocity *= 0.6f;
DashHitbox.StopAttack();
};
}
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))
{
_currentRawDirection = Input.GetVector(
ActionName.MoveLeft,
ActionName.MoveRight,
ActionName.MoveUp,
ActionName.MoveDown);
_currentDirection = To8DirectionVector(_currentRawDirection);
}
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 (!DashTimer.IsStopped())
{
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 (!JumpTimer.IsStopped())
{
velocity.Y = -JumpAscentSpeed;
}
else if (!IsOnFloor() && !IsInWater && DashTimer.IsStopped())
{
velocity += GetGravity() * deltaF;
}
if (DashTimer.IsStopped())
{
// Drag in water
if (IsInWater)
{
if (_currentDirection.IsZeroApprox() || IsHoldingWall)
{
velocity += Physics.DragForce(-velocity, 0.2f) * deltaF;
}
else
{
velocity += Physics.DragForce(-velocity, 0.015f) * deltaF;
}
}
// Drag while in air
else if (!IsOnFloor() && JumpTimer.IsStopped())
{
velocity += Physics.DragForce(-velocity, 0.009f) * deltaF;
}
}
if (IsHoldingWall)
{
velocity.Y = Mathf.Min(velocity.Y, 5.0f);
IsFacingRight = Mathf.Sign(GetWallNormal().X) > 0;
}
var collideWithPlatforms = PlatformIgnoreTimer.IsStopped();
// layer 7 is platforms
SetCollisionMaskValue(7, collideWithPlatforms);
Velocity = velocity;
MoveAndSlide();
{
var count = GetSlideCollisionCount();
for (var i = 0; i < count; i++)
{
var collision = GetSlideCollision(i);
if (collision.GetCollider() is not TileMapLayer tileMapLayer)
continue;
var collisionPos = collision.GetPosition() + collision.GetTravel();
var mapCoords = tileMapLayer.GlobalToMap(collisionPos);
if (tileMapLayer.GetCellTileData(mapCoords) is not { } tileData)
continue;
if (!tileData.HasCustomData("damage")
|| tileData.GetCustomData("damage") is not { VariantType: Variant.Type.Float } variant)
continue;
if (variant.AsSingle() is > 0f and var damage)
TakeDamage(damage);
}
}
if (IsOnFloor())
JumpAllowedTimer.Start();
{
var addedDashPoints = 3f * deltaF;
if (IsInWater)
{
DashPoints += BankedDashPoints;
BankedDashPoints = 0;
DashPoints = Mathf.Min(MaxDashPoints, DashPoints + addedDashPoints);
}
else BankedDashPoints = Mathf.Min(1, BankedDashPoints + 3f * addedDashPoints);
}
if (IsOnCeiling()) JumpTimer.Stop();
}
public void OnEnteredWater(Node2D body) => IsInWater = true;
public void OnLeftWater(Node2D body)
{
if (!IsInWater || SubmersedSensor.HasOverlappingBodies()) return;
IsInWater = false;
WaterJumpAllowedTimer.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 =>
!IsOnFloor()
&& IsOnWall()
&& Mathf.Sign(GetWallNormal().X) != Mathf.Sign(_currentDirection.X)
&& _currentDirection.X != 0;
public void OnProcess(double delta)
{
var body = GetNode<Node2D>("%Body");
body.Scale = new(IsFacingRight ? 1 : -1, 1);
body.Modulate = ParryTimer.IsStopped() ? Colors.White : new(2f, 2f, 2f);
}
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,
Parry,
}
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;
}
}
}
/// <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 !JumpAllowedTimer.IsStopped()
&& (!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 !WaterJumpAllowedTimer.IsStopped():
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 DashCooldownTimer.IsStopped() && DashPoints >= 1f:
Dash();
return true;
case { Action: Action.Parry, IsPressed: true }:
Parry();
return true;
default:
return false;
}
}
private void DropDown() => PlatformIgnoreTimer.Start();
private void GroundJump()
{
AdjustFacing();
JumpAllowedTimer.Stop();
JumpTimer.Start();
}
private void WallJump()
{
AdjustFacing();
JumpAllowedTimer.Stop();
JumpTimer.Start();
var wallDirection = (float)Mathf.Sign(GetWallNormal().X);
var upwardComponent = IsInWater ? 0f : -.4f;
var direction = new Vector2(wallDirection, upwardComponent).Normalized();
Velocity = direction * 200.0f;
}
private void JumpCut()
{
JumpTimer.Stop();
// 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();
WaterJumpAllowedTimer.Stop();
JumpTimer.Start();
}
private void Dash()
{
AdjustFacing();
DashPoints -= 1f;
DashTimer.Start();
DashCooldownTimer.Start();
DashDirection = (_currentDirection.IsZeroApprox()
? FacingVector
: To4DirectionVector(_currentRawDirection)
).Normalized();
DashHitbox.StartAttack();
_playback.Travel("side_dash");
}
private void Parry() => ParryTimer.Start();
private static Vector2 To8DirectionVector(Vector2 input)
{
if (input.IsZeroApprox()) return Vector2.Zero;
const float tan225 = 0.414213562f; // 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 static Vector2 To4DirectionVector(Vector2 input)
{
if (input.IsZeroApprox()) return Vector2.Zero;
Vector2 a = input.Abs(), s = input.Sign();
return
a.Y < a.X ? new(s.X, 0) : new(0, s.Y);
}
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)
{
if (!ParryTimer.IsStopped()) return;
TakeDamage(attack.Damage);
}
public void TakeDamage(float amount)
{
if (!GlobalDamageImmunityTimer.IsStopped()) return;
Health -= amount;
GlobalDamageImmunityTimer.Start();
}
public void OnHitboxAdded(Hitbox hitbox) => hitbox.TargetHit += OnEnemyHit;
public void OnHitboxRemoved(Hitbox hitbox) => hitbox.TargetHit -= OnEnemyHit;
IHitboxOwner IProvide<IHitboxOwner>.
Value() => this;
public enum Move
{
}
public void OnAttacked(Hurtbox hurtbox, in Attack attack)
{
GetAttacked(attack);
}
public void OnHurtboxAdded(Hurtbox hurtbox)
{
hurtbox.Attacked += OnAttacked;
}
public void OnHurtboxRemoved(Hurtbox hurtbox)
{
hurtbox.Attacked -= OnAttacked;
}
public IHurtboxOwner 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),
(ActionName.Parry, Player.Action.Parry),
];
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;
}
}
}