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

Shooting script

Discussion in 'Scripting' started by MasterMage102, Oct 23, 2015.

  1. MasterMage102

    MasterMage102

    Joined:
    Sep 8, 2015
    Posts:
    4
    My bullet goes out of the side of my gun instead of the barrel.

    static var ammo = 100;
    static var maxAmmo = 100;
    var key : String = "mouse 0";
    var bullet : Rigidbody;
    var speed : float = 1000;

    function Update () {
    if(Input.GetKeyDown(key)){
    if(ammo > 0){
    shoot();
    }
    }
    }
    function shoot(){
    var bullet1 : Rigidbody = Instantiate(bullet, transform.position, transform.rotation);
    bullet1.AddForce(transform.forward * speed);
    ammo --;
    }
    function OnGUI(){
    GUI.Label(Rect(10, 10, 500, 500), ""+ammo);
    }
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    Try to use code tags to make it easier to help you in the future: http://forum.unity3d.com/threads/using-code-tags-properly.143875/

    Is the bullet shooting sideways, or is it just not lined up with the barrel?

    It's possible that your bullet model is facing the right (down the x axis) instead of forward (down the z axis), in which case you'll want to add force in the direction of transform.right or -transform.right.

    It's also possible that the object that's creating the bullet is facing the right, in which case you'll want to fix the rotation of the bullet inside your instantiate function (or after it).

    Either way, the problem is definitely in your Shoot() function. If you can't get it figured out, give me some more info and I'll try to help.
     
  3. MasterMage102

    MasterMage102

    Joined:
    Sep 8, 2015
    Posts:
    4
    The -transform.right worked. Thanks.
     
  4. MasterMage102

    MasterMage102

    Joined:
    Sep 8, 2015
    Posts:
    4
    The -transform.right worked. Thank you