- Home /
Make a Gun fire multiple times
I have a gun and need it to fire when I am holding down the left mouse button until a specific number of bullets fired is reached, then i reload. The script I have right now Instantiates a sphere and adds a force to it, but its only a one shot and doesnt have the bullet limit or reload function. I can add the reload and bullet limits myself i think, but im really stuck on the fire rate.
Add a timer that resets each time you fire. Only fire if the timer has reached a certain point. Change the time on the timer to change the rate of fire.
Answer by DayyanSisson · Jul 15, 2012 at 02:10 AM
Look at this:
http://docs.unity3d.com/Documentation/ScriptReference/Time-time.html
Gives you the actual firing code too.
Answer by Muuskii · Jul 11, 2012 at 02:19 AM
I tend to use Time.deltaTime and Mathf.Max like so:
float timeTillNextShot = 0;
void Update()
{
timeTillNextShot = Mathf.Max(timeTillNextShot - Time.deltaTime, 0); //never go below 0
if(timeTillNextShot <= 0) //Add condition to check if we're firing here
{
timeTillNextShot = timeBetweenShots; //reset
fireAShot();
}
}
Answer by fipps129 · Jul 15, 2012 at 12:32 AM
Just use a bool check with InvokeRepeating().
public bool mousePressed = false;
public float timeBetweenShots = 0.2f;
public int shotsPerClip = 30;
private bool runOnce = false;
void Update()
{
if(Input.GetMouseDown(0)){
mousePressed = true;
}
if(Input.GetMouseUp(0)){
mousePressed = false;
}
if(mousePressed){
if(shotsPerClip>0&&!runOnce){
InvokeRepeating("ShootGun", 0, timeBetweenShots);
runOnce=true;
}
}else{
CancelInvoke();
runOnce=false;
}
}
public void ShootGun(){
//do all shooting functions
if(shotsPerClip<=0){
CancelInvoke();
//call reload function
}
}
Your answer
Follow this Question
Related Questions
Setting bullet instansiate direction? help? 1 Answer
Bullets aren't firing / Bullet holes not instantiating correctly 0 Answers
Control amount of bullets 2 Answers
Best way to make a gun? 1 Answer
Bullets Based on Orientation 1 Answer