Set up time between each instantiated object?
I have a script to shoot bullet's out of a gun, but the bullet's are being shot in such a short time that they collide with thenselves everytime the gun moves, how do i set the time (0.1 seconds) between each bullet shot so they don't collide?
Here's the script (not complete, only usefull parts):
function Update () {
if(Input.GetButton("Fire1") && bulletsInCurrentMag > 0) {
shoot();
}
}
function shoot () {
var pel = Instantiate(projectile, muzzle.position, muzzle.rotation);
pel.GetComponent.<Rigidbody>().AddForce(transform.forward * 0);
bulletsInCurrentMag -= 1;
isFiring = true;
}
PS: AddForce is set to 0 just so i can track the bullets. It still doesn't work with 1, 2 or 1000.
Anyone can help me?
Answer by g__l · Dec 29, 2015 at 06:59 PM
The problem is that your method is getting called from Update() so that is every frame which is a very short time. So instead i would recommend using InvokeRepeating() which calls a selected method after so many seconds and repeats it every so many seconds. It takes in three parameters
InvokeRepeating(string methodName, float time, float repeatRate);
So put this code in your start function and choose the time since start to call the method and the repeat rate to call that method. Hope that helps...
Note - I code in C# sharp so when i say method i guess you mean function (function shoot ()). Any problems look at the documentation or video.
Didn't work man, apearently in JS, it's only Invoke("function", float time); and the problem is still the same, just as it was yield WaitForSeconds
@g__l
Remember you are using InvokeRepeating not Invoke. The second half of the video or documentation will help. Say if you have any more problems.
Answer by bowloflol · Dec 30, 2015 at 01:05 AM
Try this, change attack speed to whatever you think is best.
var attackSpeed : float = .5;
var attackSpeedCurrent : float = 0;
function Update () {
if(attackSpeed > 0) {
attackSpeedCurrent -= Time.deltaTime;
}
if(Input.GetButton("Fire1") && bulletsInCurrentMag > 0 && attackSpeedCurrent <=0) {
shoot();
}
}
function shoot () {
var pel = Instantiate(projectile, muzzle.position, muzzle.rotation);
pel.GetComponent.<Rigidbody>().AddForce(transform.forward * 0);
bulletsInCurrentMag -= 1;
isFiring = true;
attackSpeedCurrent = 0
}