Gravity problem on Rigibody2D

I’m writing a script in C# in Unity that essentially functions as a switch to turn gravity on or off for a 2D Rigidbody. When the game starts, gravity should be 0 for the Rigidbody. Then when the user taps the space bar, gravity is supposed to increase to 3 (which is does). Then, however, when the player collides with a gameObject labeled ‘InvisGoal’, the player should teleport to another location and then gravity should be 0 again. However, the player always falls after coming in contact with InvisGoal and teleporting and I can’t figure out why. This is my first project in C# so sorry for any obvious errors… The script is here:

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

public class BallLaunch : MonoBehaviour {

    private Rigidbody2D myRigidBody;
    public GameObject Ball;

    // Use this for initialization
    void Start ()
 {
        myRigidBody = GetComponent<Rigidbody2D> ();
        GetComponent<Rigidbody2D>().gravityScale = 0f;
    }

    // Update is called once per frame
    void Update () 
{
        if (Input.GetButtonDown ("Jump"))
        {
            GetComponent<Rigidbody2D> ().gravityScale = 3f;
        }
}
    void OnTriggerEnter2D(Collider2D other){

        if (other.tag == "InvisGoal") 
        {
            Ball.gameObject.GetComponent<Rigidbody2D>().gravityScale = 0f;
            transform.position = new Vector3 (0.61f, 1.18f, 0f);
            return;
        }
     }
}

A couple of things I notice:

  1. you get the rigid body 2d component in Start(), but then never use it. You keep re-getting the component, instead :slight_smile:
  2. You adjust the gravity scale of the component on the game object in 2 examples, but then when you’re teleporting, you are adjusting the component on ‘Ball’. If Ball is not the current game object, you’re not modifying the correct component.

Hope that helps resolve it. If not, I’m not sure what else it could be, unless there is some movement code that is making it fall or something.

You’ll need to zero out the velocity also when you teleport. Setting the gravity scale to 0 won’t stop it’s existing velocity. An object in motion stays in motion… Calling myRigidBody.Sleep() in your OnTriggerEnter2D method should effectively do that.