【问题标题】:How to Calculate Target Destination如何计算目标目的地
【发布时间】:2015-04-03 21:16:27
【问题描述】:

我在弄清楚这一点时遇到了一些麻烦。我想要实现的是一种应对运动。玩家从远处冲向目标。

图表显示了设置。蓝色菱形是玩家,红色是目标。紫色框是目标 SkinnedMeshRenderer 的渲染器边界。我正在使用渲染器边界,因为某些目标的网格比其他的大得多。目前,玩家正在向橙色星星射击……这是不现实的。我希望他,无论目标面向什么方向,始终以目标相对于他的位置最近的点为目标……在图表的情况下,这将是棕色的星星。这是我一直在使用的代码...

 public IEnumerator Blitz()
{
    rigidbody.velocity = Vector3.zero; //ZERO OUT THE RIGIDBODY VELOCITY TO GET READY FOR THE BLITZ
    SkinnedMeshRenderer image = target.GetComponentInChildren<SkinnedMeshRenderer>();
    Vector3 position = image.renderer.bounds.center + image.renderer.bounds.extents;
    position.y = target.transform.position.y;
    while(Vector3.Distance(transform.position, position) > 0.5f)
    {
    transform.position = Vector3.Lerp(transform.position, position, Time.deltaTime * 10);
        yield return null;
    }
    Results(); //IRRELEVANT TO THIS PROBLEM. THIS CALCULATES DAMAGE.
    Blitz.Stop(); //THE PARTICLE EFFECT ASSOCIATED WITH THE BLITZ.
    GetComponent<Animator>().SetBool(moveName, false); //TRANSITIONS OUT OF THE BLITZ ANIMATION
    GetComponent<Input>().NotAttacking(); //LET'S THE INPUT SCRIPT KNOW THE PLAYER CAN HAVE CONTROL BACK.
}

【问题讨论】:

    标签: unity3d position transform renderer qvector3d


    【解决方案1】:
    //Get the derection to tarvel in and normalize it to length of 1
    Vector3 Direction = (Target - transform.position).normalized
    

    借助 Direction,您可以做很多事情。例如,您可以将方向乘以您的速度并将其添加到您的位置。

    transform.position += Direction * MoveSpeed;
    

    如果你想到达最近的点,你可以使用方便的 Collider.ClosestPointOnBounds 方法。

    Target = TargetObject.GetComponent<Collider>().ClosestPointOnBounds(transform.position)
    

    并将 Target 插入用于获取方向的代码中。

    或者,您可以使用 Vector3.Lerp 而无需获取方向,因为它只是插值。

    transform.position = Vector3.Lerp(Target,transform.position,time.DeltaTime);
    

    对于在目标点停止,可以使用到达行为。

    //Declare the distance to start slowing down
    float ClosingDistance = Speed * 2;
    //Get the distance to the target
    float Distance = (Target - transform.position).magnitude;
    //Check if the player needs to slow down
    if (Distance < ClosingDistance)
    {
    //If you're closer than the ClosingDistance, move slower
    transform.position += Direction * (MoveSpeed * Distance / ClosingDistance);
    }
    else{
    //If not, move at normal speed
    transform.position += Directino * MoveSpeed;
    }
    

    【讨论】:

    • 嗯,我已经在使用 Vector3.Lerp... 它在我的代码的第 9 行。我不知道的 Collider.ClosestPointOnBounds……听起来很棒!然而,问题仍然是停在正确的点以模拟玩家与目标的碰撞。这就是为什么我也需要使用 renderer.bounds 的原因。在动画期间,对撞机不会改变(至少在我的情况下不会),但网格会改变......所以如果玩家向前倾斜,他就在他的对撞机之外。为了弥补这一点,我想将 renderer.bounds 合并到计算中。
    • “停在正确的位置”是指当您的球员站在目标位置时停止吗?如果是这样,插值将为您做到这一点。您还可以使用到达行为,我将在答案中添加解释。
    猜你喜欢
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多