Unity collider going through other colliders at ti

2019-08-13 10:25发布

问题:

I'm trying to create a Pong clone for practice. I setup my project in 2D.

The paddle has the following components:

  • -Rigidbody2D (set to kinematic)
  • -BoxCollider2D (is a trigger)

The ball has the following components:

  • -Rigidbody2D (set to kinematic)
  • -CircleCollider2D (is a trigger)

The paddle is controlled via dragging (user dragging finger on screen left/right). I used the EasyTouch plugin for this.

Then I move the ball with this script:

void Update () {
        transform.position += new Vector3(xSpeed * Time.deltaTime, ySpeed * Time.deltaTime);
    }

This is how I detect collisions and redirect the ball once it hits something (Horizontal objects are the top/bottom/paddle while Vertical objects are the left/right screen border):

void OnTriggerEnter2D(Collider2D c)
    {
        if(c.gameObject.tag.Equals("Horizontal"))
        {
            ySpeed *= -1;
        }
        else if(c.gameObject.tag.Equals("Vertical"))
        {
            xSpeed *= -1;
        }

    }

The problem is sometimes the ball goes through the paddle which can look glitchy to the end-user. I've searched about this online and I've tried to set the rigidbody's Collision Detection property to Continuous instead of Discrete. But the ball still goes through the paddle at certain times.

Anyone know how to solve this? What am I doing wrong with how I setup/coded my game?

Thanks

回答1:

You have a very simple concept error. OnTriggerEnter2D(Collider2D) is to get if the collider has entered other collider. In other words you can go through the object.

you need to use this function instead:

OnCollisionEnter2D(Collision2D coll)

I suggest you to watch this Unity tutorial because it explains all this really good: https://unity3d.com/learn/tutorials/modules/beginner/physics/colliders

Additional info : http://docs.unity3d.com/ScriptReference/Collider2D.html

Thanks.



回答2:

As the code shows, the transform is controlled by yourself while the continuous detection requires control of physics engine, so try to control the gameObject with physics engine instead give it a position modified by your own code.