Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Collision 2D

Discussion in '2D' started by Chunrand, Mar 7, 2015.

  1. Chunrand

    Chunrand

    Joined:
    Feb 21, 2015
    Posts:
    27
    Okay so I have a empty game object with only 1 script attached to it and I want when the player hits the ground to set the boolean to true but I want it to do it via this script not to make another one and inheritance it is it possible? Here is the script.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class gameManager : MonoBehaviour
    5. {
    6.     public GameObject player;
    7.     public Rigidbody2D playerRb2d;
    8.     public GameObject ground;
    9.     public GameObject obstacle;
    10.     public float speed;
    11.     public float jumpHeigh;
    12.     public bool canJump;
    13.  
    14.     void Update ()
    15.     {
    16.         playerRb2d.velocity = new Vector2 (speed, 0);
    17.  
    18.         if(Input.GetKey(KeyCode.Space) && canJump == true)
    19.         {
    20.             playerRb2d.velocity = new Vector2(0, jumpHeigh);
    21.             canJump = false;
    22.         }
    23.     }
    24.  
    25.     void OnCollisionEnter2D ()
    26.     {
    27.         canJump = true;
    28.     }
    29.  
    30.     void OnCollisionExit2D ()
    31.     {
    32.         canJump = false;
    33.     }
    34. }
     
  2. Teaky

    Teaky

    Joined:
    Oct 14, 2013
    Posts:
    7
    This logic should work, though it assumes all colliders are the ground, (I don't know that the rest of the code would necessarily work, just as an aside). One way to differentiate is to first add a tag to the transform that has the collider which represents the ground. Then pass a reference to this in the oncollisionenter function by putting Collision2D coll in the parenthesis. Then add an if statement which checks to make sure its the ground if (coll.transform.tag == "Ground") assuming that you used the tag Ground for ground.

    You might want to watch the 2d tutorials as they go over this.
     
  3. Chunrand

    Chunrand

    Joined:
    Feb 21, 2015
    Posts:
    27
    I tried like that just after I posted this and it worked, thanks anyway I was trying to achieve something else but I got it at the end via another script. Thanks.