【问题标题】:Unity transform.up not rotatingunity transform.up 不旋转
【发布时间】:2019-09-28 23:08:46
【问题描述】:

我正在尝试创建一些基本的游戏 AI 逻辑,让一名玩家奔跑并避开另一名玩家。这很好,但是当我这样做时,我现在正在寻找防守者(以前是静态的)来追逐跑步者。我为此苦苦挣扎了很长时间,但发现 transform.up 是我一直在寻找的魔法,因为它使用玩家 Y(绿色轴)继续前进并使用旋转。

在我的 2d 平面上,跑步者跑上页面时效果很好,但我的后卫跑下来了,这就是我的问题。我预计当我在 Z 轴上将角色旋转 180 度时,transform.up 会在页面下方下降。我发现 transform.up 仍在页面上方,我我不确定我错过了什么。

为了移动玩家,我正在执行以下操作(在 Update() 内):

transform.Translate(transform.up * 15f * Time.deltaTime);

为了尝试调试问题,我在 Start() 中添加了以下内容:

// DEBUG: Show position indicators;
if (showPositionIndicators == true) {

    Dictionary<string, Vector3> posIndicators = new Dictionary<string, Vector3>();
    posIndicators.Add("Up", transform.up);
    posIndicators.Add("Rt", transform.right);
    posIndicators.Add("Dn", -transform.up);
    posIndicators.Add("Lt", -transform.right);
    posIndicators.Add("Fd", transform.forward);
    posIndicators.Add("Bk", -transform.forward);

    Vector3 scaleLocPos = new Vector3(10f, 10f, 10f);
    dbgPosInd = new List<GameObject>();
    foreach (KeyValuePair<string, Vector3> posIndicator in posIndicators) {

        GameObject t = Instantiate(prefabPosInd, transform);
    t.name = "Pos_" + posIndicator.Key;
        t.transform.localPosition = Vector3.Scale(posIndicator.Value, scaleLocPos);
        t.GetComponent<TextMeshProUGUI>().text = posIndicator.Key;
        dbgPosInd.Add(t);
    }
}

这似乎表明 transform.up 确实在“后面”并且与跑步者相同。我错过了一些简单的东西吗?这是故意的吗?我将如何让两名球员相对于他们自己的轮换前进(即都向中间跑)

[

【问题讨论】:

    标签: c# unity3d transform


    【解决方案1】:

    您在t.transform.localPosition = Vector3.Scale(posIndicator.Value, scaleLocPos); 中使用transform.up 作为局部空间向量,但transform.up世界空间 中提供变换局部向上向量。它就像transform.TransformDirection(Vector3.up); 的简写。

    旋转 180 度的对象的局部空间向上向量在世界空间中向下。你说对了那部分。但是,当您将其用作旋转对象的 localPosition 时,由于对象已旋转,因此该局部空间位置设置为 down,并且将再次上升在世界空间中。

    这就是为什么“UP”调试文本是颠倒的,它应该是颠倒的,但世界空间是向上的。这是因为在对象的本地空间中,它是向下的。

    在您的t.transform.localPosition 分配中使用Vector3.up(和其他方向),因为该引用已经指向本地空间位置。


    由于transform.Translate() 默认使用local-space,同样的问题也会发生。您的局部空间向上(当获取时)向下(在世界空间中),但您的局部空间向下平移又在世界空间中备份。

    使用transform.Translate(Vector3.up * 15f * Time.deltaTime)(推荐),或相对于世界空间进行翻译,transform.Translate(transform.up * 15f * Time.deltaTime, Space.World);


    另一个潜在问题:

    假设您的角色拥有或将拥有物理元素,请不要在更新或变换时进行移动。在FixedUpdate() 上使用Rigidbody2D.MovePosition()。有一个Rigidbody2d.position,但它会覆盖其他物理效果,因此推荐MovePosition()

    【讨论】:

    • 效果很好,令人讨厌的是,我确实有 Vector3.up(和 co),但在发现 transform.up 后更改了它以保持一致性。如果我将 transform.Translate 更改为 Vector3.up 它不会像使用 transform.up 那样避开防守者(它使用 Quaternion.RotateTowards: ``` transform.Translate(transform.up * runSpeed * Time.deltaTime ); transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0f, 0f, rotationAmount), rotationSpeed * Time.deltaTime);```
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多