c# - 难以理解沿着局部和全局空间的统一运动

标签 c# unity-game-engine

CharacterController _charController;

// ...

moveInputX = Input.GetAxis("Horizontal") * speed;
moveInputZ = Input.GetAxis("Vertical") * speed;
Vector3 movement = new Vector3(moveInputX, 0, moveInputZ);
movement = Vector3.ClampMagnitude(movement, speed);

movement.y = -9.81f;

movement *= Time.deltaTime;
movement = transform.TransformDirection(movement);
_charController.Move(movement);

我有一个旋转的玩家,我想让他向本地方向移动,但我不明白何时从其移动的代码中删除 movement = transform.TransformDirection(movement);到全局方向,这没有任何意义,因为这行代码将方向从局部空间转换为全局空间。

最佳答案

这是因为 CharacterController.Move 需要世界空间中的向量。遗憾的是,相关文档从未明确说明这一点。

当您在此处计算运动时:

Vector3 movement = new Vector3(moveInputX, 0, moveInputZ);

您可以看到它没有考虑角色变换的旋转。为了做到这一点,您需要找到该向量在世界空间中被解释为在角色的本地空间中时的样子。这正是这一行的作用:

movement = transform.TransformDirection(movement);

它将运动从本地空间转换为世界空间。

2018.1 CharacterController.Move documentation实际上在其示例中使用了 transform.TransformDirection:

using UnityEngine;
using System.Collections;

// The GameObject is made to bounce using the space key.
// Also the GameOject can be moved forward/backward and left/right.
// Add a Quad to the scene so this GameObject can collider with a floor.

public class ExampleScript : MonoBehaviour
{
    public float speed = 6.0f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;

    private Vector3 moveDirection = Vector3.zero;
    private CharacterController controller;

    void Start()
    {
        controller = GetComponent<CharacterController>();

        // let the gameObject fall down
        gameObject.transform.position = new Vector3(0, 5, 0);
    }

    void Update()
    {
        if (controller.isGrounded)
        {
            // We are grounded, so recalculate
            // move direction directly from axes

            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection = moveDirection * speed;

            if (Input.GetButton("Jump"))
            {
                moveDirection.y = jumpSpeed;
            }
        }

        // Apply gravity
        moveDirection.y = moveDirection.y - (gravity * Time.deltaTime);

        // Move the controller
        controller.Move(moveDirection * Time.deltaTime);
    }
}

关于c# - 难以理解沿着局部和全局空间的统一运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58272822/

相关文章:

c# - 为 PrincipalContext 指定容器后无法找到用户

android - 应用内计费 v3 unity onActivityResult

text - 多语言支持在 TextMesh Pro 中不起作用

c# - 如何通过脚本统一制作多个网格?

ios - Unity - 使用 Fabric 导致 iOS 出现问题

c# - 将 XUnit 与 Service Fabric 结合使用

c# - 键盘记录程序崩溃

C# 字节数组转字符串数组

unity-game-engine - ParseFacebookUtils.LogInAsync 仅在 WebPlayer 上给出错误

C# 不要为未使用的参数定义变量