Gravity problem on Rigibody2D (Unity)

Updated on January 2, 2018 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
1 on January 2, 2018

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:

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class BallLaunch : MonoBehaviour {
  6.  
  7.     private Rigidbody2D myRigidBody;
  8.     public GameObject Ball;
  9.  
  10.     // Use this for initialization
  11.     void Start ()
  12.  {
  13.         myRigidBody = GetComponent<Rigidbody2D> ();
  14.         GetComponent<Rigidbody2D>().gravityScale = 0f;
  15.     }
  16.  
  17.     // Update is called once per frame
  18.     void Update ()
  19. {
  20.         if (Input.GetButtonDown (“Jump”))
  21.         {
  22.             GetComponent<Rigidbody2D> ().gravityScale = 3f;
  23.         }
  24. }
  25.     void OnTriggerEnter2D(Collider2D other){
  26.  
  27.         if (other.tag == “InvisGoal”)
  28.         {
  29.             Ball.gameObject.GetComponent<Rigidbody2D>().gravityScale = 0f;
  30.             transform.position = new Vector3 (0.61f, 1.18f, 0f);
  31.             return;
  32.         }
  33.      }
  34. }
  • Liked by
Reply
0 on January 2, 2018

Here are a few methods to try.

  1. Set the position first then the gravity
  2. Set the position a fraction higher than the position you want.

Let me know if any of these work, if not ill work something else out for you.

  • Liked by
Reply
Cancel