2

so I'm making a 2D platformer game with 360° shooting in Unity. I want my bullets to be reflected when they hit something (think billiard).

The code below works if bullets ricochet off of the ceiling or the floor. The problem is that when i hit something from the side the new direction of the bullet is exactly 180° off.

    private void OnTriggerEnter2D(Collider2D col)
{
    if (col.gameObject.tag != "Player" && col.gameObject.tag != "Bullet")
    {
        ContactPoint2D[] contacts = new ContactPoint2D[10];
        col.GetContacts(contacts);

        Vector3 currentBulletMoveVector = transform.right;
        Vector2  newBulletMoveVector = Vector2.Reflect(currentBulletMoveVector, contacts[0].normal);

        transform.right = new Vector3(newBulletMoveVector.x, newBulletMoveVector.y, 0);
    }
}

Any advice on where I went wrong or how to fix this?

oHoodie
  • 209
  • 4
  • 13
  • Possible duplicate of [Reflect a projectile on collision in Unity](https://stackoverflow.com/questions/49790711/reflect-a-projectile-on-collision-in-unity) although yours would use 2D logic instead – Ruzihm Nov 08 '18 at 18:29
  • unfortunately the answer on that question didn't help as I'm not using rigidbody & velocity. – oHoodie Nov 08 '18 at 18:36
  • where do you keep track of what direction the bullet is going? Is that always `transform.right`? Also, when you say "the new direction" is off, do you mean specifically the travel direction is off, or is it only the orientation of the transform that is wrong, and the bullet is traveling in the correct direction? – Ruzihm Nov 08 '18 at 18:52
  • Yes the direction my bullet is going is always transform.right. And to set the new direction i set transform.right to a new value. I just found out that contacts[0].normal always returns v(0/-1) which explains the odd behaviour. but now i don't know why i get wrong normals... – oHoodie Nov 08 '18 at 18:59
  • See [How to get contact points from a trigger?](https://stackoverflow.com/questions/31641522/how-to-get-contact-points-from-a-trigger) – Ruzihm Nov 08 '18 at 19:22

0 Answers0