【问题标题】:Rotating a 3D character on when they move移动时旋转 3D 角色
【发布时间】:2017-01-06 18:36:45
【问题描述】:

我想从 Unity 上的一个小 3D 平台游戏开始。当我移动时,我希望角色看向移动的方向。因此,当我按下左/“A”时,我希望角色立即左转并向前走。其他方向也一样。问题是当我离开钥匙时,角色会回到默认旋转。

重要代码:

private void FixedUpdate()
    {
        float inputX = Input.GetAxis("Horizontal"); // Input
        float inputZ = Input.GetAxis("Vertical"); // Input

        if (GroundCheck()) // On the ground?
        {
            verticalVelocity = -gravity * Time.deltaTime; // velocity on y-axis
            if (Input.GetButtonDown("Jump")) // Jump Key pressed
            {
                verticalVelocity = jumpPower; // jump in the air
            }
        }
        else // Player is not grounded
        {
            verticalVelocity -= gravity * Time.deltaTime; // Get back to the ground
        }

        Vector3 movement = new Vector3(inputX, verticalVelocity, inputZ); // the movement vector
        if (movement.magnitude != 0) // Input given?
        {
            transform.rotation = Quaternion.LookRotation(new Vector3(movement.x, 0, movement.z)); // Rotate the Player to the moving direction
        }
        rigid.velocity = movement * movementSpeed; // Move the character
    }

第二件事是,在

transform.rotation = Quaternion.LookRotation(new Vector3(movement.x, 0, movement.z));

y 轴上有 0。它说查看向量为零。当我传入另一个数字(如movement.y)时,角色会倾斜到地板上。所以我不知道该传递什么。

【问题讨论】:

    标签: unity3d 3d game-physics


    【解决方案1】:

    至于松开按键时重置:你的线路

    if (movement.magnitude != 0) // Input given?
    

    是个好主意,但很有可能您的控制器报告的值会略微偏离 0,因此即使您实际上并没有移动,您的角色的方向也会发生变化。我会将其更改为

    if (movement.magnitude >.1f) // Input given?
    

    或其他接近(但不完全)零的数字。在处理这个问题时,我会在这个函数中添加Debug.Log(movement.magnitude);,并确保值在您期望的范围内。

    关于第二个话题: 当您将verticalVelocity 应用到rigidBody.velocity 时,在您的运动向量中添加verticalVelocity 很重要,但您不希望它出现在面向角色的向量中。如果你想让你的角色只看一个平面,那么只考虑两个维度是非常有意义的;正如您提到的,添加第三个维度将使它看起来像天空或地面。此外,我也会更改您的输入检查线以使用它,因为您只想根据角色是否水平移动来改变面。这将使您的代码看起来像这样:

    Vector3 movement = new Vector3(inputX, verticalVelocity, inputZ); // the movement vector
    Vector3 horizontalMovement = new Vector3(inputX, 0f, inputZ);
            if (horizontalMovement.magnitude != 0) // Input given?
            {
                transform.rotation = Quaternion.LookRotation(horizontalMovement); // Rotate the Player to the moving direction
            }
            rigid.velocity = movement * movementSpeed; // Move the character
    

    最后一点,当您接地时,您可能希望将verticalVelocity 设置为0,而不是-gravity*deltaTime。此错误可能不可见(物理引擎会将您的角色推回地板外),但如果用户使用 alt-tab 并且帧之间的时间过长,您的角色将传送穿过地板!

    祝你好运。

    【讨论】:

    • 感谢您的回复 :) 我的所有问题都通过编写 transform.rotation = Quaternion.LookRotation(transform.forward + new Vector3(inputX, 0, inputZ) * smoothRotation);
    猜你喜欢
    • 1970-01-01
    • 2022-08-14
    • 2022-08-03
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    相关资源
    最近更新 更多