Search Unity

Random Gunfire Raycast

Discussion in 'Scripting' started by dukerustfield, Jul 11, 2020.

  1. dukerustfield

    dukerustfield

    Joined:
    Dec 5, 2019
    Posts:
    33
    This is something I did for my own work and thought I'd pass along.

    I couldn't figure out how to make "noise" on a raycast going in a base direction (forward). You're going to get some level of fairly random inaccuracy from the muzzle of the gun through its travel. Not just bullet drop, but there is humidity, wind(s), thermals, sligh imperfections, and a million other things that contribute. With some guns pulling this or that way more.

    This code fragment takes a forward shot, uses a weapon variable of Scatter, and multiplies by a random value from -1 to 1. So if it has a 5 degree scatter in the X axis, it will be anywhere from -5 to 5. Changing the Scatter will uniformly change XYZ scatter potential. But you can also change the Euler range of each one. Instead of -1 to 1 you could be -.5 to .5 for instance. Depending on how far the bullet (or whatever Ray) travels, the Scatter will be magnified. 5 degrees would be a horribly inaccurate POS gun in the real world, but for many shooter games, it's fairly reliable.

    I'm sure there are many other ways to do it. I had seen posts asking for similar some time ago, but didn't really favor their results. I had been using getting a random point in a circle of the scatter after it was shot. But that could potentially mean it should have crossed through an obstruction and not hit at all. And I was using Quarternion .AngleAxis, but I wanted to freefloat XYZ.

    Code (CSharp):
    1.  public void Fire()
    2.         if (Scatter != 0)
    3.         {
    4.             direction = Quaternion.Euler(Scatter * Random.Range(-1f,1f), Scatter * Random.Range(-1f, 1f), Scatter * Random.Range(-1f, 1f)) * transform.forward;
    5.             ray = new Ray(transform.position, direction);
    6.         }
    7.    
    8.         if (Physics.Raycast(ray, out hit, BulletDistance))