给定当前角度和目标位置计算目标角度?

时间:2015-07-23 22:36:34

标签: c# math unity3d vectormath

我一直在努力解决我认为应该是一个非常简单的问题:

Diagram of the problem

我知道当前的航向角度(比如15度),并且给定目标游戏对象的变换,我想计算我应朝向目标旋转的角度。在上面的例子中,我想计算说335ish deg。

请注意,我需要计算目标角度,我有另一个类,给定一个角度,负责将标题旋转到所需的角度。我知道Transform.LookAt()和其他类似的函数,它们不适用于这种情况,因为原因(在另一类中我基本上计算了Euler四元数和Lerp直到达到目标角度,由于项目限制,Transform.LookAt()不起作用。

在第一种方法中,我尝试使用Vector3.forward的Dot积和方向向量计算角度theta,并没有完全正常工作(无论是永久旋转还是向错误的方向旋转)

Diagram of the problem

targetAngle = Vector3.Angle(Vector3.forward, (target pos - current pos).normalized);

我想也许如果我可以计算当前的航向方向向量,我可以将其中的Dot乘积和目标方向向量得到角度theta,然后使用theta和当前角度来计算超出目标角度(360°θ或其他?)以获得我想要旋转的角度。事实上,我只有当前的角度和当前位置,我不了解如何根据该信息计算当前的航向方向向量。我只是将一些任意常数添加到当前位置的Z值并从当前位置中减去,得到一个dir矢量?看似hacky并且它不应该工作。

Diagram of the problem

欢迎任何想法。

修改:其他信息

方向代码/ u / Asad询问:

    // Calculate the target Quat to rotate all children by
    Quaternion targ = Quaternion.Euler(0, 0, targetAngleHeading);
    // Calculate the Linear interpolation to apply to all children
    Quaternion lerp = Quaternion.Lerp(children[0].transform.localRotation, targ, Time.deltaTime * speedHeading_dps);

    foreach (GameObject c in children)
    {
        // Apply lerp calcualted above to all children
        c.transform.localRotation = lerp;
    }
    // Update the current heading angle 1st child's local z angle
    currentAngleHeading = turrets[0].transform.localEulerAngles.z;

然后在FixedUpdate()中我有:

    if (currentAngleHeading != targetAngleHeading)
    {
        DesiredHeading();
    }

2 个答案:

答案 0 :(得分:2)

您可以将变换向前移动,将矢量移动到目标,然后从这些变换角度或旋转:

Vector3 vectorToTarget = target.transform.position - transform.position;
Vector3 facingDirection = transform.forward; // just for clarity!

float angleInDegrees = Vector3.Angle(facingDirection, vectorToTarget);
Quaternion rotation = Quaternion.FromToRotation(facingDirection, vectorToTarget);

请注意,旋转是相对的;也就是说,你需要从当前位置应用以使其面向目标。

答案 1 :(得分:0)

试试这个

你可以直接从transform.position获取矢量距离矢量然后 vector3.normalize(target.position - object.position)

这是角落对象想要移动