working around FixedUpdate-Physics Step execution order

Hi all,

I am trying to convert my 2d platformer controller from a raycast based system to a rigidbody based system, but I’m running into some trouble with the physics execution order that I don’t know how to resolve. This seems like a general enough problem that I thought I might be able to get help from people here :slight_smile:

The problem essentially boils down to these two small snippets of code. Originally, my fixed update call looked like this:

void FixedUpdate() //old version
{
     //update velocity from inputs, (prev frame) velocity and grounded flag
     compute_movement();
    
     //get a tentative delta for this frame
     Vector2 dxy = velocity * Time.deltaTime;
    
     //raycast in the directions of movement by length dxy to find hits
     //truncate dxy to the shortest hits in each direction
     CollisionInfo sides_touching = perform_raycasts(ref dxy);
    
     //zero this.velocity (*not* dxy) along the directions where there was a hit.
     //set the grounded flag if there was a hit on the bottom
     react_to_collisions(sides_touching);
    
     transform.translate(dxy)
}

After the port to rigidbodies, my code looks like this:

void FixedUpdate() //new, version 1
{
     //update velocity from inputs, (prev frame) velocity and grounded flag
     compute_movement();
    
     //get a tentative delta for this frame
     Vector2 dxy = velocity * Time.deltaTime;
    
     //move first, and allow builtin physics to prevent passing through geometry
     rigid_body.MovePosition(transform.position + (Vector3)dxy);

     //error: expecting physics step to update the contact points here!
    
     //check sides touching by reading the normals of each contact point
     //and checking against cardinal directions (everything is an AABB)
     CollisionInfo sides_touching = sides_from_contact_normals();
    
     react_to_collisions(sides_touching)
}

Obviously this doesn’t work because the physics step won’t update the contact points until after fixedupdate is done running. The result is that if the player jumps, there will be an extra frame where they are in the air but still register as grounded (this does cause different behavior for me in the game and is important).

I tried fixing this by moving the last bit of code into a coroutine like so, but am still having the same problem. If the player jumps, the contact points still arent cleared between the call to moveposition and the call to check_sides_from_contact_normals

void Start() //new, version 2
{
    //...
    StartCoroutine("post_fixed_update");
    //...
}

void FixedUpdate()
{
     //update velocity from inputs, (prev frame) velocity and grounded flag
     compute_movement();
    
     //get a tentative delta for this frame
     Vector2 dxy = velocity * Time.deltaTime;
    
     //move first, and allow builtin physics to prevent passing through geometry
     rigid_body.MovePosition(transform.position + (Vector3)dxy);
}

void post_fixed_update()
{
    while (true)
    {
         yield return new WaitForFixedUpdate();
         //check sides touching by reading the normals of each contact point
         CollisionInfo sides_touching = sides_from_contact_normals();
         react_to_collisions(sides_touching)
    }
}

(note that in all 3 cases, I am using my own Vector2 velocity)

Based on the execution order, it looks like this version should work, but when I step through with the debugger, I am still seeing sides_from_contact_normals() register a floor on the jump frame. Velocity is positive, the player’s position has moved up, and still I am getting a contact point where there shouldn’t be any.

Non-solutions: I am using highly nonphysical equations of motion so forces are out of the question. I also require all the precision I can get, so approximate detections of floors, walls, etc using boxcasts or spherecasts are unusable.

Has anyone else come across this problem? What is the way of getting around it?

Why would you expect that? As the docs state, “It is important to understand that the actual position change will only occur during the next physics update therefore calling this method repeatedly without waiting for the next physics update will result in the last call being used. For this reason, it is recommended that it is called during the FixedUpdate callback.”

If you’re not interested in dynamic contacts in-between those position movements (sweeps) because everything is Kinematic then you can set the Rigidbody2D position/rotation directly prior the to simulation step and just teleport there. Doing this means any spatial queries you perform (overlaps, casts etc) are immediately available. If you’re reading contacts though, they are only available from the last simulation step.

You are also free to manually perform the physics simulation step using Physics2D.Simulate() too if that helps. You can arrange for this to be done in a script that executes before any other FixedUpdate callback on any other MonoBehaviour by controlling the script execution order of the script. Also, you are free to simulate per-frame if you want. You can even do so without code by setting the Phyiscs2D.SimulationMode to Update.

Maybe expected is the wrong word to use. I only was trying to explain that that was the logical error in the code. I understand why the second example doesn’t work. I don’t understand why the third example doesn’t fix it. WaitForFixedUpdate happens after the physics step, doesn’t it?

Even if I put sides_from_contact_normals() and react_to_collisions() at the top of fixed update, I am still getting the same issue of having 1 frame contact delay. That seems like it obviously puts the execution order the right way yet the issue is the same

(E: I should add that Physics.SimulationMode isn’t available in my unity version, and querying with casts and overlaps brings me back to where I was with the raycast controller, which was insufficient in the first place because of large number of moving platforms with composite shapes, where I need to know the side that was hit, not just that there was one. A moving platform and a stationary player, e.g, would present a problem in that setup. Casting from every moving platform would slow the game to a crawl from the number and shapes of the platforms)

(E2: putting Physics2D.Simulate(Time.deltaTime) directly in between MovePosition and sides_from_contact_normals does not fix the one frame lag for me. In fact, when I step with the debugger, it doesn’t even look like Physics2D.Simulate updates the position before the next line is reached.)

I can confirm this issue and have helped @pleasefixthis as a Unity Live Expert.

Maybe it’s something we’re missing both, but a Bug report will be submitted by @pleasefixthis .

This indeed looks like some kind of editor bug.
I sent in a bug report and will also paste an example project here.

The following script illustrates the problem.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UnityBug : MonoBehaviour
{
    ContactPoint2D[] contacts = new ContactPoint2D[20];
    bool buffer_input = false;

    void Start()
    {
        StartCoroutine(after_physics_step());
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)) buffer_input = true;
    }

    void FixedUpdate()
    {
        if (buffer_input)
        {
            GetComponent<Rigidbody2D>().MovePosition(transform.position + Vector3.up);
        }
    }
    IEnumerator after_physics_step()
    {
        while (true)
        {
            yield return new WaitForFixedUpdate();
            if (GetComponent<Rigidbody2D>().GetContacts(contacts) > 0)
            {
                if (buffer_input) Debug.Log("contact points are lagging");
                else Debug.Log("touching");
            }
            else
            {
                Debug.Log("airborne");
            }

            buffer_input = false;
        }
    }
}

In a scene like the one in the attached image, I place this script on the white square and align it flush with a box collider 2D. Pressing space moves the white square off the box collider.

The frame that the white square moves, it runs fixedupdate, which calls MovePosition, then does a physics step, then does GetContacts. GetContacts returns contact points with the floor, even though there is a one unit gap between the white square and the floor after the physics step.

If you don’t like WaitForFixedUpdate you can manually step physics as suggested and then read contact points and you will get the same issue. This happens in the most recent version of unity but has existed as an error since at least the 2019 version.


7056688–837892–UnityBug.zip (22.2 KB)

If I follow what you’re saying, this isn’t a bug, it’s just not what you want. This comes up time and time again for 2D and 3D physics.

Contacts are not where it is in contact now, it’s where there was a contact at the start of the simulation step. The rest of the simulation step involves resolving the contact. When everything is solved, it doesn’t then recalculate all the contacts. Contacts are historic. This applies to both 2D (Box2D) and 3D (physx).

I guess I don’t understand what the intended method of precise grounded/side detection is then.

Every blogpost/tutorial I have come across has said to do one of two things:

  1. use forces and resign yourself to indirect control of player velocity

  2. use raycasts for hit detection

  3. doesn’t work, and if you try 2, you run into a problem with corners, as wall hits come up as floors, etc

the standard reply to this seems to be “only raycast in the direction of movement” which immediately breaks as soon as you add a moving platform.

“Just add raycasts from moving platforms also”. What if almost all platforms in your game are moving? with complex shapes?

Is there not some function that I can call to just do GJK/EPA against my player object, and grab the contact points?