Files
AceField-New-Horizon/Scripts/Entities/Player.cs

66 lines
2.5 KiB
C#

using System;
using Godot;
namespace AceFieldNewHorizon.Scripts.Entities;
public partial class Player : CharacterBody2D
{
[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)
{
// Get direction to mouse and calculate angle
var mousePos = GetGlobalMousePosition();
var direction = GlobalPosition.DirectionTo(mousePos);
Rotation = direction.Angle();
}
public override void _PhysicsProcess(double delta)
{
// 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 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();
}
}