✨ Player movement with sprints and optimzation
This commit is contained in:
@@ -5,7 +5,11 @@ namespace AceFieldNewHorizon.Scripts.Entities;
|
||||
|
||||
public partial class Player : CharacterBody2D
|
||||
{
|
||||
[Export] public float Speed = 400.0f;
|
||||
[Export] public float MaxSpeed = 400.0f;
|
||||
[Export] public float SprintMultiplier = 1.8f; // 80% faster when sprinting
|
||||
[Export] public float Acceleration = 1500.0f;
|
||||
[Export] public float SprintAcceleration = 1800.0f; // Slightly faster acceleration when sprinting
|
||||
[Export] public float Deceleration = 1200.0f;
|
||||
[Export] public float RotationSpeed = 3.0f;
|
||||
|
||||
public override void _Process(double delta)
|
||||
@@ -20,10 +24,43 @@ public partial class Player : CharacterBody2D
|
||||
{
|
||||
// Get movement input
|
||||
var moveForward = Input.GetActionStrength("move_up") - Input.GetActionStrength("move_down");
|
||||
var moveHorizontal = Input.GetActionStrength("move_right") - Input.GetActionStrength("move_left");
|
||||
var isSprinting = Input.IsActionPressed("move_sprint");
|
||||
|
||||
// Calculate movement direction based on rotation
|
||||
Velocity = Vector2.Right.Rotated(Rotation) * moveForward * Speed;
|
||||
// Calculate movement parameters based on sprint state
|
||||
var currentMaxSpeed = isSprinting ? MaxSpeed * SprintMultiplier : MaxSpeed;
|
||||
var currentAcceleration = isSprinting ? SprintAcceleration : Acceleration;
|
||||
|
||||
// Calculate desired movement direction
|
||||
var forwardVector = Vector2.Right.Rotated(Rotation);
|
||||
var rightVector = new Vector2(-forwardVector.Y, forwardVector.X);
|
||||
|
||||
// Calculate target velocity based on input
|
||||
var targetVelocity = (forwardVector * moveForward + rightVector * moveHorizontal).Normalized() * currentMaxSpeed;
|
||||
|
||||
// Apply acceleration or deceleration
|
||||
var currentSpeed = Velocity.Length();
|
||||
var isAccelerating = targetVelocity != Vector2.Zero;
|
||||
|
||||
if (isAccelerating)
|
||||
{
|
||||
// Accelerate towards target velocity
|
||||
Velocity = Velocity.MoveToward(targetVelocity, (float)(currentAcceleration * delta));
|
||||
}
|
||||
else
|
||||
{
|
||||
// Apply deceleration when no input
|
||||
if (currentSpeed > 0)
|
||||
{
|
||||
var decelAmount = (float)(Deceleration * delta);
|
||||
if (currentSpeed <= decelAmount)
|
||||
Velocity = Vector2.Zero;
|
||||
else
|
||||
Velocity = Velocity.Normalized() * (currentSpeed - decelAmount);
|
||||
}
|
||||
}
|
||||
|
||||
// Apply the movement
|
||||
MoveAndSlide();
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user