Adding force to an object to move on a parabala

I’ve read many posts asking a similar question to mine, but just can’t find a solution that works for me. I’m making a catapult type object for my game, and I’m trying to fire it and make it land in a certain place.

Currently I’m working on just test code, where you push a button and it fires at the target object. I’ve looked through the physics equations needed to calculate how much force I need to reach a desired target, but have a hard time implementing it in code. Any help is greatly appreciated!

My thought was to find the direction from the two points, and fire at a point in between them at an arbitrary height (being 100 in this case) to create an arc, then add a force based on how far apart the two objects are. Currently, the further away the target is, the farther the object flies - which makes sense from how the code is laid out. I’ve just been stumped on this for a few days now. Thanks! :smiley:

Here’s my test code:

using UnityEngine;
using System.Collections;

public class s_ShippingCatapult : MonoBehaviour {

    public GameObject axeCrate;
    public GameObject shippingObject;

    public GameObject target;
    public float power;

    // Use this for initialization
    void Start ()
    {

        target = GameObject.FindGameObjectWithTag("BuyScreen");
	}
	
	// Update is called once per frame
	void Update ()
    {
	    if (Input.GetKeyDown(KeyCode.I))
        {

            shippingObject = Instantiate(axeCrate, gameObject.transform.position, Quaternion.identity) as GameObject;
            Rigidbody rb = shippingObject.transform.GetChild(0).GetComponent<Rigidbody>();
            Vector3 direction = target.transform.position - gameObject.transform.position;

            // fire at the buy menu, with a power based on the distance between the catapult and the tower
            rb.AddForce(new Vector3(direction.x / 2, 100, direction.z / 2) * (power * (direction.magnitude)), ForceMode.VelocityChange);

        }
	}

}

Well, one thing’s for certain – Trajectory calculations are involved.

That said, I’m going to be a little bit lazy and direct you to an older answer I gave on the subject – found here – to give you a bit of a head start.

I specifically accounted for any custom gravitational force, as well as height differences (up or down… yes, that difference is a factor I’ve run into), so if there’s anything you need that I hadn’t covered there, just ask away!