CoD Modern Warfare style gun script

Discussion in 'Scripting' started by novashot, Jun 27, 2010.

  1. novashot

    novashot

    Member

    Joined:
    Dec 12, 2009
    Messages:
    275
    Highlights:
    - Multiple Guns in one script
    - Tracers
    - Bullet Penetration
    - bullet randomness, increases over time
    - multiple material ready, just needs effects
    - Look down sights ready
    - Easy


    Here's a gun script that I been working on and it does just about everything. I searched for good gun scripts everywhere and got sick of the search; here is a bit of almost every script I seen all added together. It's a machine gun, burst / single shot, shotgun, and a grenade/rocket launcher all-in one script (c# only sorry). With a few changes in variables, you can make almost any weapon you wish.

    This gun side script supports variable bullet penetration, bullet creates impact effects and bullet holes on both sides of a penetrated wall, and variable tracers. Gun also has variables for random bullet spread with support for a decrease in accuracy during sustained fire from machine guns.

    Burst mode can fire any number of rounds per trigger pull and you can set the time between the rounds fired in the burst. Want a single shot? Set the burst to 1 and done.

    Shotgun has a variable for the number of pellets fired per shot.

    The Launcher supports both rockets and grenades if you're into noob tubes.

    ...the scripts have the framework in for multi-player, but hasn't been fully integrated yet, but should be soon. I'm working with the standard unity master server so my multi-player parts will be geared toward that.

    Forgot to mention, use the right mouse button(fire2) to look down the sights of your gun.

    Here's a Web Player Test of the gun Scripts in action.

    CoD Style Weapons WebPlayer

    Player with guns Unity Package

    If you like what you see, Use and Update these as you see fit. If you happen to add something cool, let everyone else know. Let me know what you think.

    Thanks and have fun.

    Attached Files:

    Last edited: Jun 29, 2014
  2. gamesurgeon

    gamesurgeon

    New Member

    Joined:
    Oct 11, 2009
    Messages:
    427
    Great! One slight change is that the rockets do not explode after X seconds. By this, I mean if you shoot up, the rocket appears to go on for infinity. Wouldn't be too hard to add a timer code, though.

    Thanks!
  3. FreelandCJV

    FreelandCJV

    New Member

    Joined:
    Nov 12, 2009
    Messages:
    221
    Actually, Alex, you could just make the timer code yourself and add it to the rocket prefab. That way when the rocket spawns the script will count how long until it should destroy the rocket and the rocket's children.
  4. GeneralGrant

    GeneralGrant

    New Member

    Joined:
    Jun 10, 2010
    Messages:
    977
    AMAZING!

    But there is no recoil.
  5. novashot

    novashot

    Member

    Joined:
    Dec 12, 2009
    Messages:
    275
    Yeah the current rocket just kills itself after so long...without exploding, but that is a simple fix.

    As for the demo, here's the script i used for creating the other weapons and weapon switching.

    I had to add a few lines of code in my gun script to use the weapon switch script, so will attach the updated gun.cs also.

    Thanks for the feed back.

    Attached Files:

  6. novashot

    novashot

    Member

    Joined:
    Dec 12, 2009
    Messages:
    275

    I did see a gun script with recoil and walk / run sway in. I might update my gun script to have those features soon.
  7. GeneralGrant

    GeneralGrant

    New Member

    Joined:
    Jun 10, 2010
    Messages:
    977
    Wow, pretty impresive. Your first post is a donation of code.

    Pretty awesome.
  8. FreelandCJV

    FreelandCJV

    New Member

    Joined:
    Nov 12, 2009
    Messages:
    221
    Big time donation! I love them! I was working on some scripts like these, but since you made these you saved me a lot of time!

    Thanks so much! :D
  9. novashot

    novashot

    Member

    Joined:
    Dec 12, 2009
    Messages:
    275
    I updated the gun script a bit to add the ability to choose if you want to run with ray cast bullets or physical bullets. Ray casts are less likely to have "bullet lag" in a multiplayer setting so figured adding the ability was worth while. Also some minor tweaks to the projectile scripts.

    I'm going to add in a multiplayer section to my project soon ( just using the unity master server ). I'll post that update when it is working.

    Let me know if the scripts help you out... I'd love to hear what type or weapons or how they work in your projects.

    Attached Files:

  10. novashot

    novashot

    Member

    Joined:
    Dec 12, 2009
    Messages:
    275

    Attached Files:

  11. Newnab

    Newnab

    New Member

    Joined:
    Oct 25, 2010
    Messages:
    7
    Hi there.

    Loving your work here, but I've got a few issues getting this to work with my existing set up (Making a third person game myself) and I was wondering if you could post a demo project file or just advise me where you applied which scripts? If you could I'd be grateful!

    Thanks.
  12. NewOrblivia

    NewOrblivia

    New Member

    Joined:
    Oct 27, 2010
    Messages:
    13
    Looks great, I started over, just cause my own scripts got so messy. I do however get this error, I'm assuming that is because 'offset' is not a function in 'mouselook', did you add another script or modify the mouselook script?

    "Assets/New Gun Assets/Weapons/Scripts/Gun.cs(557,46): error CS1061: Type `MouseLook' does not contain a definition for `offsetY' and no extension method `offsetY' of type `MouseLook' could be found (are you missing a using directive or an assembly reference?)"
    ----------------------

    NVM, got it solved by adding those vars to MouseLook
    Last edited: Nov 16, 2010
  13. novashot

    novashot

    Member

    Joined:
    Dec 12, 2009
    Messages:
    275
  14. NewOrblivia

    NewOrblivia

    New Member

    Joined:
    Oct 27, 2010
    Messages:
    13
    Actually my real problem is doing damage to my enemies,. hmmmm at the moment they are listening for specific bullets from my old weapon scripts, hmmm fail.

    Any ideas to what direction I should be looking at?

    I think my old script was overly complicated: Looked like this:

    function OnCollisionEnter(whatObject:Collision) {
    if (whatObject.transform.name == "bulletHit") {

    wakeUpDistance = Vector3.Distance (targetObj.transform.position, transform.position)+1;
    var contact : ContactPoint = whatObject.contacts[0];
    var rotation = Quaternion.FromToRotation( Vector3.up, contact.normal );

    print(whatObject.transform.GetComponent(Projectile).gunType);

    switch (whatObject.transform.GetComponent(Projectile).gunType) {

    case "Handgun":
    blood.particleEmitter.minEmission =10;
    blood.particleEmitter.maxEmission = 20;
    break;
    case "Rifle":
    blood.particleEmitter.minEmission =20;
    blood.particleEmitter.maxEmission = 25;
    break;
    case "Machine Gun":
    blood.particleEmitter.minEmission =30;
    blood.particleEmitter.maxEmission = 50;
    break;
    case "MP5":
    blood.particleEmitter.minEmission = 30;
    blood.particleEmitter.maxEmission = 50;
    break;
    case "Shotgun":
    blood.particleEmitter.minEmission =200;
    blood.particleEmitter.maxEmission = 300;
    break;
    }

    var zombieBlood : GameObject = Instantiate(blood, contact.point, rotation );

    receiveDamage(whatObject.transform.GetComponent(Projectile).damageAmount);
    //zombieSpeed=zombieSpeed-0.05;

    if (hitPoints<1) {
    dieGently();
    }
    }
    }

    function receiveDamage(howMuch) {
    hitPoints-=howMuch;
    return;
    }

    function dieGently() {
    dead=true;
    this.rigidbody.isKinematic = true;
    Destroy (collider);
    AudioSource.PlayClipAtPoint(clip2, Vector3 (101.162, 0.1, 97.67393));
    var whichDie ="die"+Mathf.Round(Random.Range(1,3));
    animation[whichDie].speed = 5;
    animation.CrossFade(whichDie);
    Destroy(gameObject, 5);
    //~ GameObject.FindWithTag("ZombieText").GetComponent(kills).gameText("zombiesdead");

    }

    function dieHeadshot() {
    dead=true;
    // this.rigidbody.isKinematic = true;
    Destroy (rigidbody);
    Destroy (collider);
    AudioSource.PlayClipAtPoint(clip3, Vector3 (101.162, 0.1, 97.67393));
    var whichDie ="die"+Mathf.Round(Random.Range(1,3));
    animation[whichDie].speed = 5;
    animation.CrossFade(whichDie);
    Destroy(gameObject, 5);
    //~ GameObject.FindWithTag("ZombieText").GetComponent(kills).gameText("zombiesdead");
    }
  15. novashot

    novashot

    Member

    Joined:
    Dec 12, 2009
    Messages:
    275
    My script treats all bullets about the same no matter of what kind of gun that shot them... except the gun script gives the bullets different properties like damage and velocity. I see your current script uses a different impact emitter depending on the type of gun. It would be an easy enough mod to my code to have the bullets know what type of gun fired it. Each bullet fired by my gun is sent and array of information giving the bullet it's specific propeties:

    Code (csharp):
    1.  
    2.         bulletInfo[0] = damage;
    3.         bulletInfo[1] = impactForce;
    4.         bulletInfo[2] = maxPenetration;
    5.         bulletInfo[3] = maxSpread;
    6.         bulletInfo[4] = spread;
    7.         bulletInfo[5] = bulletSpeed;
    8.  
    9.         newBullet.SendMessageUpwards("SetUp", bulletInfo); // send the gun's info to the bullet
    10.  
    You could just as easy add to the array sending the weapon type. You could change the whole array to strings if it would be easier, but then you would need to reconvert the string to a float or int to use it to cause damage. To cause damage my bullet script calls this:

    Code (csharp):
    1.  
    2.             // send a message to the hit object... let it know it was hit
    3.             bulletInfo[0] = ownersName;        // tell hit object who hit them
    4.             bulletInfo[1] = damage.ToString(); // tell them how much damage they recieved
    5.             // send the message
    6.             hit.collider.SendMessageUpwards("ImHit", bulletInfo, SendMessageOptions.DontRequireReceiver);
    7.  
    This sends a string array to the hit object telling the hit object who hit it and how hard. Each player or AI then has the function "ImHit" attached that will break up the array and use the info:

    Code (csharp):
    1.  
    2. public void ImHit(string[] info)
    3.     {
    4.        
    5.         if(!dead)
    6.         {
    7.             string myKiller = info[0];
    8.             float damage = float.Parse(info[1]);
    9.            
    10.             //Debug.Log(" I been hit by " + myKiller + " for " + damage + " damage");          
    11.            
    12.             health -= damage; // do some damage
    13.            
    14.             //Debug.Log("My health is now " + health + " / " + maxHealth);
    15.            
    16.             if(health<=0)
    17.             {  
    18.                             health = 0;
    19.                 dead = true;
    20.                 StartCoroutine(Die());
    21.             }
    22.         }
    23.     }
    24.  
    ImHit takse the bullet info and uses it to damage the player. This array is also very easy to add to if you want to send more information to the target about what hit it. In my function it just subtracts health and if health hits 0 it calls my die function.

    In your case, i would replace your recieveDamage with something similar to my ImHit and then use it to call your deaths. Your impact effects will be trickier because in my scripts the bullet creates the impact effect, not the hit object. You can modify the code to send the gun types and check what it hits to make the same effects though.

    Hope this helps
  16. NewOrblivia

    NewOrblivia

    New Member

    Joined:
    Oct 27, 2010
    Messages:
    13
    Awesome, thx for response, will apply and post it here when its working properly.
  17. GrimWare

    GrimWare

    New Member

    Joined:
    Jul 23, 2009
    Messages:
    211
    The third person view needs some work. Allow the player to aim with the mouse, not just the A and D buttons :)
  18. novashot

    novashot

    Member

    Joined:
    Dec 12, 2009
    Messages:
    275
    Check the Web player again... I believe you will find some mouse aiming is in for 3rd person now. It's still not pretty, but that construction worker was never meant to carry that weapon anyway :p the project link should be updated as well.

    CoD Style Weapons WebPlayer

    Player with guns Unity Package
    Last edited: Feb 27, 2011
  19. goma

    goma

    New Member

    Joined:
    Dec 17, 2010
    Messages:
    1
    bro....

    can u write a single script
    only for shotgun.....

    i learn fps tutorial, from unity tutorial....
    i have made machinegun, and rocket launcher...
    and i want to make new weapon like your "shotgun".....

    pls help......:p:p
    thx before....... :razz::razz:
  20. joeybubble1

    joeybubble1

    New Member

    Joined:
    Oct 30, 2010
    Messages:
    15
    with the bullet script, how would i make the particle change depending on wot it hits, its cos the case "ground" thing in it already but i tried everthing i know to make it work but it doesnt!!
  21. sxg5

    sxg5

    New Member

    Joined:
    Jan 26, 2011
    Messages:
    2
    Ok, i tried adding this script to a first-person controller, but there's an error in the Gun script dealing with the offsetY: "...does not contain a definition for 'offsetY' and no extension method 'offsetY' of type 'MouseLook' could be found..." How would i fix this??
  22. boomcrash

    boomcrash

    New Member

    Joined:
    Aug 31, 2010
    Messages:
    72
    I'm getting the same error. It needs an FPS character and camera in the scene that have the mouse look script applied,but so far I'm not having much luck getting it to work.
  23. sxg5

    sxg5

    New Member

    Joined:
    Jan 26, 2011
    Messages:
    2
    FPS character is the first-person controller, right?
  24. boomcrash

    boomcrash

    New Member

    Joined:
    Aug 31, 2010
    Messages:
    72
  25. iMAXx

    iMAXx

    New Member

    Joined:
    Aug 17, 2011
    Messages:
    1
    HI. But can you explain to me what steps to attach?
    Or give please the stage with this project.
  26. Z0mbi3Sl43R

    Z0mbi3Sl43R

    New Member

    Joined:
    Mar 7, 2012
    Messages:
    1
    Thanks for the awsome stuff novashot. I have a problem every tim i start up unity i get this error: Assets/Weapons/Scripts/Gun.cs(206,50): error CS1061: Type `MouseLook' does not contain a definition for `offsetY' and no extension method `offsetY' of type `MouseLook' could be found (are you missing a using directive or an assembly reference?)

    Can ya help me imma noob. thnx
  27. Ronkhmps

    Ronkhmps

    New Member

    Joined:
    Oct 14, 2009
    Messages:
    30
    I am getting this error:

    The type or namespace name `DecalMode' could not be found. Are you missing a using directive or an assembly reference?

    just imported the package and there was the error
    anyone has any idea why?
  28. kingcharizard

    kingcharizard

    New Member

    Joined:
    Jun 30, 2011
    Messages:
    1,134
    This isn't bad but it sill needs much work... I may work on making a fps framework
  29. eho

    eho

    New Member

    Joined:
    Jan 16, 2012
    Messages:
    1
    Thank's for exelent scripts!
  30. slasherxtrem

    slasherxtrem

    New Member

    Joined:
    Aug 8, 2012
    Messages:
    1
    i'm having the same problem, if some one could shed some light on this for me, i would be appreciative
  31. roger0

    roger0

    Member

    Joined:
    Feb 3, 2012
    Messages:
    924
    I'm bumping this thread up in hopes the author may notice. I'm getting the same errors as well. Also, what are the terms of the package? Can we use it on commercial projects?


  32. novashot

    novashot

    Member

    Joined:
    Dec 12, 2009
    Messages:
    275
    I'll take a look at it tomorrow... at the time I was making those I believe I was playing with the unity decal system in the soldier demo. I probably had some code in my project linked to that for my test but it wasn't working right so I thought I got rid of it. Decals would be used for bullet holes so look there to fix the error, remove anything referring to a decal and just spawn a plane with a bullet hole texture.

    I'll look it over and rewrite or fix it and repost. Sorry I been away so long and threads just seem to get buried pretty fast.

    Use it however you want... it would be cool if you drop me a line letting me know if you do anything cool with it but it's not required.
  33. roger0

    roger0

    Member

    Joined:
    Feb 3, 2012
    Messages:
    924
    Thanks for the quick response! It looks like no one has heard from you for 2 years on this thread. I like the package so far though. I just had to delete the decal script to get it to work. it appears google ranks this first for ''unity 3d weapon script'' and 'unity 3d gun script'. so congrats on that.
  34. novashot

    novashot

    Member

    Joined:
    Dec 12, 2009
    Messages:
    275
    I'll have to go back and rewrite this at some point here, but use the links in the first post since they were the most up to date links. The first post links don't have the phantom decal stuff in them and on import for me have no errors and compile / play fine on a blank new unity project. set the gun to physical bullets for best results... the raycast bullets require more work to get set up where as physical bullets is pretty much drag and drop.

    To add to a fps controller... have an fps controller in the scene. Drop in a gun prefab. Align the gun prefab to look correct... or how you want it to look in your fps view and make the gun prefab a child of the fps controller's camera. If you drop in the gun prefab, align to camera, parent it, set bullets to physical, and set the fps camera to the gun script's main camera... hit play and it will work.

    I agree it needs more work... i wrote it a few years ago and I need to overhaul it.... kids and life kinda set me back a bit but since there's still an interest in some Call of Duty style weapons I'll try to get back on it asap.... probably merge it with my borderlands style weapons and damage text fountain.

    Sorry again for delay.
  35. mujee

    mujee

    Member

    Joined:
    Mar 9, 2012
    Messages:
    57


    project folder link is dead please reuploaded
  36. iTz DiaMonD iTz

    iTz DiaMonD iTz

    New Member

    Joined:
    Jan 17, 2013
    Messages:
    4
    Hey, i'm noob on Unity, how i install it? =S
  37. Kastar Troy

    Kastar Troy

    Member

    Joined:
    Jul 18, 2012
    Messages:
    13
    Dude you can't ask beginner questions on something like a complex gun script thread, go through the unity tutorials first, they're awesome and it's the only way to learn properly.

    Nice script btw, gw.
  38. roger0

    roger0

    Member

    Joined:
    Feb 3, 2012
    Messages:
    924
    Hey, I'm trying to use the bullet prefab as the projectile for the UltimateFPSCamera setup. However, once the bullet is instantiated, sometimes it runs into the player and instantiates a hit effect. I tried putting the Character controller on the physics ignore raycast layer but with no luck. Can I get some help?
  39. venombreather

    venombreather

    New Member

    Joined:
    Feb 6, 2013
    Messages:
    1
    how did you fix it? plz help
  40. programmer123

    programmer123

    New Member

    Joined:
    Mar 3, 2013
    Messages:
    2
    Got a question, where do i insert the switch weapons script?? Im new to this so please help.
  41. Molton Metal

    Molton Metal

    Member

    Joined:
    Mar 9, 2013
    Messages:
    4
    pretty simple to add animation using function update with java you could say that when the certain gun is selected and Fire1 is pressed play animation "GunRecoil" and make your animation for the gun. and if you want add a shell projectile and that. you can go far with animations
  42. eeveelution8

    eeveelution8

    Member

    Joined:
    Feb 16, 2013
    Messages:
    8
    in the directory, Assets/Standard Assets/Decal System/Decal, it whines at me about the following errors :(

    (72,16) the type namespace 'Decalmode' could not be found. are you missing a using directive or assembly reference?
    (75,22) the type namespace 'DecalPolygon' could not be found. are you missing a using directive or assembly reference?
    (76,22) the type namespace 'DecalPolygon' could not be found. are you missing a using directive or assembly reference?
    (114,22) the type namespace 'Meshcombineutility' could not be found. are you missing a using directive or assembly reference?
  43. kookabara

    kookabara

    Member

    Joined:
    Jun 13, 2013
    Messages:
    7
    ive seen and get this throwback script and its really good one otherwise i need to try this on third person controller maybe later on my project so +1 to you and your script.
  44. novashot

    novashot

    Member

    Joined:
    Dec 12, 2009
    Messages:
    275
    I updated the first post with a bunch of updated and hopefully more efficient scripts.
  45. datgamemakerdude

    datgamemakerdude

    New Member

    Joined:
    Jun 26, 2013
    Messages:
    1
    I got this error for the single shot script: "Assets/Gun.cs(8,26): error CS0115: `Gun_SingleShot.Fire()' is marked as an override but no suitable method found to override"
  46. lordrockit

    lordrockit

    New Member

    Joined:
    Sep 8, 2013
    Messages:
    3
    amazing i got the cod style wepons pack and in minutes i had an amazing gun from my dreams that you soo much
  47. Gab Steve

    Gab Steve

    Member

    Joined:
    Nov 3, 2012
    Messages:
    32
    HEY thanks a TON for the scripts! I am currently making an fps game....Sorta like zombies or maybe even just like enemy drones vs the player blah blah.... So would it be fine with You if I used ur script? Reason being i might even sell the game....im not sure how much ill get im not even sure if illl get anything but only if its ok with u will i use them, and i will even put Your name in the credits! Again thanks for the scripts!!! Unity needs more people like u. :D
  48. Unity Arc

    Unity Arc

    New Member

    Joined:
    Sep 13, 2013
    Messages:
    44
    Project file link DEAD!! reupload brother :)

    EDIT: What the...?!
    Last edited: Sep 15, 2013
  49. everett24

    everett24

    Member

    Joined:
    Jul 3, 2012
    Messages:
    3
    when i downloaded the package, it says DecalMode does not exist, am i missing something?
  50. novashot

    novashot

    Member

    Joined:
    Dec 12, 2009
    Messages:
    275
    If there is a decal.cs in there delete it as it was never meant to be in there and obviously is missing some other dependant files.