我试图在特定点上投射类似弹射器的机制。例如,球的起始位置是x = 0,y = .5,z = 0,并且我希望它在x = 10,y = 0,z = 20时结束。现在我正在使用:
RigidBody.AddForce(new Vector3 (10, 15, 20) * thrust);
我是平均的' y'在x和z之间的元素,但推力似乎是最复杂的计算,我尝试通过试验+错误估计它,但这可能是正确的解决方案。
答案 0 :(得分:4)
我通过使用原点和目标位置的已知位置计算初始速度来创建解决方案。名为“transform”的变量是玩家手的变换参考,其中球开始穿过3D空间。此脚本将使射弹沿着这样的路径前进:http://en.wikipedia.org/wiki/Trajectory_of_a_projectile在飞机上方朝向目标。
例如:
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;
}
}