How to turn off gravity for my player after a collision?

Viewed 1405

How do I turn off my gravity when my player runs into an object to create a cool flying collision effect

This is my code so far:

using UnityEngine;

public class PlayerCollision : MonoBehaviour{

    public PlayerMovement movement;
    void OnCollisionEnter (Collision CollisionInfo) {
        
        Debug.Log(CollisionInfo.collider.name);

        if (CollisionInfo.collider.tag == "Obstacle"){
            movement.enabled = false;
            // Rigidbody.useGravity = false;
        }
    }
}

I tried Rigidbody.useGravity = false; but it still doesn't work.

P.S.: Disabling movement means I can't control movement not that my player stops moving completely.

3 Answers

The best solution for you, is using GetComponent, it gets the rigidbody component of your player and you will be able to modify it:

public class PlayerCollision : MonoBehaviour{

    public PlayerMovement movement;
    void OnCollisionEnter (Collision CollisionInfo) {
        
        Debug.Log(CollisionInfo.collider.name);

        if (CollisionInfo.collider.tag == "Obstacle"){
            movement.enabled = false;
            GetComponent<Rigidbody>().useGravity = false;            
        }       
    }
}

Try linking the rigidbody. In the code you shared, it references the class, "Rigidbody" and not the rigidbody component on your player.

This can be done by using Get Component(). This script will work if your script is on the player object with a rigidbody:

public class PlayerCollision : MonoBehaviour
{

    public PlayerMovement movement;

    private Rigidbody rigidbody;

    void Start()
    {
        rigidbody = gameObject.GetComponent<Rigidbody>();
    }
    void OnCollisionEnter(Collision CollisionInfo)
    {

        Debug.Log(CollisionInfo.collider.name);

        if (CollisionInfo.collider.tag == "Obstacle")
        {
            movement.enabled = false;
            rigidbody.useGravity = false;

        }


    }
}

Or you could make the rigidbody component public like so and assign it through the unity editor:

public class PlayerCollision : MonoBehaviour
{

    public PlayerMovement movement;

    public Rigidbody rigidbody;

    void OnCollisionEnter(Collision CollisionInfo)
    {

        Debug.Log(CollisionInfo.collider.name);

        if (CollisionInfo.collider.tag == "Obstacle")
        {
            movement.enabled = false;
            rigidbody.useGravity = false;

        }


    }
}
if (CollisionInfo.collider.tag == "Obstacle"){
            movement.enabled = false;
            col = GetComponent<Collider>();
            // Rigidbody.useGravity = false;
           if (col.attachedRigidbody)
             col.attachedRigidbody.useGravity = false;
        }

Gravity get exactly object must attached gravity and you must using when getting col or object has attached it.

Related