Use a vector3 position to calculate where a bomb falls

Hi everyone,

I’ve been working on a difficult problem since a few days and I’m bugged.

I’m trying to get a Vector3 position that will serve as a target. I’m trying to make something like a cannon fire at that precise position.

Here’s my code right now:

using UnityEngine;
using System.Collections;

public class Mortar : MonoBehaviour 
{
	public float force;
	public Vector3 torque;
	public GameObject explosion;
	
	private Transform target;
	private Vector3 targetPos;
	
	void Start () 
	{
		Destroy(gameObject, 5.0f);
		
		rigidbody.AddForce(transform.forward * force, ForceMode.Impulse);
		
		rigidbody.AddForce(transform.up * force, ForceMode.Impulse);
		
		rigidbody.AddTorque(torque, ForceMode.Force);
	}
	
	void OnCollisionEnter(Collision collision)
	{	
		foreach(ContactPoint cp in collision.contacts)
		{
			if(cp.otherCollider.gameObject.tag == "Floor")
			{
				Instantiate(explosion, collision.contacts[0].point, Quaternion.identity);
				Destroy(gameObject);
			}
		}		
	}
	
	void ReceiveTarget(Vector3 targetReceived)
	{
		targetPos = targetReceived;
		Debug.Log("targetPos = " + targetPos);
	}
	
	void ApplyDamage()
	{
		
	}
}

Obviously, I’m still not done with getting my Vector3 from another script, but I’m working on that.
The main problem is: when I get that info, how will I use it? I want my bomb, once fired, to do an arc from the canon tip to the target.
I’m trying hard to figure how I can do this with the AddForce…

Anybody can help? Thank you.

I answered a similar question some time ago: Shooting a cannonball. - Questions & Answers - Unity Discussions

The code in that answer is in JS, thus I posted here a C# version.

In a brief, you should calculate the velocity necessary to reach the target, instantiate the projectile and set its rigidbody.velocity to the value calculated. If the target and the cannon are at the same height, the velocity magnitude can be calculated by sqrt(distance * g * sin(2 * elevation angle)). If there exists a small height difference between the cannon and the target, this can be compensated to some extent by a smart change in the distance value.

The function BallisticVel below receives the target transform and the elevation angle, and calculates the complete velocity vector (a vector with suitable direction and magnitude), including a linear compensation for small height differences (up to about 10% of the distance):

Vector3 BallisticVel(Transform target, float angle){
    Vector3 dir = target.position - transform.position;  // get target direction
    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
    float vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 * a));
    return vel * dir.normalized;
}

// This is a test code: drag the target and projectile prefab to the appropriate
// fields in the Inspector, then press B to shoot. You can change the shootAngle,
// initially set to 30 degrees - the projectile slows down for higher angles, 
// and get faster for lower angles:

public Transform myTarget;  // drag the target here
public GameObject cannonball;  // drag the cannonball prefab here
public float shootAngle = 30;  // elevation angle

void Update(){
    if (Input.GetKeyDown("b")){  // press b to shoot
        GameObject ball = Instantiate(cannonball, transform.position, Quaternion.identity) as GameObject;
        ball.rigidbody.velocity = BallisticVel(myTarget, shootAngle);
        Destroy(ball, 10);
    }
}

This C# version was not tested, thus let me know if it has any errors.

NOTE: The projectile must not collide with the cannon, or it will never reach the target. You can have a cannon without collider, or with isTrigger=true, or attach this script to an empty object that will be the spawn point.

So if I understand you, you have two points … the source and the target and you want to move an object from the source to the target in a “ballistic” fashion following a trajectory?

I think the answer to your question will presumably involve physics and math. You will want to calculate the vector of initial launch of the projectile and the force to be applied to it. The calculation of these factors will be based on the mathematics of Trajectory.

See: