dancer-godot/src/player/Player.cs
2026-09-07 03:28:47 +02:00

657 lines
19 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.6f;
[Export(PropertyHint.None, "suffix:s⁻¹")]
public float GroundedSpeedStopDecay { get; set; } = 0.005f;
[Export(PropertyHint.None, "suffix:px/s")]
public float WalkMaxSpeed { get; set; } = 140.0f;
[Export(PropertyHint.None, "suffix:px/s")]
public float AirMaxSpeed { get; set; } = 140.0f;
[Export(PropertyHint.None, "suffix:px/s")]
public float WaterMaxSpeed { get; set; } = 220.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; } = 600.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; } = 190.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; } = 800.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;
[Export] public float DashPointRate { get; set; } = 0.5f;
private ulong MaxInputBufferTimeMicroseconds => (ulong)(MaxInputBufferTime * 1_000_000);
public bool IsJumping => !JumpTimer.IsStopped();
public bool IsWallJumping => !WallJumpTimer.IsStopped();
public bool IsDoingAnyJump => IsJumping || IsWallJumping;
/// The direction the player is currently holding.
/// This vector's components should always be -1/0/1.
private Vector2 _currentDirection = Vector2.Zero;
/// The raw direction the player is currently holding, no guarantees.
private Vector2 _currentRawDirection = Vector2.Zero;
public bool IsFacingRight { get; private set; } = true;
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 Node2D HandAttachment { get; set; } = null!;
[Node] private Timer JumpTimer { get; set; } = null!;
[Node] private Timer WallJumpTimer { get; set; } = null!;
[Node] private Timer JumpAllowedTimer { get; set; } = null!;
[Node] private Timer WallJumpAllowedTimer { get; set; } = null!;
[Node] private Timer WaterJumpAllowedTimer { get; set; } = null!;
[Node] private Timer DashTimer { get; set; } = null!;
[Node] private Timer DashDirectionChangeTimer { 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!;
[Node] private SpriteTrail SpriteTrail { get; set; } = null!;
public void OnReady()
{
this.Provide();
SetProcess(true);
SetPhysicsProcess(true);
Health = MaxHealth;
SubmersedSensor.BodyEntered += OnEnteredWater;
SubmersedSensor.AreaEntered += OnEnteredWater;
SubmersedSensor.BodyExited += OnLeftWater;
SubmersedSensor.AreaExited += OnLeftWater;
DashTimer.Timeout += () =>
{
Velocity = Velocity.LimitLength(WaterMaxSpeed);
var dot = _currentDirection.Normalized().Dot(Velocity.Normalized());
var slowdown = Mathf.Clamp(-dot + 0.2f, 0.0f, 0.5f);
Velocity *= 1f - slowdown;
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;
var dragAmount = 0f;
if (CanTurn) AdjustFacing();
// This one can be buffered indefinitely.
if (!WaterJumpAllowedTimer.IsStopped() && Input.IsActionPressed(ActionName.Jump))
{
WaterExitJump();
}
if (IsDashing)
{
if (!DashDirectionChangeTimer.IsStopped())
{
DashDirection = _currentDirection.IsZeroApprox()
? FacingVector
: _currentDirection.Normalized();
}
velocity = DashDirection * DashSpeed;
}
// Water movement
else if (IsInWater)
{
var velocityWasTooLarge = velocity.Length() > WaterMaxSpeed;
var inputDirection = _currentDirection;
if (Input.IsActionPressed(ActionName.Jump))
{
inputDirection.Y = -1f;
}
if (!velocityWasTooLarge || velocity.Dot(inputDirection) < 0f)
{
velocity += inputDirection.Normalized() * WaterAccel * deltaF;
}
var velocityIsTooLarge = velocity.Length() > WaterMaxSpeed;
if (velocityWasTooLarge && velocityIsTooLarge)
{
dragAmount = 0.015f;
}
if (!velocityIsTooLarge && inputDirection.IsZeroApprox())
{
dragAmount = 0.1f;
velocity = velocity.MoveToward(Vector2.Zero, 5f * 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
{
// Speed too high, but the player wants to carry momentum
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
{
var velocityWasTooLarge = Mathf.Abs(velocity.X) > AirMaxSpeed;
if (!velocityWasTooLarge || Mathf.Sign(_currentDirection.X) != Mathf.Sign(velocity.X))
{
velocity.X += Mathf.Sign(_currentDirection.X) * AirAccel * deltaF;
}
var velocityIsTooLarge = Mathf.Abs(velocity.X) > AirMaxSpeed;
if (!velocityWasTooLarge && velocityIsTooLarge)
{
velocity.X = Mathf.Clamp(velocity.X, -AirMaxSpeed, AirMaxSpeed);
}
dragAmount = _currentDirection.Normalized().Dot(Velocity.Normalized()) < 0.1f
? 0.015f
: 0.002f;
}
// Move up while holding jump
if (!JumpTimer.IsStopped())
{
velocity.Y = -JumpAscentSpeed;
}
else if (!IsOnFloor() && !IsInWater && DashTimer.IsStopped())
{
velocity += GetGravity() * deltaF;
}
if (IsDoingAnyJump) dragAmount = 0f;
velocity += Physics.DragForce(-velocity, dragAmount) * deltaF;
// Slow down descent while holding on to a wall
if (IsHoldingWall)
{
if (velocity.Y >= 0f)
velocity.Y = Mathf.MoveToward(velocity.Y * Mathf.Pow(0.0001f, deltaF), 0f, 750f * deltaF);
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() && !IsInWater)
JumpAllowedTimer.Start();
{
var addedDashPoints = DashPointRate * deltaF;
if (IsInWater)
{
DashPoints += BankedDashPoints;
BankedDashPoints = 0;
DashPoints = Mathf.Min(MaxDashPoints, DashPoints + addedDashPoints);
}
else BankedDashPoints = Mathf.Min(1f, BankedDashPoints + addedDashPoints);
}
if (IsOnCeiling()) JumpTimer.Stop();
if (IsOnWall()) WallJumpAllowedTimer.Start();
}
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
{
get
{
var wallNormal = GetWallNormal();
return !IsOnFloor()
&& IsOnWall()
// player holding into the wall
&& Mathf.Sign(wallNormal.X) != Mathf.Sign(_currentDirection.X)
// wall isn't too bad of an overhang
&& wallNormal.Y <= 0.05f
&& _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);
AnimationTree.Set("parameters/state/transition_request",
IsInWater
? "dive"
: IsOnFloor()
? "ground"
: "air"
);
AnimationTree.Set("parameters/holding_wall/blend_amount", IsHoldingWall ? 1f : 0f);
AnimationTree.Set("parameters/ground/blend_position", Mathf.Abs(Velocity.X));
AnimationTree.Set("parameters/air/blend_position", Velocity.Y);
AnimationTree.Set("parameters/dive/blend_position",
new Vector2(Mathf.Abs(Velocity.X), Velocity.Y));
AnimationTree.Set("parameters/dash_sm/dash/blend_position",
new Vector2(Mathf.Abs(Velocity.X), Velocity.Y));
}
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 !WallJumpAllowedTimer.IsStopped():
WallJump();
return true;
case { Action: Action.Jump, IsPressed: true }
when !WaterJumpAllowedTimer.IsStopped():
WaterExitJump();
return true;
case { Action: Action.Jump, IsPressed: false }
when IsDoingAnyJump:
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();
WallJumpAllowedTimer.Stop();
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()
{
if (!JumpTimer.IsStopped())
{
JumpTimer.Stop();
// Jump cut only once, if we're still moving up
if (Velocity.Y < 0)
Velocity *= new Vector2(1f, 0.1f);
}
if (!WallJumpTimer.IsStopped())
{
WallJumpTimer.Stop();
if (Velocity.Y < 0)
Velocity *= new Vector2(1f, 0.1f);
Velocity = Velocity.LimitLength(AirMaxSpeed);
}
}
private void Attack()
{
AdjustFacing();
// Velocity += (IsFacingRight ? Vector2.Right : Vector2.Left) * SlashSpeedBoost;
// _playback.Travel("front_kick");
// placeholder for directional attacks
var attackPlaceholderScene =
GD.Load<PackedScene>("res://src/player/attack_placeholder.tscn");
var attackPlaceholder = attackPlaceholderScene.Instantiate<Node2D>();
attackPlaceholder.Position = HandAttachment.GlobalPosition - GlobalPosition;
var targetDir = _currentDirection.IsZeroApprox()
? FacingVector
: _currentDirection;
attackPlaceholder.Rotation = Vector2.Up.AngleTo(targetDir);
AddChild(attackPlaceholder);
CreateTween().TweenCallback(Callable.From(attackPlaceholder.QueueFree)).SetDelay(0.2f);
}
private void WaterExitJump()
{
AdjustFacing();
WaterJumpAllowedTimer.Stop();
JumpTimer.Start();
}
private void Dash()
{
AdjustFacing();
DashPoints -= 1f;
DashTimer.Start();
DashDirectionChangeTimer.Start();
DashCooldownTimer.Start();
DashDirection = (_currentDirection.IsZeroApprox()
? FacingVector
: _currentDirection
).Normalized();
DashHitbox.StartAttack();
AnimationTree.Set("parameters/dash/request", (int)AnimationNodeOneShot.OneShotRequest.Fire);
Engine.Singleton.TimeScale = 0.1f;
SpriteTrail.CreateAfterImages = true;
var tween = CreateTween().SetEase(Tween.EaseType.InOut);
tween.TweenProperty(Engine.Singleton, "time_scale", 0.2f, 0.02);
tween.TweenProperty(Engine.Singleton, "time_scale", 0.5f, 0.01);
tween.TweenProperty(Engine.Singleton, "time_scale", 1.0f, 0.01).SetDelay(0.07);
tween.TweenCallback(Callable.From(() => SpriteTrail.CreateAfterImages = false)).SetDelay(0.05);
}
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 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;
}
}
}