- Home /
Bullet instantiates sometimes in wrong posiiton
enter code here
I am having a script where projectiles (bullet ) are instantiated when player fires at high rate. Unfortunatly some times for example when firing continuesly some bullets instantiate on wrong spot. using the FixedUpdate instead of the Update function corrected most of the problem buit still some bulelts are not instantiated at the correct position that is in front of the gun. As a result the weapon fires bullets on two directions. Bullets are being instantiated at a high rate. Is there a way to correct this?
void FixedUpdate () {
if (Input.GetMouseButton (1) && !playerMovement.crouchState ) {
if(Input.GetMouseButton(0) && Time.time > nextFire){
nextFire = Time.time + fireRate;
GameObject cloneBullet = Instantiate(bullet,transform.position,transform.rotation) as GameObject;
muzzleFlash.animation.Play();
cloneBullet.rigidbody.AddForce(cloneBullet.transform.forward*bulletSpeed);
if(!audioPlayed){
audio.clip = fireSFX;
audio.Play();
audioPlayed = true;
}
Destroy(cloneBullet.gameObject,2);
audioPlayed = false;
}
}else{
}
}
Are the bullets colliding with each other and therefor moving in a different direction/get pushed away from the spawn point? If this is the case maybe have the bullet collides ignore each other (by layers).
I do not think that the bullets collide because they are ravelling on a straight line. The problem is that on ket's say every 5 bullets the other 2 are going straigh to the wrong direction. I noticed that firirn once at a time it is much better. I am wondering maybe if the fire rate has to do something with the functions that are called i mean the time interval.
Anyway i will lokk at it and let you know. thanks
Well, considering they are rigidbodies and you spawn them in the same place they want to push away from each other and bounce off each other when you add a force to them. Try adding them to a layer and make them ignore that layer :)
For making a gun, I would recommend the Raycast functions inside of the Physics class rather than spawning an actual object to fly across the screen. It's just that unless we're really in the $$anonymous$$atrix, we can't see bullets get shot from a gun without some form of slow motion software. Now if you were trying to do a slow motion cam of the guy getting hit where the camera follows the bullet, that would be a reasonable use.