Answer the question
In order to leave comments, you need to log in
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
The simplest thing is to raycast not exactly at the target (the center of the screen, judging by yours), but with some random offset.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question