Unity3d 如何将球扔到平面上的特定点?

Unity3d 如何将球扔到平面上的特定点?,unity3d,Unity3d,我正在尝试一种类似弹射器的机制,在一个特定的点上射出一个球。例如,球的起始位置是x=0,y=0.5,z=0,我希望它在x=10,y=0,z=20处结束。目前我正在使用: RigidBody.AddForce(new Vector3 (10, 15, 20) * thrust); 我将“y”元素平均到x和z之间,但推力似乎是最复杂的计算方法,我尝试用试错法来估算,但这并不是正确的解。我通过使用已知的原点和目标位置计算初始速度来创建解。名为“transform”的变量是球员手部的变换参考,球从这里

我正在尝试一种类似弹射器的机制,在一个特定的点上射出一个球。例如,球的起始位置是x=0,y=0.5,z=0,我希望它在x=10,y=0,z=20处结束。目前我正在使用:

RigidBody.AddForce(new Vector3 (10, 15, 20) * thrust);

我将“y”元素平均到x和z之间,但推力似乎是最复杂的计算方法,我尝试用试错法来估算,但这并不是正确的解。

我通过使用已知的原点和目标位置计算初始速度来创建解。名为“transform”的变量是球员手部的变换参考,球从这里开始在3D空间中移动。此脚本将使投射物沿着如下路径:在平面上方朝向目标

例如:

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;
    }
}

除非你想修改物理,否则你必须计算它或猜测和检查。嗨,它似乎不起作用,而且方法FiringElevationAngle丢失了(我在那里输入'45'作为值)。您能测试一下它是否适合您吗?我添加了缺少的FiringElevationAngle方法,将所有代码放入一个完整的脚本中,并测试以验证其正确性。