C# Rigibody2D.Gravityscale problems

We were trying to trigger gravity on coillision when the player jumps out of the water. To prevent the player from “swimming” in the air. The gravity is suppose to turn off after a specific amount of time. Instead it doesn’t, so physics of the player and the gravity end up fight each other. Resulting in a jittery background.

Any help is appreciated :).

Gravity Trigger:

using UnityEngine;
using System.Collections;

public class GravityTrigger : MonoBehaviour {

    public Rigidbody2D TurtleBody;
    public float GravityInstensity;

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Player")
        {
            TurtleBody.gravityScale = GravityInstensity;
            print ( "Gravity is upon us");
            Invoke("NoGravity", 1f);
        }
    }
    void NoGravity()
    {
        TurtleBody.gravityScale = 0;
        print ("no gravity");
    }

}

Still currently looking for solutions.

Does NoGravity get called at all?

If it does, the only possibility I see is that TurtleBody isn’t assigned to the correct Rigidbody2D.

If the player enters the trigger multiple times then things will get messy. The Invoke called from a previous enter could cancel the new one.

There are multiple ways around this. The easiest will be to set up OnTriggerExit and reset the gravity there. The other is to implement some state variables and a coroutine so the gravity turns off 1 second after the last time the player enters the trigger.

well, I tried using the coroutine but that didn’t help. The gravity ended up pushing the player down and off the screen and the player thats connected to the camera jiggles spastically. Plus the gravity doesn’t stop after 1 second.

Modified code:

using UnityEngine;
using System.Collections;

public class GravityTrigger : MonoBehaviour {

    public Rigidbody2D TurtleBody;
    public float GravityInstensity;
   
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Player")
        {
            TurtleBody.gravityScale = GravityInstensity;
            print ( "Gravity is upon us");

            StartCoroutine (GravityReset());
        }
    }
    /*void NoGravity()
    {
        TurtleBody.gravityScale = 0;
        print ("no gravity");
    }*/

    IEnumerator GravityReset ()
    {
        TurtleBody.gravityScale = GravityInstensity;

        yield return new WaitForSeconds (1f);

        TurtleBody.gravityScale = 0;
    }
}

Currently still unsolved, will appreciate any help.