- Home /
Spreading Fire (Bullets)
So i currently have created a tank, but its Shell shots are bang on perfect everytime. What i want is to have them be a little off somtimes, not always perfect. How could i do somthing like this through script? (I dont want a script, just an idea how to do this). Also, the bullet spread has to be adjustible, because the bullet spread will increase/decrease due to movement, if on the ground, etc. Thanks in advance. (I work in JS)
Answer by EX_Darius · Dec 05, 2013 at 12:38 AM
You can create a random spread by using Random.range , use the value for the rotation of the instantiated object, after that apply the force/movement to the object.
a short example in C#:
public float Stray;
private float NextShot;
void FireWeapon()
{
if(Time.time > NextShot)
{
var randomNumberX = Random.Range(-Stray, Stray);
var randomNumberY = Random.Range(-Stray, Stray);
var randomNumberZ = Random.Range(-Stray, Stray);
Rigidbody YourProjectileClone =(Rigidbody)Instantiate(YourProjectile,position, rotation); // instantiate projectile
YourProjectileClone.transform.Rotate(randomNumberX, randomNumberY, randomNumberZ);
YourProjectile.AddForce(YourProjectile.transform.forward * 6000);
NextShot = Time.time + 0.1f;
}
Just a heads up, you can save yourself the calculation of the Z axis. In this instance, it is not necessary. Just replace with:
YourProjectileClone.transform.Rotate(randomNumberX, randomNumberY, 0.0f);
Answer by TimBorquez · Dec 04, 2013 at 08:54 PM
before every shot i would use random range to determine some inaccuracy to add on to your shot angle,
and for the max number in random i would put a variable there and make it a higher/lower number depending on how accurate you want it
And then just set the rotate of the spawn depending on the number that comes up?
yeah when you instantiate yo bullet, i guess you could then give the bullet velocity that includes some of that random range, i can give more detail later when i get home
actually scratch that, i think you can set the rotation when you instantiate it (the quaternion) and then just make the bullet go straight, that should work i think...
Answer by alienbaby · Dec 04, 2013 at 11:15 PM
I'd suggest adding a small offset vector to the aim vector you have, of a random direction with the magnitude scaled appropriately depending on how your modelling the physics of the bullet. This would separate accuracy from the physical properties of the gun, which is ideal for a game unless you are trying to simulate real world interactions.
Your answer
Follow this Question
Related Questions
How to make my bullets spread when fired 3 Answers
[Unity2D] Make fire spread through tiles in Platformer 0 Answers
Setting bullet instansiate direction? help? 1 Answer
Multiple Bullets 2 Answers
2D Bullet Hell Game - Bullet Patterns 2 Answers