Fix the frame-rate independent drag in a platformer
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 as0.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_countis 0 or less, orframe_dtis 0 or less, no time passed: returninitial_speed. - If
retention_per_secondis 0 or less, return 0. - Otherwise each frame multiplies the speed by
retention_per_secondraised to the powerframe_dt. So frames that add up to one second multiply it by exactlyretention_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) -> floatExample 1
Input
speed_after_drag(10, 0.98, 0.016666666666666666, 60)Output
9.79999999999998Example 2
Input
speed_after_drag(10, 0.98, 0.006944444444444444, 144)Output
9.800000000000026Example 3
Input
speed_after_drag(10, 0.5, 1, 3)Output
1.25