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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Rigidbody.Velocity On Bullet, Strange Issue [Problem Solved]

Discussion in 'Scripting' started by Filip-ljunglof, Aug 13, 2017.

  1. Filip-ljunglof

    Filip-ljunglof

    Joined:
    Dec 13, 2015
    Posts:
    25
    Hi, I got a very weird issue that makes no sense to me I've tried to fix it myself but i honestly cant figure out why this is happening so i turn to you mighty power of unity forums. Anyway.. Here's the issue i got this code and it works perfectly when the player/character is moving, but if i try and shoot while the player is stationary nothing happens? (bullet does not move)

    Code (CSharp):
    1. void PlayerShoot() {
    2. GameObject bullet = Instantiate(projectile, bulletSpawn.position, bulletSpawn.rotation);
    3. bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 30;
    4. Destroy(bullet, 2f);
    5. }
     
  2. dpgdemos

    dpgdemos

    Joined:
    Apr 28, 2014
    Posts:
    24
    How is this method being called in your script? Can you provide that code?
     
  3. Filip-ljunglof

    Filip-ljunglof

    Joined:
    Dec 13, 2015
    Posts:
    25
    Sure its very easy
    Code (CSharp):
    1. if (Input.GetButtonDown("Fire1"))  {
    2. PlayerShoot();
    3. }
     
  4. dpgdemos

    dpgdemos

    Joined:
    Apr 28, 2014
    Posts:
    24
    I'm guessing you have the above code in an Update method. I just tested and I have it working fine on my end. I instead used a 3rd-person transform for the bullet's instantiated position and rotation.

    Code (CSharp):
    1. private void Update() {
    2.         if (Input.GetKey (KeyCode.Space)) {
    3.             PlayerShoot ();
    4.         }
    5.     }
    6.  
    Code (CSharp):
    1. private void PlayerShoot() {
    2.         print ("shoot");
    3.         GameObject bullet = Instantiate(_bullet, transform.position, transform.rotation);
    4.         bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 30;
    5.         Destroy(bullet, 2f);
    6.     }
     
  5. Filip-ljunglof

    Filip-ljunglof

    Joined:
    Dec 13, 2015
    Posts:
    25
    Problem fixed, It was another script that i used to detect if the bullet hit something that deleted the bullet because it would sometimes collide with the gun
     
    dpgdemos likes this.