12 C
New York
Tuesday, November 25, 2025

c++: need assistance with 2D participant driver


I am attempting to create a 2D aspect scrolling participant controller like in Terraria, however I can not get the delta time proper. If I set my laptop computer to battery saving mode, my character shakes (attributable to dt jitters), however performance-wise, every little thing is ok. It additionally appears that the decrease the body charge, the sooner the participant strikes.

   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 ? velocity : velocity * .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);
   // Deal with Y collision and floor examine
   pos.x = lerp(pos.x, pos.x + vel.x, smoothing);
   // Deal with X collision

Listed below are my constants if it helps:

constexpr float velocity = 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;
```

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles