Pausing an objects physics simulation on collision with another object, while keeping its velocity

Hi,

I’m relatively new to Unity and C# coding. (I’m used to working with Java, so it’s been pretty easy to pick up.) But, I have been experimenting some in unity for the past few days, and in short what I want to accomplish is having a projectile of some kind, (with a rigidbody on it) hit a moving wall/plane, and pause its physics simulation, and once the wall has moved out of the path of the projectile, it will continue flying its original course as though nothing ever happened.

For now I have been using this C# code to somewhat achieve my goal.

This code is on the plane object that the projectile is hitting. It controls the movement of the plane, and the pausing of the test projectile.

public float moveSpeed = 0.1f;
    //public static string V;
   

    public void OnCollisionEnter(Collision col) {
        if (col.gameObject.name == "TSphere") {
            col.rigidbody.isKinematic = true;
                }
        }
    public void FixedUpdate () {
        transform.Translate(new Vector3(0, 0, 0.01f));
    }

This is the code on the projectile itself that handles resuming the physics simulation upon exiting the collision with the plane.

public void OnCollisionExit(Collision exit) {
        gameObject.rigidbody.isKinematic = false;

        }

Now as some of you I’m sure have noticed, is that I’m using OnCollisionEnter to pause the physics of the projectile. And as I was assuming would happen before I tested the code, it applies all the code that pauses the physics after it has realized that the projectile hit the wall. Therefore ruining the effect I was going for, which was the projectile hit the wall, pause, then continue flying as though nothing ever happened.

I’ve been doing some trial and error with trying to save the velocity and then re applying it using OnCollisionExit. But, it hasn’t been working out the way I was hoping it would. I believe my issue may just be that I’m not very familiar with C# and unity in general.

Any suggestions would be appreciated!

Thank you!

You could try to set a bool (‘isPaused’) to true/false in OnCollisionEnter/OnCollisionExit and run the code that sets it to kinematic in the Update() is isPaused is true. The idea is that this way the physics engine would have enough time to ‘push’ your bullet out of the wall and into the correct collision position.

Also, you would have to restore the velocity your self, as setting isKinematic to false will set the rigidbodies velocity to 0 (And angular velocity too). So, in OnCollisionEnter, store the bullets velocity (rigidbody.velocity) and in OnCollisionExit set the rigidbody.velocity to the value you have stored.