How to throw a ball to a specific point on an airplane?
I am trying to create a catapult-like mechanism for shooting a ball at a specific location. For example, the starting position of the ball is x = 0, y = .5, z = 0, and I want it to end at x = 10, y = 0, z = 20. For now, I use:
RigidBody.AddForce(new Vector3 (10, 15, 20) * thrust);
I am averaging the element 'y' between x and z, but push seems to be the most difficult to calculate, I tried to evaluate it with trial + error, but this may not be the right solution.
source to share
I created a solution by calculating an initial velocity using known origin and target positions. A variable named "transform" is a reference to the transformation of the player's hand, where the ball begins its journey through 3D space. This script will make the projectile follow the following path: http://en.wikipedia.org/wiki/Trajectory_of_a_projectile above the plane to the target.
Example:
public class BallisticLauncherTest : MonoBehaviour
{
public GameObject ballGameObject;
public Transform target;
// Use this for initialization
void Start()
{
ThrowBallAtTargetLocation(target.position, 10f);
}
// Throws ball at location with regards to gravity (assuming no obstacles in path) and initialVelocity (how hard to throw the ball)
public void ThrowBallAtTargetLocation(Vector3 targetLocation, float initialVelocity)
{
Vector3 direction = (targetLocation - transform.position).normalized;
float distance = Vector3.Distance(targetLocation, transform.position);
float firingElevationAngle = FiringElevationAngle(Physics.gravity.magnitude, distance, initialVelocity);
Vector3 elevation = Quaternion.AngleAxis(firingElevationAngle, transform.right) * transform.up;
float directionAngle = AngleBetweenAboutAxis(transform.forward, direction, transform.up);
Vector3 velocity = Quaternion.AngleAxis(directionAngle, transform.up) * elevation * initialVelocity;
// ballGameObject is object to be thrown
ballGameObject.rigidbody.AddForce(velocity, ForceMode.VelocityChange);
}
// Helper method to find angle between two points (v1 & v2) with respect to axis n
public static float AngleBetweenAboutAxis(Vector3 v1, Vector3 v2, Vector3 n)
{
return Mathf.Atan2(
Vector3.Dot(n, Vector3.Cross(v1, v2)),
Vector3.Dot(v1, v2)) * Mathf.Rad2Deg;
}
// Helper method to find angle of elevation (ballistic trajectory) required to reach distance with initialVelocity
// Does not take wind resistance into consideration.
private float FiringElevationAngle(float gravity, float distance, float initialVelocity)
{
float angle = 0.5f * Mathf.Asin((gravity * distance) / (initialVelocity * initialVelocity)) * Mathf.Rad2Deg;
return angle;
}
}
source to share