Search code examples
c#unity-game-enginecollision-detection

Trying to get an object to bounce once on the ground - then when it falls again go through the ground


Here's the script:

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

public class groundCollision : MonoBehaviour
{
    public bool hasTouchedGround = false;

    public CircleCollider2D cC;

    void OnCollisionEnter(Collision collision)
    {
        if (collision.collider.tag == "ball")
        {
            hasTouchedGround = true;
        }
    }

    void Update()
    {
        if (hasTouchedGround == true)
        {
            cC.isTrigger = true;
        }
    }
}

I have two gameObjects. One is a ball, named "ball", with the tag "ball" and the other is a square that has been stretched on the X axis into a large rectangle and named "ground" with no tag. The ball has a rigidbody set to dynamic (there will be lots of balls and the point of the game is to click the balls as they fall to gain points) and a CircleCollider2D, and the gravity scale has been set to 0.5 (Although I had the same issue when using a normal gravity scale of 1).

I want the ball to be able to rebound off of the ground (which has a BoxCollider2D and a Physics Material 2D with a bounciness of 1) and be able to be clicked even if you missed it the first time, but I only want this to happen once, so I want the CricleCollider2D to become a trigger after it touches the ground once, allowing it to still be clicked but letting the ball fall through the ground next time. However, with this script, the collision isn't being detected.

When the ball hits the ground and bounces off, the boolean "hasTouchedGround" doesn't become true. What could be causing this? I double checked all my references and they are all good, the CircleCollider2D (cC) referenced in the script is set to the CircleCollider2D on the ball. I don't think it matters, but the ground object is off-screen slightly so the ball will go off screen for a split second then come back on screen for you to click again.


Solution

  • Since you are in unity2d, you need to make sure that everything you do is not 3d. Since you are detecting 2d collisions, you need to make sure that the right methods are being called.

    When testing this out, I tried putting a print statement in the OnCollisionEnter, and got nothing even when the ball hit it. This is because OnCollisionEnter is detecting 3d collisions, and OnCollisionEnter2D detects 2d collisions. If you use the 2d version, you also have to have 2d arguments. In this case, we use Collision2D instead of Collision.

    Here is what you should do:

        void OnCollisionEnter2D(Collision2D collision)
        {
            if (collision.collider.tag == "ball")
            {
                collision.collider.isTrigger = true;
            }
        }
    

    I changed your code a little big, but yours should work, if it doesn't, change yours to mine.