K
K
Kirill Artamonovich2018-12-12 21:17:23
C++ / C#
Kirill Artamonovich, 2018-12-12 21:17:23

How to create ballistics when firing raycast?

In real life, when you shoot a weapon at a great distance, the bullet in flight begins to weaken over time and fall down along a certain trajectory. Here I need to somehow make ballistics when shooting created via raycast. Help me please! How can this be implemented?
Shooting script:

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

public class RifleB : MonoBehaviour {

    private RecoilController recoilController;
    private Camera _camera;
    public GameObject body;
    public float minx = -5;
    public float maxx = 5;
    public float miny = -5;
    public float maxy = 5;

    void Awake()
    {
        recoilController = body.GetComponent<RecoilController>();
    }
    void Start()
    {
        _camera = GetComponent<Camera>();
    }
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Shoot();
        }
    }
    public void Shoot()
    {
        var currentRotate = transform.rotation;
        transform.Rotate(Random.Range(minx, maxx), Random.Range(miny, maxy), 0);
        Vector3 point = new Vector3(
        _camera.pixelWidth / 2, _camera.pixelHeight / 2, 0);
        Ray ray = _camera.ScreenPointToRay(point);
        transform.rotation = currentRotate;
        RaycastHit hit;
        recoilController.Recoil();

        if (Physics.Raycast(ray, out hit))
        {
            StartCoroutine(SphereIndicator(hit.point));
            transform.Rotate(0, 0, 0);
        }
    }
        private IEnumerator SphereIndicator(Vector3 pos)
        {
            GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            sphere.transform.position = pos;
            yield return new WaitForSeconds(1);
            Destroy(sphere);
        }
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question