Unity3d 计算初始速度,将其设置为刚体,使其达到目标位置,并具有给定的发射角度、起始位置和目标位置

Unity3d 计算初始速度,将其设置为刚体,使其达到目标位置,并具有给定的发射角度、起始位置和目标位置,unity3d,Unity3d,我需要从任何高度射出一个球,让它在用户定义的目标位置反弹。给出了发射角。到目前为止,我已经尝试了几种解决方案: Vector3 calcBallisticVelocityVector(Vector3 source, Vector3 target, float angle) { Vector3 direction = target - source; float h = direction.y;

我需要从任何高度射出一个球,让它在用户定义的目标位置反弹。给出了发射角。到目前为止,我已经尝试了几种解决方案:

Vector3 calcBallisticVelocityVector(Vector3 source, Vector3 target, float angle) {
         Vector3 direction = target - source;                            
         float h = direction.y;                                           
         direction.y = 0;                                               
         float distance = direction.magnitude;                           
         float a = angle * Mathf.Deg2Rad;                                
         direction.y = distance * Mathf.Tan(a);                            
         distance += h/Mathf.Tan(a);                                      

         // calculate velocity
         float velocity = Mathf.Sqrt(distance * Physics.gravity.magnitude / Mathf.Sin(2*a));
         return velocity * direction.normalized;    
     }
我得到的结果是,即使球确实进入了预期的方向,它也会比预期的更早落下,因此用这些方法计算的速度似乎低于击中目标位置所需的实际速度。 刚体的质量设置为1,重力设置为0,-98,0,刚体的阻力和角阻力设置为0。还有哪些其他变量会影响这种行为


编辑:我忘了提到的一件事是,我正在将结果向量设置为刚体的速度,所以我没有使用“应用力”方法。

我修改了从这里得到的代码:现在我得到了我期望的结果。我总是能以我输入的任何角度击中目标位置

private Vector3 calcBallisticVelocityVector(Vector3 initialPos, Vector3 finalPos, float angle)
{
    var toPos = initialPos - finalPos;

    var h = toPos.y;

    toPos.y = 0;
    var r = toPos.magnitude;

    var g = -Physics.gravity.y;

    var a = Mathf.Deg2Rad * angle;

    var vI = Mathf.Sqrt (((Mathf.Pow (r, 2f) * g)) / (r * Mathf.Sin (2f * a) + 2f * h * Mathf.Pow (Mathf.Cos (a), 2f)));

    Vector3 velocity = (finalPos.Planar() - initialPos.Planar()).normalized * Mathf.Cos(a);
    velocity.y = Mathf.Sin(a);

    return velocity * vI;
 }

水平速度是速度幅值*余角。如果给定了角度,则只需使用:VelMagnite=水平距离/cosangle获得速度大小。Tanke考虑了它的水平距离,而不是距离:pointA-PointB利用三角函数或点积的支持,你可以得到两点之间的水平距离
private Vector3 calcBallisticVelocityVector(Vector3 initialPos, Vector3 finalPos, float angle)
{
    var toPos = initialPos - finalPos;

    var h = toPos.y;

    toPos.y = 0;
    var r = toPos.magnitude;

    var g = -Physics.gravity.y;

    var a = Mathf.Deg2Rad * angle;

    var vI = Mathf.Sqrt (((Mathf.Pow (r, 2f) * g)) / (r * Mathf.Sin (2f * a) + 2f * h * Mathf.Pow (Mathf.Cos (a), 2f)));

    Vector3 velocity = (finalPos.Planar() - initialPos.Planar()).normalized * Mathf.Cos(a);
    velocity.y = Mathf.Sin(a);

    return velocity * vI;
 }