First question:
You can create two variables: one which controls the rate of fire (rateOfFire), and the other holds the time of the last shot fired (lastFired).
public var rateOfFire : float; // Rate of fire for the projectile
private var lastFired : float; // Time of the last shot fired
Instead of placing all of your code inside the Update() function, you should move it into a Shoot() function, like so...
function Shoot ()
{
// Create the projectile
var instantiatedProjectile : Rigidbody = Instantiate( projectile, transform.position, transform.rotation );
// Propel the projectile forward based on the gameobject's current direction
instantiatedProjectile.velocity = transform.TransformDirection( Vector3( 0, 0, speed ) );
// Ignore collisions from the projectile and the gameobject
Physics.IgnoreCollision( instantiatedProjectile. collider, transform.root.collider );
}
Now, in order to fire a projectile every (*n*) seconds, you need to check if the current time subtracted from the last fired shot is past the rate at which to fire. Simply add an if statement and place your instantiate and fire code inside...
function Shoot ()
{
// If the current time is past the rate of fire ...
if ( Time.time - lastFired >= rateOfFire )
{
// ... create and fire a projectile
// Create the projectile
var instantiatedProjectile : Rigidbody = Instantiate( projectile, transform.position, transform.rotation );
// Propel the projectile forward based on the gameobject's current direction
instantiatedProjectile.velocity = transform.TransformDirection( Vector3( 0, 0, speed ) );
// Ignore collisions from the projectile and the gameobject
Physics.IgnoreCollision( instantiatedProjectile. collider, transform.root.collider );
}
Then all you need is to place the Shoot() function inside Update().
function Update ()
{
// Shoot a projectile
Shoot();
}
----------
Second question: The only difference between the first question is in the Update() function. Check if the Fire1 button was pressed.
function Update ()
{
// If the fire button is pressed ...
if ( Input.GetButtonDown( "Fire1" ) )
{
// ... shoot a projectile
Shoot();
}
}
↧