Thursday, 14 November 2019

Unity C# Shooting a object along a trajectory

Create a new game object a sphere that will be the object that will be used for shooting, also create an empty game object and name it as a target. Copy the below script and attach it to a new empty game object and attach the sphere and target object in the inspector.


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

public class ShootingBall : MonoBehaviour
{
    public Transform myTarget;
    public GameObject snowballs;
    float shootAngle = 30;
    float angle;
    // Start is called before the first frame update
    public Vector3 BallisticVel(Transform target, float angle)
    {
        Vector3 dir = target.position - transform.position;
        float h = dir.y;  // get height difference
        dir.y = 0;  // retain only the horizontal direction
        float dist = dir.magnitude;  // get horizontal distance
        float a = angle * Mathf.Deg2Rad;  // convert angle to radians
        dir.y = dist * Mathf.Tan(a);  // set dir to the elevation angle
        dist += h / Mathf.Tan(a);  // correct for small height differences
                                   // calculate the velocity magnitude
        var vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 * a));
        return vel * dir.normalized;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("b"))
        {  // press b to shoot
            GameObject ball = Instantiate(snowballs, transform.position, Quaternion.identity);
            ball.GetComponent<Rigidbody>().velocity = BallisticVel(myTarget, shootAngle);
            Destroy(ball, 10);
        }
    }
}