旋转相机时,单位速度会加快

时间:2019-02-16 17:59:28

标签: c# unity3d

我正在创建一个3D平台游戏,我有两种运动模式:地面和空中。当玩家在地面上时,他会朝着自己的方向移动,并且在空中,由两个变量“ velX”和“ velZ”控制。

我的问题是,当我在空中旋转相机,而播放器在空中向左走时,速度将朝着相机所面对的方向向左走。我已经尝试修复了将近一个星期,但找不到如何解决问题的任何答案。我知道为什么会发生这种情况,因为这行代码是如何工作的。

moveDirection = (camera.forward * Mathf.Round(velZ)) + (camera.right * Mathf.Round(velX));

我尝试从moveDirection中删除camera.forward / right,但随后播放器不会根据相机方向移动。然后,我尝试在添加/减去velX / velZ的地方添加了camera.forward / right,但是由于camera.forward / right是浮点数,因此遇到了麻烦。

这是我的代码:

velZ += acceleration * Input.GetAxis("Vertical") * 1.5f * Time.deltaTime;
velX += acceleration  * Input.GetAxis("Horizontal") * 1.5f * Time.deltaTime;
if (!myCharacterController.isGrounded) {
    moveDirection = (camera.forward * Mathf.Round(velZ)) + (camera.right * Mathf.Round(velX));
}
myCharacterController.move(moveDirection * Time.deltaTime);

1 个答案:

答案 0 :(得分:1)

我设法很轻松地解决了我的问题。我只是用称为“ airVel”的Vector3替换了velX和velZ(它们是浮点数)。

代码:

airVel += acceleration * Input.GetAxis("Vertical") * 1.5f * Time.deltaTime;
airVel += acceleration  * Input.GetAxis("Horizontal") * 1.5f * Time.deltaTime;
if (!myCharacterController.isGrounded) {
    moveDirection = airVel;
}
myCharacterController.move(moveDirection * Time.deltaTime);