0
\$\begingroup\$

I'm trying to create a 2D side-scrolling player controller like in Terraria, but I can't get the delta time right. If I set my laptop's mode to battery saver, my character jitters (from dt jitters), but on performance, everything is smooth. It also appears that the lower the framerate is, the faster the player moves.

   auto dt = GetFrameTime();
   auto dir = IsKeyDown(KEY_D) - IsKeyDown(KEY_A);

   if (not onGround) {
      vel.y = min(maxGravity * dt, vel.y + gravity * dt);
   } else {
      vel.y = min(maxGravity * dt, gravity * dt);
   }

   if (dir != 0) {
      auto speedX = (onGround ? speed : speed * .6f);
      vel.x = lerp(vel.x, dir * speedX * dt, acceleration);
   } else {
      vel.x = lerp(vel.x, 0.f, deceleration);
   }

   if (IsKeyDown(KEY_SPACE) and canHoldJump) {
      vel.y = jumpSpeed * dt;

      holdJumpTimer += dt;
      if (holdJumpTimer >= jumpHoldTime) {
         canHoldJump = false;
      }
   }

   if (onGround) {
      canHoldJump = true;
      holdJumpTimer = 0.f;
   } else if (not IsKeyDown(KEY_SPACE)) {
      canHoldJump = false;
   }

   pos.y = lerp(pos.y, pos.y + vel.y, smoothing);
   // Handle Y collision and ground check
   pos.x = lerp(pos.x, pos.x + vel.x, smoothing);
   // Handle X collision

Here are my constants if it helps:

constexpr float speed = 80.f;
constexpr float jumpSpeed = -100.f;
constexpr float gravity = 10.f;
constexpr float maxGravity = 200.f;
constexpr float acceleration = .083f;
constexpr float deceleration = .167f;
constexpr float smoothing = .333f;
constexpr float jumpHoldTime = .4f;
```
New contributor
Acerx.AMJ is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
2
  • \$\begingroup\$ take a look to this post that may help if I understand well your problem. gamedev.stackexchange.com/questions/215868/… \$\endgroup\$ Commented Nov 26 at 10:42
  • \$\begingroup\$ @philB Thanks! This post solved my issue. \$\endgroup\$ Commented Nov 26 at 14:25

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.