首页 > 解决方案 > 当角色环顾四周时,Contoller 脚本不会改变方向

问题描述

我正在使用 Unity 官方网站上的控制器脚本来移动我的角色。我还使用脚本来使用鼠标转动相机。一切正常,直到角色环顾四周并面向不同的方向。然后 WASD 控件根据原始方向移动它们。例如,如果我转动 180 度,W 将我向后移动,S 将我向前移动。

我试图用 transform.forward 来解决这个问题,但我真的不知道我在做什么。

运动脚本:

CharacterController characterController;

public float speed = 6.0f;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;

private Vector3 moveDirection = Vector3.zero;

void Start()
{
    characterController = GetComponent<CharacterController>();
}

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

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

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

    // Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
    // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
    // as an acceleration (ms^-2)
    moveDirection.y -= gravity * Time.deltaTime;

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

感谢您的任何帮助 :)

标签: c#unity3d

解决方案


您可以使用Transform.TransformDirection将本地方向转换为世界方向。使用您要移动的本地方向调用它,它将返回您可以提供的相应世界方向CharacterController.Move

void Update()
{
    if (characterController.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. Gravity is multiplied by deltaTime twice (once here, and once below
    // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
    // as an acceleration (ms^-2)
    moveDirection.y -= gravity * Time.deltaTime;


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

事实上,旧的文档就CharacterController.Move使用了这种方法!

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);
}

推荐阅读