using System.Threading;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
[Header("Movement")]
public float MovementAcceleration;
public float MovementDrag;
[Header("Dash")]
public float DashSpeed;
public float DashDuration;
public float DashSlowdown;
public Key DashKey = Key.Space;
public float MaxDashFlash;
public float DashCooldown;
public float CurrentDashCooldown;
private float xVelocity;
private float yVelocity;
private float xInput;
private float yInput;
public bool isDashing;
private float dashTimer;
private Vector2 dashDirection;
private SpriteRenderer playerSprite;
private Color originalColor;
void Start()
{
playerSprite = GetComponentInChildren<SpriteRenderer>();
originalColor = playerSprite.color;
}
void Update()
{
HandleInputs();
HandleMovement();
float brightness = Mathf.Lerp(1f, MaxDashFlash, dashTimer / DashDuration);
playerSprite.color = originalColor * brightness;
if (CurrentDashCooldown > 0)
{
CurrentDashCooldown -= Time.deltaTime;
} else { CurrentDashCooldown = 0; }
}
private void HandleInputs()
{
if (isDashing)
return;
xInput = (Keyboard.current.dKey.isPressed ? 1f : 0f)
- (Keyboard.current.aKey.isPressed ? 1f : 0f);
yInput = (Keyboard.current.wKey.isPressed ? 1f : 0f)
- (Keyboard.current.sKey.isPressed ? 1f : 0f);
if (Keyboard.current[DashKey].wasPressedThisFrame && (xInput != 0 || yInput != 0) && CurrentDashCooldown <= 0)
{
isDashing = true;
dashTimer = DashDuration;
CurrentDashCooldown = DashCooldown;
dashDirection = new Vector2(xInput, yInput).normalized;
}
}
private void HandleMovement()
{
if (isDashing)
{
if (dashTimer > 0)
{
xVelocity = dashDirection.x * DashSpeed;
yVelocity = dashDirection.y * DashSpeed;
dashTimer -= Time.deltaTime;
}
else
{
float slowdownFactor = 1 - DashSlowdown * Time.deltaTime;
xVelocity *= slowdownFactor;
yVelocity *= slowdownFactor;
if (new Vector2(xVelocity, yVelocity).magnitude < 10f)
isDashing = false;
}
}
else
{
xVelocity += xInput * MovementAcceleration;
yVelocity += yInput * MovementAcceleration;
xVelocity *= 1 - MovementDrag * Time.deltaTime;
yVelocity *= 1 - MovementDrag * Time.deltaTime;
}
Vector2 movement = new Vector2(xVelocity, yVelocity) * Time.deltaTime;
transform.position += (Vector3)movement;
}
}