From bc37e46216b7fddbf6d2fbef1eaf399a586e59fc Mon Sep 17 00:00:00 2001 From: Aki Date: Mon, 18 Apr 2022 13:21:46 +0200 Subject: Added player speed dampening --- Player.cpp | 46 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/Player.cpp b/Player.cpp index c5be5a8..9e4be4d 100644 --- a/Player.cpp +++ b/Player.cpp @@ -8,8 +8,13 @@ #include "KeyboardController.h" -static constexpr float ACCELERATION {1900}; -static constexpr float MAX_SPEED {160}; +static constexpr float ACCELERATION {1800}; +static constexpr float MAX_SPEED {180}; +static constexpr float DAMP {2200}; +static constexpr float MARGIN {0.3f}; + + +static float damped_velocity(float dt, float direction, float velocity); Player::Player() : @@ -24,12 +29,8 @@ void Player::update(const float dt) { const auto direction = m_controller->direction(); - const Vector2 acceleration { - direction.x * ACCELERATION, - direction.y * ACCELERATION, - }; - m_velocity.x = std::clamp(m_velocity.x + acceleration.x * dt, -MAX_SPEED, MAX_SPEED); - m_velocity.y = std::clamp(m_velocity.y + acceleration.y * dt, -MAX_SPEED, MAX_SPEED); + m_velocity.x = std::clamp(damped_velocity(dt, direction.x, m_velocity.x), -MAX_SPEED, MAX_SPEED); + m_velocity.y = std::clamp(damped_velocity(dt, direction.y, m_velocity.y), -MAX_SPEED, MAX_SPEED); m_position.x += m_velocity.x * dt; m_position.y += m_velocity.y * dt; } @@ -40,3 +41,32 @@ Player::draw() { DrawCircle(m_position.x, m_position.y, 10, LIGHTGRAY); } + + +float +damped_velocity(const float dt, const float direction, const float velocity) +{ + if (direction > 0 || direction < 0) + return velocity + direction * ACCELERATION * dt; + if (velocity > 0) { + if (velocity > MARGIN) { + const float next = velocity - dt * DAMP; + if (next < MARGIN) + return 0; + else + return next; + } + return 0; + } + if (velocity < 0) { + if (velocity < MARGIN) { + const float next = velocity + dt * DAMP; + if (next > MARGIN) + return 0; + else + return next; + } + return 0; + } + return 0; +} -- cgit v1.1