Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[SOLVED] 2D Collision problem

Discussion in 'Physics' started by pedrohb88, Sep 20, 2017.

  1. pedrohb88

    pedrohb88

    Joined:
    Aug 23, 2017
    Posts:
    16
    Hi everyone. I'm trying to do something very simple, when my "player" is on the ground, a text is set to true, but as you can see it does not work...




    Code (CSharp):
    1. public class PlayerController : MonoBehaviour {
    2.  
    3.     Rigidbody2D rb;
    4.     public float speed;
    5.     public Text bottomText;
    6.     public Text topText;
    7.     bool isOnGround;
    8.     bool isOnTop;
    9.     // Use this for initialization
    10.     void Start () {
    11.         rb = gameObject.GetComponent<Rigidbody2D> ();
    12.     }
    13.    
    14.     // Update is called once per frame
    15.     void Update () {
    16.  
    17.  
    18.         if (Input.GetKeyDown ("right")) {
    19.                 rb.velocity = new Vector2 (speed, 0);
    20.         }
    21.         if (Input.GetKeyDown ("left")) {
    22.                 rb.velocity = new Vector2 (-speed, 0);
    23.         }
    24.         if (Input.GetKeyDown ("up")) {
    25.                 rb.velocity = new Vector2 (0, speed);
    26.         }
    27.  
    28.         bottomText.text = isOnGround.ToString();
    29.         topText.text = isOnTop.ToString();
    30.     }
    31.  
    32.     void OnCollisionEnter(Collision col){
    33.  
    34.         if(col.gameObject.tag == "ground"){
    35.             isOnGround = true;
    36.         }
    37.         if(col.gameObject.tag == "top"){
    38.             isOnTop = true;
    39.         }
    40.     }
    41. }
     
  2. Plystire

    Plystire

    Joined:
    Oct 30, 2016
    Posts:
    142
    Object has gravity?

    Can you make player jump and watch it fall back to ground? Does OnCollisionEnter trigger when this happens? Try using Debug.Log(col.gameObject.name) in function to see in output log what all is detected during collision.
     
  3. pedrohb88

    pedrohb88

    Joined:
    Aug 23, 2017
    Posts:
    16
    I've already solved this. The problem was that i was using "OnCollisionEnter" instead "OnCollisionEnter2D". Thank you!