Fix the frame-rate independent drag in a platformer

Review the AI's codeEasy10 min

Your task

Your platformer applied air drag as velocity.x *= 0.98 once per frame, so a 144 Hz machine slowed the player more than twice as fast as a 60 Hz one. The fix states drag per second and scales each frame's share by the frame's duration. The same stretch of time must leave the same speed at any frame rate.

An assistant wrote speed_after_drag(initial_speed, retention_per_second, frame_dt, frame_count). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • initial_speed: the speed before the frames run.
  • retention_per_second: the share of speed kept after one second of drag, such as 0.98.
  • frame_dt: each frame's duration in seconds.
  • frame_count: how many frames run.
  • Return the speed after the frames.

Rules the tests check:

  • If frame_count is 0 or less, or frame_dt is 0 or less, no time passed: return initial_speed.
  • If retention_per_second is 0 or less, return 0.
  • Otherwise each frame multiplies the speed by retention_per_second raised to the power frame_dt. So frames that add up to one second multiply it by exactly retention_per_second, whatever the frame rate.
  • Answers within 0.000001 of the expected value pass.

Examples

speed_after_drag(initial_speed: float, retention_per_second: float, frame_dt: float, frame_count: int) -> float
Example 1
Inputspeed_after_drag(10, 0.98, 0.016666666666666666, 60)
Output9.79999999999998
Example 2
Inputspeed_after_drag(10, 0.98, 0.006944444444444444, 144)
Output9.800000000000026
Example 3
Inputspeed_after_drag(10, 0.5, 1, 3)
Output1.25