Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

Usando interpolações físicas

Como nós incorporamos interpolações físicas em um jogo da Godot ? Existem algumas condições ?

Nós já tentamos deixar o sistema o mais fácil possível, e muitos jogos existentes trabalharão em poucas mudanças. Dito isso, têm situações que requerem um tratamento especial, e estas serão descritas.

Ativando a configuração de interpolações físicas

O primeiro passo é ativar as interpolações físicas em Project Settings > Physics > Common > Physics Interpolation. E você pode agora rodar o seu jogo.

É provável que nada se pareça muito diferente, particularmente se você estiver rodando a física em 60 TPS ou em algum múltiplo disso. Entretanto, tem bastante coisas acontecendo atrás das cenas.

Dica

Para converter um jogo existente para usar interpolação, é altamente recomendado definir temporariamente Project Settings > Physics > Common > Physics Tick per Second para um valor baixo, como 10, o que tornará os problemas de interpolação mais óbvios.

Mova (quase) toda a lógica de jogo de _process para _physics_process

The most fundamental requirement for physics interpolation (which you may be doing already) is that you should be moving and performing game logic on your objects within _physics_process (which runs at a physics tick) rather than _process (which runs on a rendered frame). This means your scripts should typically be doing the bulk of their processing within _physics_process, including responding to input and AI.

Setting the transform of objects only within physics ticks allows the automatic interpolation to deal with transforms between physics ticks, and ensures the game will run the same whatever machine it is run on. As a bonus, this also reduces CPU usage if the game is rendering at high FPS, since AI logic (for example) will no longer run on every rendered frame.

Nota

If you attempt to set the transform of interpolated objects outside the physics tick, the calculations for the interpolated position will be incorrect, and you will get jitter. This jitter may not be visible on your machine, but it will occur for some players. For this reason, setting the transform of interpolated objects should be avoided outside of the physics tick. Godot will attempt to produce warnings in the editor if this case is detected.

Dica

This is only a soft rule. There are some occasions where you might want to teleport objects outside of the physics tick (for instance when starting a level, or respawning objects). Still, in general, you should be applying transforms from the physics tick.

Garanta que todos os movimentos indiretos aconteçam durante os ticks de física

Consider that in Godot, nodes can be moved not just directly in your own scripts, but also by automatic methods such as tweening, animation, and navigation. All these methods should also have their timing set to operate on the physics tick rather than each frame ("idle"), if you are using them to move objects (these methods can also be used to control properties that are not interpolated).

Nota

Also consider that nodes can be moved not just by moving themselves, but also by moving parent nodes in the SceneTree. The movement of parents should therefore also only occur during physics ticks.

Escolha uma taxa de ticks de física

When using physics interpolation, the rendering is decoupled from physics, and you can choose any value that makes sense for your game. You are no longer limited to values that are multiples of the user's monitor refresh rate (for stutter-free gameplay if the target FPS is reached).

Um guia difícil:

Taxas de ticks baixas (10 - 30)

Taxas de ticks médias (30 - 60)

Taxas de ticks altas (60+)

Melhor desempenho da CPU

Bom comportamento de física em cenas complexas

Bom(a) com físicas rápidas

Adicione algum atraso para a entrada

Bom(a) para jogos de primeira pessoa

Bom(a) para jogos de corrida

Comportamento simples de física

Nota

Você sempre pode mudar a taxa de ticks, é tão simples quanto mudar as configurações do projeto.

Chame reset_physics_interpolation() quando estiver teletransportando objetos

Na maior parte do tempo, a interpolação é o que você quer entre dois ticks de física. Entretanto, tem uma situação aonde isso pode não ser o que você quer. Isso é quando você está inicialmente colocando objetos, ou movendo eles para um novo local. Aqui, você não quer um movimento suave entre onde o objeto estava e a posição inicial - você quer um movimento instantâneo.

The solution to this is to call the Node.reset_physics_interpolation function. What this function does under the hood is set the internally stored previous transform of the object to be equal to the current transform. This ensures that when interpolating between these two equal transforms, there will be no movement.

Even if you forget to call this, it will usually not be a problem in most situations (especially at high tick rates). This is something you can easily leave to the polishing phase of your game. The worst that will happen is seeing a streaking motion for a frame or so when you move them - you will know when you need it!

Existem dois jeitos de usar reset_physics_interpolation():

Ponto inicial (por exemplo, o jogador)

  1. Defina a transformação inicial

  2. Chame reset_physics_interpolation()

The previous and current transforms will be identical, resulting in no initial movement.

Início de movimento (como uma bala)

  1. Defina a transformação inicial

  2. Chame reset_physics_interpolation()

  3. Immediately set the transform expected after the first tick of motion

The previous transform will be the starting position, and the current transform will act as though a tick of simulation has already taken place. This will immediately start moving the object, instead of having a tick delay standing still.

Importante

Make sure you set the transform and call reset_physics_interpolation() in the correct order as shown above, otherwise you will see unwanted "streaking".

Testing and debugging tips

Even if you intend to run physics at 60 TPS, in order to thoroughly test your interpolation and get the smoothest gameplay, it is highly recommended to temporarily set the physics tick rate to a low value such as 10 TPS.

The gameplay may not work perfectly, but it should enable you to more easily see cases where you should be calling Node.reset_physics_interpolation, or where you should be using your own custom interpolation on e.g. a Camera3D. Once you have these cases fixed, you can set the physics tick rate back to the desired setting.

The other great advantage to testing at a low tick rate is you can often notice other game systems that are synchronized to the physics tick and creating glitches which you may want to work around. Typical examples include setting animation blend values, which you may decide to set in _process() and interpolate manually.

Nota

In 2D, the position of visible collision shapes shown by the Debug > Visible Collision Shapes option will take physics interpolation into account.

By contrast, in 3D, the position of visible collision shapes will not take physics interpolation into account. This means the visible collision shapes can appear to move less smoothly and appear slightly in front of the object's visual representation when the object is moving. This is not a bug, but a consequence of how physics interpolation is implemented in 3D.