如何使角色面对行进方向?

时间:2019-09-20 11:02:25

标签: c# unity3d animation bezier

有人知道我该如何修改我的代码,以使角色面向行进方向?我意识到这个问题似乎与现有问题重复,但是我不确定在哪里/如何在我的代码中应用正确的旋转代码:

coroutineAllowed = false;
Vector2 p0 = routelist[routeIndex].routes[routeNumber].GetChild(0).position;
Vector2 p1 = routelist[routeIndex].routes[routeNumber].GetChild(1).position;
Vector2 p2 = routelist[routeIndex].routes[routeNumber].GetChild(2).position;
Vector2 p3 = routelist[routeIndex].routes[routeNumber].GetChild(3).position;

while (tParam < 1)
{
    tParam += Time.deltaTime * speedModifier;
    characterPosition = Mathf.Pow(1 - tParam, 3) * p0 +
        3 * Mathf.Pow(1 - tParam, 2) * tParam * p1 +
        3 * (1 - tParam) * Mathf.Pow(tParam, 2) * p2 +
        Mathf.Pow(tParam, 3) * p3;
    transform.position = characterPosition;
    yield return new WaitForEndOfFrame();
}

4 个答案:

答案 0 :(得分:1)

Unity中的子画面(通常,如果不是总是)垂直于其局部forward方向。这就是为什么将其局部正向设置为与正交摄影机的方向正交会导致它们不可见的原因。

从您在其他答案中共享的图像来看,似乎您需要沿与角色移动相反的方向旋转角色的局部“向上”方向,同时保持角色的局部“向前”方向指向全局向前方向。

您可以使用Quaternion.LookRotation来执行此操作,尽管您需要对参数稍加创意,将要面对的方向作为up参数,并使用全局{{ 1}}作为前进参数。

forward

答案 1 :(得分:0)

您可以像这样使用transform.LookAt(Vector3)

characterPosition = Mathf.Pow(1 - tParam, 3) * p0 +
    3 * Mathf.Pow(1 - tParam, 2) * tParam * p1 +
    3 * (1 - tParam) * Mathf.Pow(tParam, 2) * p2 +
    Mathf.Pow(tParam, 3) * p3;
transform.LookAt(characterPosition);
transform.position = characterPosition;

答案 2 :(得分:0)

尝试以这种方式进行操作,首先获取Lookvector,然后指示字符对其进行调查。

while (tParam < 1)
{
    tParam += Time.deltaTime * speedModifier;
    characterPosition = Mathf.Pow(1 - tParam, 3) * p0 +
        3 * Mathf.Pow(1 - tParam, 2) * tParam * p1 +
        3 * (1 - tParam) * Mathf.Pow(tParam, 2) * p2 +
        Mathf.Pow(tParam, 3) * p3;
    Vector3 v3 = characterPosition;
    Vector3 Lookvector = v3 - transform.position;
    Quaternion rotation = Quaternion.LookRotation(Lookvector);
    transform.rotation = rotation;
    transform.position = characterPosition;
    yield return new WaitForEndOfFrame();
}

答案 3 :(得分:-2)

您看过这个吗

https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html

这也可能会在x和z空间中旋转,但是您可以解决此问题并执行以下操作:

// Direction vector
Vector3 relativePos = target.position - transform.position;

// the second argument, upwards, defaults to Vector3.up
Quaternion rotation = Quaternion.LookRotation(relativePos, Vector3.up);

// fix rota so that only y rotation occures.
var vectorRota = rotation.EulerAngles;
Vector3 fixedYRotation =  new Vector(0f, vectorRota.y, 0f);

// create Quaternion back from Vector3
Quaternion finalRotation = Quaternion.Euler(fixedYRotation );

// assing rotation to GameObject
gameObject.transform.rotation = finalRotation;