x


How to delay a shot.

Hi I need to know how to delay a shot. For example I have a game where my player has a gun and I want it so when he holds down the left mouse button the shots fire automatically, with a delay so its not shooting a hundred bullets a second. Heres the code that makes the gun shoot. This code is in java, and if you can please make a public variable so I can change the delay time. The name of the gameobject is laser which you will probably notice in the code. This code does work, but it just needs a delay, and if your wondering I don't want the if statement to go from Input.GetButton to Input.GetButtonUp or Down. I know that that will make it so the player just has to click it and it will fire, but thats not what I want it to do. I want it the same, but just a delay on when the bullets fire when I hold down the left mouse button. Thanks so much.

var throwSound : AudioClip; var coconutObject : Rigidbody; var throwForce : float;

function Update () {

if(Input.GetButton("Fire1")){ audio.PlayOneShot(throwSound); var newCoconut : Rigidbody = Instantiate(coconutObject, transform.position, transform.rotation); newCoconut.rigidbody.velocity = transform.TransformDirection(Vector3(0,0, throwForce)); newCoconut.name = "laser"; Physics.IgnoreCollision(transform.root.collider, newCoconut.collider, true);

} }

@script RequireComponent(AudioSource)

more ▼

asked Jul 12 '12 at 04:27 PM

Jammer3000 gravatar image

Jammer3000
18 4 11 17

(comments are locked)
10|3000 characters needed characters left

1 answer: sort newest

Here you are, Unity's solution examples in JS and C# to solve your problem:

JS

// Instantiates a projectile off every 0.5 seconds,
// if the Fire1 button (default is ctrl) is pressed.

var projectile : GameObject;
var fireRate = 0.5;
private var nextFire = 0.0;

function Update ()
{

if (Input.GetButton ("Fire1") && Time.time > nextFire) 
{
    nextFire = Time.time + fireRate;
    var clone = Instantiate (projectile, transform.position, transform.rotation);
}

}

C#

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour 
{
 public GameObject projectile;
 public float fireRate = 0.5F;
 private float nextFire = 0.0F;

 void Update() 
 {
    if (Input.GetButton("Fire1") && Time.time > nextFire) 
    {
        nextFire = Time.time + fireRate;
        GameObject clone = Instantiate(projectile, transform.position, transform.rotation) as GameObject;
    }
 }
}
more ▼

answered Jul 12 '12 at 04:51 PM

Maddogc gravatar image

Maddogc
31 1 2 3

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

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

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5098
x3342
x2097
x179
x26

asked: Jul 12 '12 at 04:27 PM

Seen: 874 times

Last Updated: Jul 12 '12 at 05:08 PM