【问题标题】:move object and _camera.TransformDirection(moveDirection)移动对象和 _camera.TransformDirection(moveDirection)
【发布时间】:2015-11-08 06:02:38
【问题描述】:

我正在使用这个简单的功能移动游戏对象,移动身体取决于相机视图。唯一的问题是相机 X 旋转不是 0 并且身体试图移动到地面但没有向前清除并且移动缓慢

void VerySimpleMove()
{
    if (_controllerBody.isGrounded)
    {
        _moveDirection.x = _mj.GetAxis("Horizontal");
        _moveDirection.y = 0;
        _moveDirection.z = _mj.GetAxis("Vertical");                  

        _moveDirection = _camera.TransformDirection(_moveDirection); 
        if (Mathf.Abs(_moveDirection.x) > 0 || Mathf.Abs(_moveDirection.y) > 0)
        {
            _body.rotation = Quaternion.LookRotation(_moveDirection);
        }
        if (_jumpButton)
        {
            _jumpButton = false;
            _moveDirection.y = _jumpHeight;
        }
    }
    _moveDirection.y -= _gravity * Time.deltaTime;
    _controllerBody.Move(_moveDirection * Time.deltaTime);
}

如何通过 _camera.eulerAngle.x 旋转 _moveDirection 以使其真正向前?

【问题讨论】:

  • 看起来我需要通过 _camera.angleEulers.x 旋转 Vector3

标签: c# unity3d game-physics


【解决方案1】:

如果我理解正确,您需要确保 _moveDirection 始终平行于 XZ 平面。 一种方法是不使用_camera.TransformDirection,而是计算相机前向矢量在XZ 平面上的投影,然后在该方向上使用LookRotation,如下所示:

var forward = _camera.transform.forward; // Get camera forward vector
forward.y = 0; // Project it on XZ plane
_moveDirection =  Quaternion.LookRotation(forward) * _moveDirection; // Rotate

请注意,仅按建议的相机 X 角度旋转对象在这里并不总是有帮助,因为相机 Z 角度可能会产生相同的效果。

所以最终的代码是:

void VerySimpleMove()
{
    if (_controllerBody.isGrounded)
    {
        _moveDirection.x = _mj.GetAxis("Horizontal");
        _moveDirection.y = 0;
        _moveDirection.z = _mj.GetAxis("Vertical");                  

        var forward = _camera.transform.forward; // Get camera forward vector
        forward.y = 0; // Project it on XZ plane
        _moveDirection =  Quaternion.LookRotation(forward) * _moveDirection; // Rotate
        if (Mathf.Abs(_moveDirection.x) > 0 || Mathf.Abs(_moveDirection.y) > 0)
        {
            _body.rotation = Quaternion.LookRotation(_moveDirection);
        }
        if (_jumpButton)
        {
            _jumpButton = false;
            _moveDirection.y = _jumpHeight;
        }
    }
    _moveDirection.y -= _gravity * Time.deltaTime;
    _controllerBody.Move(_moveDirection * Time.deltaTime);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2016-02-20
    • 2014-09-17
    • 2017-11-07
    相关资源
    最近更新 更多