当3D角色移动时将其旋转 [英] Rotating a 3D character on when they move

查看:0
本文介绍了当3D角色移动时将其旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Unity上的一个小3D平台开始。当我移动时,我希望角色看向移动的方向。因此,当我按下Left/"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的数字时,字符会倾斜到地板上。因此,我不知道要在那里传递什么。

推荐答案

至于松开按键时重置:您的行

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

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

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

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

关于第二个主题: 尽管在将verticalVelocity应用于rigidBody.ocity时,在移动向量中具有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,而不是-重力*deltaTime。这个错误可能看不到(物理引擎会把你的角色从地板上推回来),但如果用户按Alt键并且两帧之间有太长的距离,你的角色就会在地板上传送!

祝你好运。

这篇关于当3D角色移动时将其旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆