K
K
Kirill Artamonovich2018-12-09 17:23:18
Unity
Kirill Artamonovich, 2018-12-09 17:23:18

How to spread bullets through raycast?

Hello! Can you please tell me how to implement the spread of bullets if I created the shooting through Raycast?
I just don't understand how it can be done!
Here is the firing code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RifleB : MonoBehaviour {

    private Camera _camera;

    public GameObject body;
    private RecoilHorizontal recoilHorizontal;
    private RecoilVertical recoilVertical;

    void Awake()
    {
        recoilHorizontal = body.GetComponent<RecoilHorizontal>();
        recoilVertical = GetComponent<RecoilVertical>();

        _camera = GetComponent<Camera>();

        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    // Use this for initialization
    void Start() {

    }

    // Update is called once per frame
    void Update() {
        if (Input.GetMouseButtonDown(0))
        {
            Shoot();
        }

    }
    public void Shoot()
    {
        Vector3 point = new Vector3(
        _camera.pixelWidth / 2, _camera.pixelHeight / 2, 0);
        Ray ray = _camera.ScreenPointToRay(point);
        RaycastHit hit;
        recoilHorizontal.recoilHor();
        recoilVertical.recoilVer();
        if (Physics.Raycast(ray, out hit))
        {
            GameObject hitObject = hit.transform.gameObject;
            ReactiveTarget target = hitObject.GetComponent<ReactiveTarget>();
            if (target != null)
            {
                target.ReactToHit();
            }
        }
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2018-12-09
@ITprogER76

The simplest thing is to raycast not exactly at the target (the center of the screen, judging by yours), but with some random offset.

I
Ilya, 2018-12-12
@FireGM

https://docs.unity3d.com/ScriptReference/Random-in...
add a raycast hit to the transform

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question