Raycast Shooting Recoil

Hello, I have this script, How i can make an recoil?

            if (Input.GetKey(KeyCode.Mouse0) && Time.time > singleNextFire)
            {
                GetComponent<AudioSource>().Play();
                muzzleFlash.Stop();
                muzzleFlash.Play();

                singleNextFire = Time.time + fireRate;

                Vector3 rayOrigin = raycastcamera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0));
                RaycastHit hit;

                if (Physics.Raycast(rayOrigin, raycastcamera.transform.forward, out hit, maxRange))
                {
                    Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
                    EnemyHealth enemy = hit.collider.GetComponent<EnemyHealth>();
                    if (enemy != null)
                    {
                        enemy.DamageEnemy(damage);
                    }

                    if (hit.rigidbody != null)
                    {
                        hit.rigidbody.AddForce(-hit.normal * hitForce);
                    }
                }
            }

Maybe if i make if i make:

Vector3 rayOrigin = raycastcamera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0));

To be randomly at 0.4 and 0.6 or an number between 0.4 - 0.6??

You need to make sure, that the player (or thing that shoots) has a rigidbody, then add some force in the direction opposite of the shooting direction, aka -transform.forward

But if i use Random.Range or something like this?

Oh, you mean to affect the bullet direction? You need to add some value to transform.forward with Random.Range

Can you give an example?

  if (Physics.Raycast(rayOrigin, raycastcamera.transform.forward, out hit, maxRange))

raycastcamera.transform.forward + new Vector3(randomvaluehere, randomvaluehere, rendomvaluehere)

1 Like

I put this but nonthinking, maybe i need to use other numbers?

Your answer is here
You know, if you don’t learn a bit of programmic logic, just copy and paste some code from somewhere, then you wont get anywhere