我正在尝试设计一个弹射机构,用于将球射向特定点。例如,球的起始位置为x=0,y=.5,z=0,我希望它最终停留在x=10,y=0,z=20。目前我正在使用:
RigidBody.AddForce(new Vector3 (10, 15, 20) * thrust);
我正在将“y”元素平均到x和z之间,但是推力似乎是最难计算的。我尝试通过试错法估计它,但那可能不是正确的解决方案。
我正在尝试设计一个弹射机构,用于将球射向特定点。例如,球的起始位置为x=0,y=.5,z=0,我希望它最终停留在x=10,y=0,z=20。目前我正在使用:
RigidBody.AddForce(new Vector3 (10, 15, 20) * thrust);
我正在将“y”元素平均到x和z之间,但是推力似乎是最难计算的。我尝试通过试错法估计它,但那可能不是正确的解决方案。
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;
}
}