【问题标题】:Rotate GameObject on Z axis while moving forward向前移动时在 Z 轴上旋转游戏对象
【发布时间】:2014-09-22 22:52:19
【问题描述】:

目前我有以下代码,它适用于 3D 游戏 100%,但我无法让它适用于 2D 游戏。

它应该做的是,一旦物体到达航点,它应该朝着新的航点旋转。实际发生的是它围绕xy 轴旋转,而不是z 轴。我该怎么做才能让它只在z 轴上旋转?物体应该根据转弯速度向前移动。除非转弯速度很高,否则不应立即转弯。但无论如何,我再次问我如何让这段代码只在z 轴上旋转?

void Update () {
    if(toWaypoint > -1){
        Vector3 targetDir = wayPoints[toWaypoint].position - transform.position;
        Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, turnSpeed * Time.deltaTime, 0.0f);
        transform.rotation = Quaternion.LookRotation(newDir);
    }
    if(!usePhysics && toWaypoint != -1){
        transform.Translate(Vector3.forward * Time.deltaTime * speed);
        next();
    }
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    对于 2D 游戏,外观旋转不可靠,因为前向轴不同。一种解决方法是将精灵作为空游戏对象的父对象,z 轴(蓝色箭头)指向精灵将旋转的方向。

    【讨论】:

      【解决方案2】:

      看起来您正在使用 Unity3D,这让我想知道如果您在 2D 编辑模式下制作游戏,为什么首先要搞乱 Z 轴。 Z 轴在该模式下实际上什么都不做,除非您将两个轴设置为以某种方式包含它。我给你的建议是如果你还没有切换到 2D 编辑,然后使用 Vector2s 而不是 Vector3s。

      另外,请尝试使用其他轴之一作为您的旋转轴(transform.right.up 而不是 .forward)。

      【讨论】:

        【解决方案3】:

        我找到了我要找的东西:

        void Update () {
            if(toWaypoint > -1){
                Vector3 vectorToTarget = wayPoints[toWaypoint].position - transform.position;
                float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
                Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
                transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * turnSpeed);
            }
            if(!usePhysics && toWaypoint != -1){
                transform.Translate(Vector3.right * Time.deltaTime * speed);
                next();
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-14
          • 1970-01-01
          相关资源
          最近更新 更多