Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- using System;
- [RequireComponent(typeof(AudioSource))]
- public class SpawnBomb : MonoBehaviour
- {
- //Drag in the Bomb into the Component Inspector.
- public GameObject Bombs;
- //Enter the Speed of the Bomb from the Component Inspector.
- public float Bomb_Forward_Force;
- //Max ammo until you need to reload
- public int MaxAmmo;
- //Current ammo
- protected int Ammo;
- Rigidbody rb;
- //AudioSource
- AudioSource Sounds;
- public double m_ReArmTimer = 2;
- // Use this for initialization
- void Start()
- {
- //Get the rigidbody of the ship
- rb = GetComponentInParent<Rigidbody>();
- Sounds = GetComponent<AudioSource>();
- //Set the current ammo to be equal to the max ammo.
- Ammo = MaxAmmo;
- }
- .
- // Update is called once per frame
- void Update()
- {
- //Start a timer to see how long it has been since we fired the bullet
- m_ReArmTimer += Time.deltaTime;
- if (Input.GetMouseButtonDown(1))
- {
- if (Ammo >= 1)
- {
- //Reset the timer of when we last shot
- m_ReArmTimer = 0;
- //The Bullet instantiation happens here.
- GameObject Temporary_Bullet_Handler;
- Temporary_Bullet_Handler = Instantiate(Bombs, transform.position, transform.rotation) as GameObject;
- Ammo = Ammo - 1;
- //Sometimes bullets may appear rotated incorrectly due to the way its pivot was set from the original modeling package.
- //This is EASILY corrected here, you might have to rotate it from a different axis and or angle based on your particular mesh.
- //Temporary_Bullet_Handler.transform.Rotate(Vector3.down * 90);
- //Retrieve the Rigidbody component from the instantiated Bullet and control it.
- Rigidbody Temporary_RigidBody;
- Temporary_RigidBody = Temporary_Bullet_Handler.GetComponent<Rigidbody>();
- //Set the velocity of the bomb to the same as the ship, this effectively prevents you from running into your own bombs
- Temporary_RigidBody.velocity = rb.velocity;
- //Tell the bullet to be "pushed" forward by an amount set by Bullet_Forward_Force.
- Temporary_RigidBody.AddForce(transform.forward * Bomb_Forward_Force);
- //Basic Clean Up, set the Bullets to self destruct after 10 Seconds, I am being generous here, normally 3 seconds is plenty.
- Destroy(Temporary_Bullet_Handler, 10.0f);
- //Play our fire sound
- Sounds.Play();
- }
- }
- //If you have no ammo reload!
- if (Ammo <= 0)
- {
- //Start out couroutine
- StartCoroutine(Reload());
- }
- }
- // This is the reload function that we call when out of ammo
- private IEnumerator Reload()
- {
- yield return new WaitForSeconds(3);
- Ammo = MaxAmmo;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment