Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

Fixing jitter, stutter and input lag

What is jitter, stutter and input lag?

Джиттер и задержка это два разных изменения в визуальном движении объектов по экрану которые могут влиять на игру, даже при запуске на полной скорости. Эти эффекта главным образом видны в играх где мир движется с постоянной скоростью в фиксированном направлении, такие как раннеры или платформеры.

Input lag is unrelated to jitter and stutter, but is sometimes discussed alongside. Input lag refers to visible on-screen delay when performing actions with the mouse, keyboard, controller or touchscreen. It can be related to game code, engine code or external factors (such as hardware). Input lag is most noticeable in games that use the mouse to aim, such as first-person games. Input lag can't be completely eliminated, but it can be reduced in several ways.

Distinguishing between jitter and stutter

Игра запущенная с нормальной частотой кадров и без использования эффектов будет проигрываться гладко:

../../_images/motion_normal.gif

Игра с джиттером будет постоянно дёргаться в непонятной манере:

../../_images/motion_jitter.gif

Наконец, игра с задержкой будет проигрываться плавно, но будет приостанавливаться или откатывать кадр назад каждые пару секунд:

../../_images/motion_stutter.gif

Джиттер

Существует много причин вызывающие джиттер, самая обычная возникает когда игра с частотой физики (обычно 60 Гц) запускается в разрешении отличном от частоты обновления монитора. Проверьте если ваша частота монитора отличается от 60 Гц.

This is generally not a problem, given that most monitors are 60 Hz, and starting with Godot 3.1, a frame timer was introduced that tries to synchronize with refresh as well as possible.

Sometimes only some objects appear to jitter (character or background). This happens when they are processed in different time sources (one is processed in the physics step while another is processed in the idle step). Godot 3.1 does some improvements to this, from allowing kinematic bodies to be animated in the regular _process() loop, to further fixes in the frame timer.

Примечание

You can use physics interpolation to mitigate physics-related jittering. See lawnjelly's smoothing-addon for an add-on that can be dropped into any project to enable physics interpolation.

Задержка

Задержка может возникнуть из-за двух разных причин. Первое, и самое очевидное, если игра не может поддерживать производительность частоты кадров. Исправление этого зависит от игры и может потребоваться провести оптимизацию.

Другая причина более сложная, поскольку часто не связывается с движком или игрой но зависит от операционной системы. Здесь показана некоторая информация о задержках на различных OS.

On platforms that support disabling V-Sync, stuttering can be made less noticeable by disabling V-Sync in the project settings. This will however cause tearing to appear, especially on monitors with low refresh rates. If your monitor supports it, consider enabling variable refresh rate (G-Sync/FreeSync) while leaving V-Sync enabled. This avoids mitigating some forms of stuttering without introducing tearing.

Forcing your graphics card to use the maximum performance profile can also help reduce stuttering, at the cost of increased GPU power draw.

Windows

Система Windows часто вызывает задержки в оконных играх. Это часто зависит от установленного железа, версий драйверов или процессов запущенных параллельно (т.е. если открыто много вкладок браузера это может привести в задержкам в запущенной игре). Для избегания этого, начиная с 3.1, Godot поднимает приоритет игрового процесса на Выше Нормального. Это значительно помогает, но может не до конца исправлять задержки.

Полное исправление этого требует передачи вашей игре полных привилегий на то чтобы стать критичной по времени, что не рекомендуется. Некоторые игры могут делать это, но лучше научиться жить с этой проблемой, так как она распространена для Windows игр и большинство пользователей не играют в оконном режиме (игры которые играются в окне, напр. головоломки, в любом случае обычно не проявят эту проблему).

Для полноэкранного режима, Windows даёт игре специальный приоритет, так что игровые задержки не будут видны и станут очень редкими. Так работает большинство игр.

Совет

Games should use the Exclusive Fullscreen window mode, as opposed to Fullscreen which is designed to prevent Windows from automatically treating the window as if it was exclusive fullscreen.

Fullscreen is meant to be used by GUI applications that want to use per-pixel transparency without a risk of having it disabled by the OS. It achieves this by leaving a 1-pixel line at the bottom of the screen. By contrast, Exclusive Fullscreen uses the actual screen size and allows Windows to reduce jitter and input lag for fullscreen games.

Linux

Stutter may be visible on desktop Linux, but this is usually associated with different video drivers and compositors. Some compositors may also trigger this problem (e.g. KWin), so it is advised to try using a different one to rule it out as the cause. Some window managers such as KWin and Xfwm allow you to manually disable compositing, which can improve performance (at the cost of tearing).

There is no workaround for driver or compositor stuttering, other than reporting it as an issue to the driver or compositor developers. Stutter may be more present when playing in windowed mode as opposed to fullscreen, even with compositing disabled.

Feral GameMode can be used to automatically apply optimizations (such as forcing the GPU performance profile) when running specific processes.

macOS

В целом, macOS свободна от задержек, хотя недавно были найдены некоторые ошибки при запуске в полноэкранном режиме. Если вы владеете устройством демонстрирующим данное поведение, пожалуйста сообщите нам.

Android

Android в целом лишён джиттеров и задержек поскольку запущенный процесс получает полный приоритет. Однако, на некоторых устройствах могут возникать проблемы (старые Kindle Fire известны этим). Если вы увидели проблему на вашем Android устройстве, пожалуйста сообщите нам.

iOS

Устройства iOS в целом работают без задержек, но на старых устройствах запущенных на новых версиях операционной системы могут проявляться ошибки. Это в целом нельзя избежать.

Input lag

Project configuration

On platforms that support disabling V-Sync, input lag can be made less noticeable by disabling V-Sync in the project settings. This will however cause tearing to appear, especially on monitors with low refresh rates.

Increasing the number of physics iterations per second can also reduce physics-induced input latency. This is especially noticeable when using physics interpolation (which improves smoothness but increases latency). To do so, set Physics > Common > Physics Ticks Per Second to a value higher than the default 60, or set Engine.physics_ticks_per_second at run-time in a script. Values that are a multiple of the monitor refresh rate (typically 60) work best when physics interpolation is disabled, as they will avoid jitter. This means values such as 120, 180 and 240 are good starting points. As a bonus, higher physics FPSes make tunneling and physics unstability issues less likely to occur.

The downside of increasing physics FPS is that CPU usage will increase, which can lead to performance bottlenecks in games that have heavy physics simulation code. This can be alleviated by increasing physics FPS only in situations where low latency is critical, or by letting players adjust physics FPS to match their hardware. However, different physics FPS will lead to different outcomes in physics simulation, even when delta is consistently used in your game logic. This can give certain players an advantage over others. Therefore, allowing the player to change the physics FPS themselves should be avoided for competitive multiplayer games.

Lastly, you can disable input buffering on a per-rendered frame basis by calling Input.set_use_accumulated_input(false) in a script. This will make it so the _input() and _unhandled_input() functions in your scripts are called on every input, rather than accumulating inputs and waiting for a frame to be rendered. Disabling input accumulation will increase CPU usage, so it should be done with caution.

Hardware/OS-specific

If your monitor supports it, consider enabling variable refresh rate (G-Sync/FreeSync) while leaving V-Sync enabled, then cap the framerate in the project settings to a slightly lower value than your monitor's maximum refresh rate as per this page. For example, on a 144 Hz monitor, you can set the project's framerate cap to 141. This may be counterintuitive at first, but capping the FPS below the maximum refresh rate range ensures that the OS never has to wait for vertical blanking to finish. This leads to similar input lag as V-Sync disabled with the same framerate cap (usually less than 1 ms greater), but without any tearing.

This can be done by changing the Application > Run > Max FPS project setting or assigning Engine.max_fps at run-time in a script.

On some platforms, you can also opt into a low-latency mode in the graphics driver options (such as the NVIDIA Control Panel on Windows). The Ultra setting will give you the lowest possible latency, at the cost of slightly lower average framerates. Forcing the GPU to use the maximum performance profile can also further reduce input lag, at the cost of higher power consumption (and resulting heat/fan noise).

Finally, make sure your monitor is running at its highest possible refresh rate in the OS' display settings.

Also, ensure that your mouse is configured to use its highest polling rate (typically 1,000 Hz for gaming mice, sometimes more). High USB polling rates can however result in high CPU usage, so 500 Hz may be a safer bet on low-end CPUs. If your mouse offers multiple DPI settings, consider also using the highest possible setting and reducing in-game sensitivity to reduce mouse latency.

On Linux, disabling compositing in window managers that allow it (such as KWin or Xfwm) can reduce input lag significantly.

Reporting jitter, stutter or input lag problems

Если вы докладываете о задержке или джиттере (открывая проблему) не вызванную ни какой из вышеперечисленных проблем, пожалуйста точно опишите информацию об устройстве, операционной системе, версии драйверов, итд. Это может помочь для лучшего решения.

If you are reporting input lag problems, please include a capture made with a high speed camera (such as your phone's slow motion video mode). The capture must have both the screen and the input device visible so that the number of frames between an input and the on-screen result can be counted. Also, make sure to mention your monitor's refresh rate and your input device's polling rate (especially for mice).

Also, make sure to use the correct term (jitter, stutter, input lag) based on the exhibited behavior. This will help understand your issue much faster. Provide a project that can be used to reproduce the issue, and if possible, include a screen capture demonstrating the bug.