Kevin Lewis
Kevin Lewis

Reputation: 241

How can I detect where a collision occurs in Unity?

I'm trying to make a pong game and I need to detect where on the paddle the ball hits. How can I determine where the ball is relative to the paddle when they collide? Do I have to determine the position of each object and then compare or is there another way to do it, maybe using the getContact method?

void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "rightRect" || col.gameObject.tag == "leftRect")
    {
       //What do I put here?
    }

}

Once I get the relative position, I can do the math to figure out the direction the ball should go, I just need to get that value. Thanks!

Upvotes: 1

Views: 922

Answers (1)

Ruzihm
Ruzihm

Reputation: 20249

With OnCollisionEnter2D(Collision2D col) on the ball, you can easily compare the ball's position (transform.position) vs. the paddle's position (col.transform.position). You're probably most interested with their comparative position along the y axis, so that could look like this:

void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "rightRect" || col.gameObject.tag == "leftRect")
    {
       float ballYFromPaddle = transform.position.y - col.transform.position.y;

       // do stuff with ballYFromPaddle...
    }

}

Upvotes: 3

Related Questions