Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Reflecting a bullet

Discussion in '2D' started by SimpleDuude, Sep 18, 2023.

  1. SimpleDuude

    SimpleDuude

    Joined:
    May 22, 2021
    Posts:
    5
    I have a attackarea, in which i can attack and reflect bullets.
    The problem is that the reflection doesn’t work properly.

    Here’s a example how it looks:



    I wan’t it to reflect it STRAIGHT BACK, not up or down.

    These two script-parts are the only relevant for this function:
    Code (CSharp):
    1. if (collider.tag == "bullet")
    2. {
    3.     Rigidbody2D rbOther = collider.GetComponent<Rigidbody2D>();
    4.     if (rbOther != null)
    5.     {
    6.         Vector2 incomingVelocity = rbOther.velocity;
    7.         Vector2 normal = (collider.transform.position - transform.position).normalized;
    8.         Vector2 reflectedVelocity = Vector2.Reflect(incomingVelocity, normal);
    9.  
    10.         // Weise die reflektierte Velocity dem Rigidbody2D zu
    11.         rbOther.velocity = reflectedVelocity;
    12.     }
    13. }
    Code (CSharp):
    1. void Update()
    2. {
    3.     if (Input.GetKeyDown(KeyCode.G))
    4.     {
    5.         var bullet = Instantiate(bulletPrefab, bulletSpawnpoint.position, bulletSpawnpoint.rotation);
    6.         bullet.GetComponent<Rigidbody2D>().velocity = bulletSpawnpoint.up * bulletSpeed;
    7.     }
    8. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,561
    Reflecting it straight back is just negating the vector:

    Code (csharp):
    1. Vector2 incomingVelocity = rbOther.velocity;
    2. Vector2 reflectedVelocity = -incomingVelocity;
    That's it.

    Keep in mind you might still be colliding on the next frame, especially if the thing you hit is moving closer.

    In that case it may be necessary to make a float timer that inhibits bouncing for a short period of time after each bounce.