> For the complete documentation index, see [llms.txt](https://kinematicsoup.gitbook.io/reactor/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kinematicsoup.gitbook.io/reactor/guides/predictors.md).

# Motion Prediction

## Summary

Shows how to customise entity movement prediction using predictors.

* Configure predictors using predictor assets.
* Give an overview of the built-in predictors.
* Configure which properties are predicted and their prediction behaviour.
* Create a basic custom predictor that uses `Vector3.SmoothDamp` on position and linearly interpolates rotation.

## Predictor Assets

Predictors are used to predict or smooth entity motion. Predictors receive server transform and property updates, and control the transform and property values on the client. You can change the default predictors in the *'Default Predictors'* section of the *ksRoomType* component. There are four predictor fields:

* **Entity** The default predictor to use for entities that do not use input prediction. By default this is *'DefaultLinearPredictor'*.
* **Controller** The default predictor to use for entities controlled by the local player. By default this is *'DefaultConvergingInputPredictor'* If the player controller has `ksPlayerController.UseInputPrediction` set to false, the controlled entity will use the *'Entity'* predictor instead.
* **Room** The predictor for predicting room properties. By default this is none, which means room properties are not predicted.
* **Player** The predictor for predicting player properties. By default this is none, which means player properties are not predicted.

You can assign different predictors to an entity using the following fields in the *ksEntityComponent* inspector:

* **Predictor** The predictor to use when the entity is not controlled by the local player. If the checkbox is unchecked, it will use the default *'Entity'* predictor from the *ksRoomType*.
* **Controller Predictor** The predictor to use when the entity is controlled by the local player. If the checkbox is unchecked, it will use the default *'Controller'* predictor from the *ksRoomType*.

Some predictors, such as the *ksConvergingInputPredictor*, can only be used with player controllers and can only be assigned to the *ksRoomType*'s *'Controller'* field or the entity's *'Controller Predictor'*.

### Which Predictor an Entity Uses

Each client chooses a predictor for each entity based only on whether that client controls the entity. What moves the entity on the server doesn't matter.

| The entity, as seen by this client                                                                                                                                        | Predictor                                   | Default                                                                            |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | ---------------------------------------------------------------------------------- |
| Controlled by the local player with a player controller that uses input prediction (`UseInputPrediction`, on by default)                                                  | `ksEntity.InputPredictor`                   | The room type's *'Controller'* predictor, or the entity's *'Controller Predictor'* |
| Everything else: entities controlled by other players, entities moved only by server scripts or physics, and local entities whose controller doesn't use input prediction | `ksEntity.NonInputPredictor`                | The room type's *'Entity'* predictor, or the entity's *'Predictor'*                |
| Owned by the local player with the `TRANSFORM` permission                                                                                                                 | None. The client moves the entity directly. |                                                                                    |

Other clients never receive the player controller for an entity they don't control, so a player's own entity uses the input predictor on their client and the non-input predictor everywhere else. A locally controlled entity that server scripts also move still uses the input predictor; the server's changes arrive as server state the predictor converges toward.

## Predictor types

### ksLinearPredictor

[ksLinearPredictor](https://kinematicsoup.gitbook.io/reactor/api-reference/ks.reactor.client/ks.reactor.client.kslinearpredictor.md) is the default predictor for entities without player controllers. It will linearly interpolate between each server position. If it reaches the last known server position before a new server position is received, it continues to linearly extrapolate. The linear predictor uses the [ksTimeKeeper](https://kinematicsoup.gitbook.io/reactor/api-reference/ks.reactor.client/ks.reactor.client.kstimekeeper.md) to determine which point in time to render the entity at. This ensures all entities using the linear predictor are rendered at the same point in time. The time keeper has some properties you can set to configure the behaviour of the linear predictor. Create a linear predictor asset whose properties you can edit by right-clicking in the project window and selecting **'Create->Reactor->Linear Predictor'**, or use the built-in *'DefaultLinearPredictor'* asset.

*Connect Script*

```c#
    ...
    // Try to stay one sixtieth of a second behind the server when a new server frame arrives. Increasing this
    // value reduces the chance that we get ahead of the server and have to extrapolate which can lead to moving
    // entities momentarily penetrating other objects and popping out at the expense of increasing latency.
    // By default this is zero to have the minimum amount of latency.
    ksTimeKeeper timeKeeper = (ksTimeKeeper)room.Time.Adjuster;
    timeKeeper.TargetLatency = 1 / 60f;
    
    // Connect to the room
    room.Connect();
    ...
```

Entities that have owners with the `ksOwnerPermissions.TRANSFORM` permission use client-authoritative movement. They use a different time keeper that uses time deltas synced from the player who owns the entity. You can access an owning player's time data and time keeper using `Room.GetTime(playerId)` and `(ksTimeKeeper)Room.GetTime(playerId).Adjuster`.

### ksConvergingInputPredictor

[ksConvergingInputPredictor](https://kinematicsoup.gitbook.io/reactor/api-reference/ks.reactor.client/ks.reactor.client.ksconverginginputpredictor.md) is the default predictor for entities with player controllers that use input prediction. Accelerations are slower than on the server so that the client and server will converge. Create a converging input predictor asset whose properties you can edit by right-clicking in the project window and selecting **'Create->Reactor->Converging Input Predictor'**, or use the built-in *'DefaultConvergingInputPredictor'* asset.

#### Configuring the Converging Input Predictor From Code

The asset's settings are in the predictor's `Config`, a `ksConvergingInputPredictor.ConfigData`. Two things to know before changing it at runtime:

* **The config is shared.** Every entity created from the same predictor asset gets the same `ConfigData` object, so changing a field changes it for all of them. Clone the config, change the clone, and assign it back to give one entity its own settings.
* **`Config` is null while the predictor uses the built-in defaults.** Clone `ksConvergingInputPredictor.ConfigData.Default` in that case.

`ConfigData.MoveCheck` is the collision check the predictor runs when it moves the entity: a sweep and slide (4 iterations and up to 90 degrees of total slide angle by default, from the asset's *'Sweep And Slide Iterations'* and *'Max Total Slide Angle'*), followed by depenetration. Sliding follows the contact normal, so an entity pushed against a sloped surface, such as a ball or another vehicle, can be moved upward. You can wrap the check to constrain the result.

The following client entity script keeps a ground vehicle on the plane Y = 0 during prediction.

*Client Entity Script*

```c#
using KS.Reactor;
using KS.Reactor.Client;
using KS.Reactor.Client.Unity;

public class GroundVehiclePrediction : ksEntityScript
{
    public override void Initialize()
    {
        ksConvergingInputPredictor predictor = Entity.InputPredictor as ksConvergingInputPredictor;
        if (predictor == null)
        {
            return;
        }
        // Clone the config so the change only affects this entity.
        ksConvergingInputPredictor.ConfigData config = predictor.Config != null ?
            predictor.Config.Clone() : ksConvergingInputPredictor.ConfigData.Default.Clone();

        ksConvergingInputPredictor.MoveChecker moveCheck = config.MoveCheck;
        config.MoveCheck = (ksBaseEntity entity, ksVector3 start, ksVector3 target, bool isRenderPosition) =>
        {
            start.Y = 0f;
            target.Y = 0f;
            ksVector3 position = moveCheck == null ? target : moveCheck(entity, start, target, isRenderPosition);
            position.Y = 0f;
            return position;
        };
        predictor.Config = config;
    }
}
```

If you assign a different predictor to `Entity.InputPredictor` later, configure the new one the same way.

`MoveCheck` only constrains the predictor's own moves. It doesn't run on the motion your player controller produces when it processes input, and server corrections bypass it. Because the player controller runs on both the client and the server, constrain movement in the controller first, and use `MoveCheck` to keep the predictor's smoothing within the same limits.

> *Rigidbody constraints, such as freezing the Y position, don't apply to predicted movement. On the client, Reactor writes the entity's* *transform directly, and the Unity rigidbody is kinematic unless the local player owns the entity with the `TRANSFORM` permission. The* *constraints only affect the server's physics simulation, and reach the client as server corrections.*

### ksClientInputPredictor

[ksClientInputPredictor](https://kinematicsoup.gitbook.io/reactor/api-reference/ks.reactor.client/ks.reactor.client.ksclientinputpredictor.md) Predicts movement and properties using only the player controller; server data is ignored. This is mostly useful for debugging the see how your player controlled entity behaves on the client without influence from the server.

## Predicting Properties

Predictors can predict property values as well as transform data. To predict properties using a linear predictor or converging input predictor, you will need to create a linear predictor asset (**'Create/Reactor/Linear Predictor'**) or converging input predictor asset (**'Create->Reactor->Converging Input Predictor'**), and configure the *`Predicted Properties`* in the inspector with the properties you want to predict. Each property has a *'Type'* that determines how the property will be predicted. It can be set to one of the following:

* **Linear Float** - Use linear interpolation on a float.
* **Linear Vector2** - Use linear interpolation on a ksVector2.
* **Linear Vector3** - Use linear interpolation on a ksVector3.
* **Linear Color** - Use linear interpolation on a ksColor.
* **Wrap Float** - Use linear interpolation on a float and wrap onto a range defined by a min and max value.
* **Spherical Vector2** - Use spherical interpolation on a ksVector2.
* **Spherical Vector3** - Use spherical interpolation on a ksVector3.
* **Quaternion** - Use spherical interpolation on a ksQuaternion.
* **Client** - The client player controller has full control over the local property value. If the controller does not set the property value, the server value is used. The server is still authoritative; the client does not decide what other clients see.

## Changing Predictors at Runtime

To change the predictor used by an entity at runtime, assign a predictor to `ksEntity.InputPredictor` if the entity is controlled by the local player, and `ksEntity.NonInputPredictor` if it is not. `ksEntity.Predictor` is the active preditor the entity is using. You can change the predictor used for room or player properties by assigning `ksRoom.Predictor` or `ksPlayer.Predictor`.

Set `ksEntity.PredictionEnabled` to enable or disable prediction for an entity at runtime. When prediction is disabled the entity will not use either the `InputPredictor` or the `NonInputPredictor` and `ksEntity.Predictor` will be null.

The following room script shows how to dynamically disable prediction for distant entities. For large worlds with thousands of moving entities, this can improve the performance of the client.

*Client Room Script*

```c#
using UnityEngine;
using KS.Reactor.Client.Unity;

public class crPredictorDistanceFilter : ksRoomScript
{
    // Disable prediction for entities that are further from the camera than this.
    public float Distance = 25f;

    private void Update()
    {
        float distanceSquared = Distance * Distance;
        foreach (ksEntity entity in Room.DynamicEntities)
        {
            entity.PredictionEnabled = (entity.ServerTransform.Position - Camera.main.transform.position).MagnitudeSquared() <= distanceSquared;
        }
    }
}
```

## Following an Entity With a Camera

Reactor updates entity transforms in a step of Unity's player loop that runs right after `PreUpdate`, before any `MonoBehaviour.Update`. By the time `Update` and `LateUpdate` run, entity transforms are final for the frame; `FixedUpdate` runs earlier and sees the previous frame's transforms.

To follow an entity with a camera, read the entity's transform in `LateUpdate` and move the camera with it. The predictor has already smoothed the entity's motion, so smoothing the camera's position again makes it lag behind the entity and can look like jitter. If you want a softer camera, smooth only what the predictor doesn't, such as the camera's rotation or height.

## Custom Predictors

To create your own predictor script, right-click in the project browser. Select **'Create->Reactor->Predictor'.** The following is a very basic sample predictor that update the entity's position using `Vector3.SmoothDamp`, linearly interpolates rotation, and updates a float property with id 0 using `Mathf.SmoothDamp`. It can be used with or without a player controller, or just to predict property 0 on a room or player. To create an asset from it that can be assigned to an entity or as a default predictor in the room type, right-click in the project browser and select **'Create->Reactor->SamplePredictor'**.

*Sample Predictor*

```c#
using System;
using System.Collections.Generic;
using System.Collections;
using UnityEngine;
using KS.Reactor.Client.Unity;
using KS.Reactor.Client;
using KS.Reactor;

[CreateAssetMenu(menuName = ksMenuNames.REACTOR + "SamplePredictor", order = ksMenuGroups.SCRIPT_ASSETS)]
public class SamplePredictor : ksPredictor
{
    private ksReadOnlyTransformState m_serverTransform;
    private ksTransformState m_controllerTransform;
    private float m_serverProperty;
    private bool m_teleported = false;
    private Vector3 m_velocity;
    private float m_rotationSpeed;
    private float m_propertySpeed;

    // Initializes the predictor. Return false if initialization fails.
    public override bool Initialize()
    {
        if (Controller != null)
        {
            // Start the controller at the server location.
            m_controllerTransform = new ksTransformState(Entity.ServerTransform);
        }
        return true;
    }

    // Called when the predictor is removed. Performs clean up.
    public override void Detached()
    {
        // The base method clears the Entity/Room reference.
        base.Detached();
    }

    // Return true if the predictor will predict the property value.
    public override bool IsPredictedProperty(uint propertyId)
    {
        // Predict property 0
        return propertyId == 0;
    }

    // Called once per server frame. Perform any relevant calculations with server frame data here, and/or store
    // the relevant server frame data to be used in calculating future client state in the ClientUpdate method.
    // If it returns false and idle is true, this function will not be called again until the server transform
    // or a server property changes.
    public override bool ServerUpdate(ksReadOnlyTransformState transform, Dictionary<uint, ksMultiType> properties, bool teleport, bool idle)
    {
        m_serverTransform = transform;
        m_teleported = teleport;

        // Properties is null if none of the predicted properties changed.
        if (properties != null)
        {
            // Get the server property value.
            ksMultiType property;
            if (properties.TryGetValue(0, out property))
            {
                m_serverProperty = property;
            }
        }
        // State is null if the predictor is predicting room or player properties.
        if (!teleport && transform != null && Time.ServerUnscaledDelta > 0f)
        {
            // Calculate rotation interpolation speed.
            m_rotationSpeed = ksQuaternion.DeltaDegrees(transform.Rotation, Entity.GameObject.transform.rotation) / Time.ServerUnscaledDelta;
        }
        if (Controller != null)
        {
            // Move the controller to the server position.
            m_controllerTransform.Position = transform.Position;
            m_controllerTransform.Rotation = transform.Rotation;
            m_controllerTransform.Scale = transform.Scale;
            if (Controller.Properties.Contains(0))
            {
                Controller.Properties[0] = m_serverProperty;
            }
            // If there's a controller we want to receive all server updates so we can reposition the controller every time a
            // server update arrives.
            return true;
        }
        // Only call this function when the server values change.
        return false;
    }

    // Called once per client render frame to update the client transform and smoothed properties.
    // If it returns false, this function will not be called again until the server transform or a
    // server property changes.
    public override bool ClientUpdate(ksTransformState transform, Dictionary<uint, ksMultiType> properties)
    {
        // Properties is null if there are no predicted properties.
        if (properties != null)
        {
            if (m_teleported)
            {
                // Teleport to the server value.
                properties[0] = m_serverProperty;
                m_propertySpeed = 0f;
            }
            else if (Time.UnscaledDelta > 0f)
            {
                // Move towards the controller property value if there is a controller. Otherwise move towards the server value.
                float targetValue = Controller == null ? m_serverProperty : Controller.Properties[0];
                properties[0] = Mathf.SmoothDamp(properties[0], targetValue, ref m_propertySpeed, Time.UnscaledDelta);
            }
        }
        // State is null if the predictor is predicting room or player properties.
        if (transform == null)
        {
            return false;
        }
        transform.Scale = m_serverTransform.Scale;
        if (m_teleported)
        {
            // Teleport to the server position.
            m_teleported = false;
            transform.Position = m_serverTransform.Position;
            transform.Rotation = m_serverTransform.Rotation;
            m_velocity = ksVector3.Zero;
            return Controller != null;
        }
        if (Time.UnscaledDelta > 0f)
        {
            // Move towards the controller position if there is a controller. Otherwise move towards the server position.
            ksVector3 targetPosition = Controller == null ? m_serverTransform.Position : m_controllerTransform.Position;
            ksQuaternion targetRotation = Controller == null ? m_serverTransform.Rotation : m_controllerTransform.Rotation;

            // Smooth damp the position.
            transform.Position = Vector3.SmoothDamp(transform.Position, targetPosition, ref m_velocity, Time.UnscaledDelta);

            // Linearly interpolate rotation.
            transform.Rotation = ksQuaternion.RotateTowards(transform.Rotation, targetRotation, m_rotationSpeed * Time.UnscaledDelta);
        }
        // If there's a controller or we haven't reached the server position, we need more client updates.
        return Controller != null || transform.Position != m_serverTransform.Position || transform.Rotation != m_serverTransform.Rotation;
    }

    // Called when a new frame of input is generated. Only called for entities with player controllers.
    public override void InputUpdate(ksInput input)
    {
        // Update the player controller.
        ksPredictorUtils.UpdateController(Entity, m_controllerTransform, Time.UnscaledDelta, Time.TimeScale);
        input.CleanUp();
        if (!m_teleported && Time.ServerDelta > 0f)
        {
            // Calculate rotation interpolation speed.
            m_rotationSpeed = Math.Max(m_rotationSpeed,
                ksQuaternion.DeltaDegrees(m_controllerTransform.Rotation, Entity.GameObject.transform.rotation) / Time.ServerUnscaledDelta);
        }
    }
}
```
