PredictionRigidbody

This class provides accurate simulations and re-simulations when applying outside forces, most commonly through collisions.

Using PredictionRigidbody is very straight forward. In short, you move from applying force changes to the rigidbody onto the PredictionRigidbody instance instead.

There are a few more steps, but equally simple.

This guide assumes you are familiar with the Getting Started section.

This bit shows the changes for adding forces to your rigidbody, or rather now the PredictionRigidbody.

public class RigidbodyPlayer
{
    //First implement the field.
    public PredictionRigidbody PredictionRigidbody { get; private set; } = new();
    
    //Make calls to PredictionRigidbody in your replicate method.
    [Replicate]
    private void Move(MoveData md, ReplicateState state = ReplicateState.Invalid, Channel channel = Channel.Unreliable)
    {
        Vector3 forces = new Vector3(md.Horizontal, 0f, md.Vertical) * _moveRate;
        PredictionRigidbody.AddForce(forces);
        PredictionRigidbody.AddForce(Physics.gravity * 3f);
        //Simulate the added forces by calling Simulate on PredictionRigidbody.
        PredictionRigidbody.Simulate();
    }

PredictionRigidbody must also be reconciled. Be sure to include it in your reconcile data.

This is also covered in the Getting Started guide.

    public struct ReconcileData : IReconcileData
    {
        public RigidbodyState RigidbodyState;
        public PredictionRigidbody PredictionRigidbody;

In your reconcile method you must update your PredictionRigidbody reference using the value from your reconcile data.

    [Reconcile]
    private void Reconciliation(ReconcileData rd, Channel channel = Channel.Unreliable)
    {
        //your other reconcile stuff...
        
        //You do not need to put this at the end of the method.
        PredictionRigidbody.Reconcile(rd.PredictionRigidbody);
    }

To add outside forces to your rigidbody you will want to apply them instead to the PredictionRigidbody. As mentioned at the very beginning, this is most commonly seen with collisions.

For triggers and collisions to work properly with prediction you must use our NetworkTrigger/NetworkCollision components. Otherwise, due to a Unity limitation, such interactions would not work. You can learn more about those components here.

Fun fact: Fish-Networking is the only framework that has the ability to simulate Enter/Exit events with prediction; not even Fusion does this!

private void NetworkTrigger_OnEnter(Collider other)
{
    //Add upward impulse when hitting this trigger.
    if (other.TryGetComponent<RigidbodyPlayer>(out rbPlayer))
        rbPlayer.PredictionRigidbody.AddForce(Vector3.up, ForceMode.Impulse);

}

Last updated