Search Unity

Re-enable gravity when it has stopped its' collision with an object

Discussion in '2D' started by jpet1991, Nov 20, 2018.

  1. jpet1991

    jpet1991

    Joined:
    Sep 10, 2018
    Posts:
    35
    hello,

    my script disables the gravity of my enemy gameobjects once it collides with my tower gameobject which allows the enemy to "climb the tower". However, if the enemy were to stop colliding or touching the tower gravity is still disabled and the enemy just floats around the scene. I want gravity to be re-enabled so they aren't just floating in space.

    Here's my script:


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class ClimbTower : MonoBehaviour {
    6.     GameObject gameObjectEnemy;
    7.     DestroyObject destroyObject;
    8.  
    9.  
    10.  
    11.     bool climbTrue;
    12.  
    13.    
    14.     float tmpSpeed;
    15.     [SerializeField] float climbSpeed = .09f;
    16.  
    17.  
    18.  
    19.  
    20.     private void Update()
    21.     {
    22.         Move();
    23.        
    24.         Debug.Log(climbTrue);
    25.     }
    26.     public void OnCollisionEnter2D(Collision2D collision)
    27.     {
    28.         if (collision.gameObject.tag == "Tower")
    29.         {
    30.             climbTrue = true;
    31.             gameObject.GetComponent<Rigidbody2D>().gravityScale = 0f;
    32.         }
    33.      
    34.  
    35.     }
    36.  
    37.    
    38.  
    39.  
    40.     public void Move()
    41.     {
    42.        
    43.         if (climbTrue)
    44.         {
    45.             transform.Translate(0f, climbSpeed, 0f);
    46.         }
    47.  
    48.     }
    49.  
    50.    
    51.  
    52.  
    53. }
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    Can't you just use OnCollisionExit2D?
     
  3. jpet1991

    jpet1991

    Joined:
    Sep 10, 2018
    Posts:
    35
    haha definitely. i forgot/haven't used that one. I'll try it out, thanks man.