首页 文章

在旋转时改变运动方向

提问于
浏览
1

我创造了一个FPS运动但玩家的动作是错误的 . 当向左或向右旋转时,播放器仍然向前移动 .

PlayerMovement.cs

public class PlayerMovement : MonoBehaviour
{
    private Vector3 movement;
    private Rigidbody rigid;
    private bool jumpPressed;

    private const int MOVEMENT_SPEED = 8;
    private const int JUMP_POWER = 20;

    private void Awake()
    {
        rigid = GetComponent<Rigidbody>();
    }

    private void Update()
    {
        SetInputs();
    }

    private void FixedUpdate()
    {
        Jump();
        Move();
    }

    private void SetInputs()
    {
        movement.x = Input.GetAxis("Horizontal") * MOVEMENT_SPEED;
        movement.y = rigid.velocity.y;
        movement.z = Input.GetAxis("Vertical") * MOVEMENT_SPEED;
        jumpPressed = Input.GetKeyDown(KeyCode.Space);
    }

    private void Jump()
    {
        if (jumpPressed && GroundCheck())
        {
            movement.y = JUMP_POWER;
            jumpPressed = false;
        }
    }

    private void Move()
    {
        rigid.velocity = movement;
    }

    private bool GroundCheck()
    {
        return true;
    }
}

CameraMovement.cs

public class CameraMovement : MonoBehaviour
{
    private Transform player;
    private Vector2 rotation;

    private Quaternion originalRotation;

    private const int HORIZONTAL_ROTATION_SPEED = 5;
    private const int VERTICAL_ROTATION_SPEED = 5;
    private const int VERTICAL_ROTATION_MIN = -80;
    private const int VERTICAL_ROTATION_MAX = 80;

    private void Awake()
    {
        player = GameObject.FindGameObjectWithTag("Player").transform;
    }

    private void Start()
    {
        originalRotation = transform.localRotation;
    }

    private void Update()
    {
        SetInputs();
        RotateCamera();
        RotatePlayer();
    }

    private void SetInputs()
    {
        rotation.x = Input.GetAxisRaw("Mouse X") * HORIZONTAL_ROTATION_SPEED;

        rotation.y += Input.GetAxisRaw("Mouse Y") * VERTICAL_ROTATION_SPEED;
        rotation.y = Mathf.Clamp(rotation.y, VERTICAL_ROTATION_MIN, VERTICAL_ROTATION_MAX);
    }

    private void RotateCamera()
    {
        Quaternion verticalRotation = Quaternion.AngleAxis(rotation.y, Vector3.left);
        transform.localRotation = originalRotation * verticalRotation;
    }

    private void RotatePlayer()
    {
        player.localRotation *= Quaternion.AngleAxis(rotation.x, player.up);
    }
}

我提供了一个小gif,显示旋转时的错误动作 .

https://media.giphy.com/media/2jMy38g1PjckODc6B0/giphy.gif

通过旋转相机旋转播放器时,播放器围绕其y轴正确旋转 . 不知怎的,他没有前进到他面对的方向,他只是向一个方向移动 .

需要修复什么?

2 回答

  • 0

    我看到你的移动逻辑不处理相机面向方向,它只是使对象随输入轴值移动,这就是你的对象像这样移动的原因 .

    如果你想让'向前'轴意味着'向前走到我面向的方向',你应该将运动与相机旋转结合起来 .

    你可以尝试类似的东西

    rigid.velocity = Camera.main.transform.rotation * movement;
    

    在你的Move()中 .

  • 0

    这是重新发明轮子 . 统一标准资产包随附fps预制件,可自定义并且运行良好 . 该脚本非常强大,控件很优雅,只需稍加调整即可轻松实现,省时,从Unity商店下载 Unity Standard Asset 软件包,并使用firstperson char预制件 . 我想你会很高兴的 .

相关问题