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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Bug Player Shoots Wrong

Discussion in '2D' started by Cfiedler23, Mar 14, 2023.

  1. Cfiedler23

    Cfiedler23

    Joined:
    Oct 19, 2022
    Posts:
    2
    For some reason when I shoot right everything works well, but when I shoot left the bullets move down and push me
    Video:
    https://drive.google.com/file/d/1jhe6x2owHSpmLgF_tSqDecRiPriK89wd/view?usp=sharing
    Code:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class gunShoot : MonoBehaviour
    4. {
    5.  
    6.     public Transform firePointR;
    7.     public Transform firePointL;
    8.     public GameObject bulletPrefab;
    9.     public flipSprite flipSprite;
    10.  
    11.     public float bulletForce = 20f;
    12.  
    13.  
    14.     void Update()
    15.     {
    16.         if (Input.GetButtonDown("Fire1"))
    17.         {
    18.             Shoot();
    19.         }
    20.     }
    21.  
    22.     void Shoot()
    23.     {
    24.        
    25.         if (flipSprite.spriteIsFlipped)
    26.         {
    27.             GameObject bullet = Instantiate(bulletPrefab, firePointL.position, firePointL.rotation);
    28.             Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
    29.             rb.AddForce(firePointR.right * bulletForce, ForceMode2D.Impulse);
    30.         }
    31.         else
    32.         {
    33.             GameObject bullet = Instantiate(bulletPrefab, firePointR.position, firePointR.rotation);
    34.             Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
    35.             rb.AddForce(firePointR.right * bulletForce, ForceMode2D.Impulse);
    36.         }
    37.        
    38.     }
    39. }
    Does anyone know how to solve this? Please let me know.
     
  2. Chubzdoomer

    Chubzdoomer

    Joined:
    Sep 27, 2014
    Posts:
    107
    Because of how your weapon is positioned, when you shoot to the right the barrel is far enough away from your player's body so that the bullets don't collide with him. When you shoot to the left, though, your barrel is much closer to your player's body, and so every spawned bullet is hitting your player.

    One way to fix this would be to put the bullets on a layer that ignores collisions with the player. Another way would be to use Physics2D.IgnoreCollision to tell each newly-spawned bullet to ignore collisions with your player (check out the code example on that page).
     
  3. Cfiedler23

    Cfiedler23

    Joined:
    Oct 19, 2022
    Posts:
    2
    thank you it worked:)