Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
This post has been wikified, any user with enough reputation can edit it.
avatar image
0
Question by rooted · Nov 07, 2013 at 03:33 AM · vector3audiosourceaudioclipyield waitforsecondsplayclipatpoint

A better script for a machine gun?

I'm trying to modify the Angry Bots autofire script.

So, you want to be able to either:

a.) Tap the fire button and shoot only one shot

b.) Hold down the fire button and shoot repeatedly at a fixed rate

The original script just played and stopped the audioclip "onStartFire" and OnStopFire" signals. As it stands now, it fires one shot cleanly using the "PlayClipAtPoint" command but doesn't rapidfire. I'm sure it's because I don't understand the Vector3 command.

 @script RequireComponent (PerFrameRaycast)
 
 var bulletPrefab : GameObject;
 var spawnPoint : Transform;
 var frequency : float = 10;
 var coneAngle : float = 1.5;
 var firing : boolean = false;
 var damagePerSecond : float = 20.0;
 var forcePerSecond : float = 20.0;
 var hitSoundVolume : float = 0.5;
 var gunPlay : AudioClip;
 var gunStop : AudioSource;
 
 var muzzleFlashFront : GameObject;
 
 private var lastFireTime : float = -1;
 private var raycast : PerFrameRaycast;
 
 function Awake () {
     muzzleFlashFront.SetActive (false);
 
     raycast = GetComponent.<PerFrameRaycast> ();
     if (spawnPoint == null)
         spawnPoint = transform;
 }
 
 function Update () {
     if (firing) {
 
         if (Time.time > lastFireTime + 1 / frequency) {
             // Spawn visual bullet
             var coneRandomRotation = Quaternion.Euler (Random.Range (-coneAngle, coneAngle), Random.Range (-coneAngle, coneAngle), 0);
             var go : GameObject = Spawner.Spawn (bulletPrefab, spawnPoint.position, spawnPoint.rotation * coneRandomRotation) as GameObject;
             var bullet : SimpleBullet = go.GetComponent.<SimpleBullet> ();
 
             lastFireTime = Time.time;
 
             // Find the object hit by the raycast
             var hitInfo : RaycastHit = raycast.GetHitInfo ();
             if (hitInfo.transform) {
                 // Get the health component of the target if any
                 var targetHealth : Health = hitInfo.transform.GetComponent.<Health> ();
                 if (targetHealth) {
                     // Apply damage
                     targetHealth.OnDamage (damagePerSecond / frequency, -spawnPoint.forward);
                 }
 
                 // Get the rigidbody if any
                 if (hitInfo.rigidbody) {
                     // Apply force to the target object at the position of the hit point
                     var force : Vector3 = transform.forward * (forcePerSecond / frequency);
                     hitInfo.rigidbody.AddForceAtPosition (force, hitInfo.point, ForceMode.Impulse);
                 }
 
                 // Ricochet sound
                 var sound : AudioClip = MaterialImpactManager.GetBulletHitSound (hitInfo.collider.sharedMaterial);
                 AudioSource.PlayClipAtPoint (sound, hitInfo.point, hitSoundVolume);
 
                 bullet.dist = hitInfo.distance;
             }
             else {
                 bullet.dist = 1000;
             }
         }
     }
 }
 
 function OnStartFire () {
     if (Time.timeScale == 0)
         return;
 
     firing = true;
 
     muzzleFlashFront.SetActive (true);
 
     //if (audio && gunPlay.isPlaying){
     //    yield WaitForSeconds (gunPlay.clip.length);
     //    gunPlay.Play ();
     //}
     //else {
         audio.PlayClipAtPoint (gunPlay,Vector3 (5, 1, 2));
     //}
 }
 
 function OnStopFire () {
     firing = false;
 
     muzzleFlashFront.SetActive (false);
     
     if (audio){
         
         gunStop.Play ();
     }
     //else {
     //    gunStop.Play ();
     //}
 }
Comment
Add comment · Show 4
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Huacanacha · Nov 07, 2013 at 05:10 AM 0
Share

Just a quick tip: your Question suffers from information overload. Try to be more concise so it doesn't take people so long (or scare them off entirely) to figure out what your question is!

avatar image Fornoreason1000 · Nov 07, 2013 at 05:28 AM 0
Share

you seem rather well informed for a newbie :P

here is a thought you could add the audio source to the bullets them selves. then give them a 1 shot bullet sound. which will eli$$anonymous$$ate the cut out effect. this will also mean that the sound will play as the bullets are ejected. you could also add a $$anonymous$$ch randomization to the sources so it doesn't sound so uniform.

the only down side is that the sound may "di$$anonymous$$ish" very quickly due to the bullet being ejecting so fast that it gains too much distance too quickly. (bullets can travel up to 6000ft per second!)

avatar image rooted · Nov 07, 2013 at 06:13 AM 0
Share

@ Huacanacha Yep, definitely will edit, thanks!

@Fornoreason Thanks, I did try that idea already and you can actually reduce the distance effect just by turning the pan to 0 in the audio source. It still didn't quite sound right though. However, I haven't tried adding the second "stop shooting" sound on "mouse button up" which did help with realism with the original loop method. I'll see if I can make it work.

It seems the "audio.PlayClipAtPoint (gunPlay,Vector3 (5, 1, 2));" command works the best but when I added it to that section of the script it only plays once. I'm not sure I understand the "Vector3 (5,1,2))

avatar image rooted · Nov 07, 2013 at 02:06 PM 0
Share

Could something in this script I found be made to work? I'm not a good programmer.

var fireRate = 0.5; private var nextFire = 0.0; private var i = 1; function Update() { if(Input.GetButtonDown("Fire1")) { Debug.Log("Fire1nce: " + i); nextFire = Time.time + fireRate; i++; } if(Input.GetButton("Fire1")) && (Time.time > nextFire)) { Debug.Log("Fire2ice: " + i); nextFire = Time.time + fireRate; i++; } }

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by rooted · Nov 18, 2013 at 10:34 AM

This worked for me very well. One caveat is that I had to pitch the single shot audioclip down an octave in order to import it into Unity. Then I pitched it back up via the audiosource. In addition, I added a tracer sound to the bullet prefab to get bullet action subtly across the screen. Very nice indeed! I found just using a single audioclip work well enough in tandem with random pitching. Adding more clips on the firing sound didn't yield better results IMO. However, the recoil/reverb action on "mouse up" is nice with some variance. Hope this helps someone.

 #pragma strict
 @script RequireComponent(AudioSource)
 
 var gunLoop : AudioSource;
 var gunLoopSounds: AudioClip[]; // set the array size and fill the elements with the sounds
 var gunStop : AudioSource;
 var gunStopSounds: AudioClip[]; // set the array size and fill the elements with the sounds
 var distortion: AudioDistortionFilter;
 
 
 
 
 function Update () {
 
     if(Input.GetMouseButtonDown(0)) {
          gunLoop.loop = true; // turn looping on
          //gunLoop.pitch = Random.Range(2.30,2.35);
          PlayRandomGunLoop(); // and start sound
          //gunLoop.loop = false; // turn looping off to stop sound;
      
      }
      
      if(Input.GetMouseButton(0)) {
          
          gunLoop.pitch = Random.Range(2.18,2.28); //2.28, 2.31 old values
          //gunLoop.volume = Random.Range(0.98,1);
          //distortion.distortionLevel = Random.Range (0.1,0.13);
      
      }
      
     
     if(Input.GetMouseButtonUp(0)) {
          gunLoop.loop = false; // turn looping off to stop sound;
          PlayRandomGunStop();    // and start sound    
     
     }
     
 }
  
 function PlayRandomGunLoop(){ // call this function to play a random sound
 
     //if (gunLoop.isPlaying) return; // don't play a new sound while the last hasn't finished
            gunLoop.clip = gunLoopSounds[Random.Range(0,gunLoopSounds.length)];
            gunLoop.Play();
     }
     
 function PlayRandomGunStop(){ // call this function to play a random sound
     //if (gunStop.isPlaying) return; // don't play a new sound while the last hasn't finished
         gunStop.clip = gunStopSounds[Random.Range(0,gunStopSounds.length)];
         gunStop.pitch = Random.Range(1.32,1.42);
         gunStop.Play();
 }
 
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

17 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Making AudioSource follow camera? 1 Answer

Why am I able to play an AudioClip without an AudioSource? 1 Answer

Using yield WaitForSeconds after AudioSource.PlayClipAtPoint 1 Answer

How to play multiple sounds simultaneously 2 Answers

Ambisonic Audio Support for PS4 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges