0
\$\begingroup\$

I'm new to Unity and C# (though I'm experienced in python) and I am trying to make a pong clone, I've spent ages googling and trying to fix this issue but for some reason my OnCollisionEnter2D won't work

My paddle hit method:

public void PaddleHit(Collision2D col)
{

    float y = WhereBallHitPaddle(transform.position,
        col.transform.position,
        col.collider.bounds.size.y);

    Vector2 dir = new Vector2();

    //determing direction to left or right depending on the paddle

    if (col.gameObject.name == "Player1")
    {
        dir = new Vector2(1, y).normalized;
    }
    if (col.gameObject.name == "Player2")
    {
        dir = new Vector2(-1, y).normalized;
    }

    rb.velocity = dir * speed;

    //play ball paddle collision sound
    SoundManager.Instance.PlayOneShot
        (SoundManager.Instance.ballpaddle);



}

When I run the game the ball moves, then when it comes into contact with a paddle it just stops moving, and if it comes into contact with a wall it bounces off, but at no point does it trigger the OnCollisionEnter2D. (I think my codes indents aren't showing properly here but it is all indented correctly, there are no compile errors or anything).

\$\endgroup\$
  • \$\begingroup\$ Did you meant to post a code for your OnCollisionEnter2D function? Because I am seeing 2 copies of your PaddleHit function in this post... \$\endgroup\$ – WQYeo Aug 8 '18 at 10:19
  • \$\begingroup\$ Can you show us where you define your OnCollisionEnter2D method? It needs to be named exactly that. \$\endgroup\$ – DMGregory Aug 8 '18 at 18:36
  • \$\begingroup\$ So normally you don't add a collider via statement. Simply add a collider on your gameobject and use the OnCollisionEnter function like the others mentioned. Spawn the player1, 2 etc. instead. Generally, its good practice to use as much as possible the editor and only use the code when you really have to (at least, this makes your code often times more efficient and more cleaner). Also, WhereBallHitPaddle seems to be not necessary. Instead, use OnTriggerEnter and call for action. See common game pattern design/tutorials,to get an better idea how to approach things inside unity like this. \$\endgroup\$ – Prometheus Aug 9 '18 at 21:47
2
\$\begingroup\$

You don't pass a Collision2D object to your paddle, instead as other people have suggested, do something like this:

void OnCollisionEnter2D(Collision2D collision)
{
    //put code here
    Debug.Log("Hello World");
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.