【问题标题】:Rotating character and camera in FPS在 FPS 中旋转角色和相机
【发布时间】:2019-06-30 17:19:21
【问题描述】:

我试图在 Unity 中移动相机,但我遇到了一个问题,播放器总是从 0,0,0 旋转开始,即使我在播放前将它在 Y 轴上旋转。

我在代码中将播放器在 Y 轴上旋转,相机在 X 轴上旋转,所以玩家在上下看时不会旋转。

代码如下:

public float cameraSpeed;
//public float smooth = 2;
[Range(0f, 1f)] public float smooth = 0.5f;
Vector2 mouseLook;
Vector2 smoothV;

private Transform cameraTransform;


void Start()
{
    //Inicializamos componentes
    rb = GetComponent<Rigidbody>();
    cameraTransform = Camera.main.transform;

    mouseLook.y = Mathf.Clamp(-cameraTransform.localRotation.x, -75, 50);
    mouseLook.x = transform.localRotation.y;
}

void CameraMovement()
{
    //Declaramos un vector con la direccion del raton
    Vector2 md = new Vector2(InputManager.main.HorizontalMouse(), InputManager.main.VerticalMouse());
    md *= cameraSpeed / smooth;
    smoothV = Vector2.Lerp(smoothV, md, smooth);
    mouseLook += smoothV;

    //Limitamos el angulo de la camara para que no de vueltas
    mouseLook = new Vector2(mouseLook.x, Mathf.Clamp(mouseLook.y, -75, 50));

    //Hacemos que rote la camara en el eje x y el jugador en el eje y
    Camera.main.transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
    transform.localRotation = Quaternion.AngleAxis(mouseLook.x  , transform.up);
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    因为您没有连续保持旋转值。你开始总是使用鼠标旋转,这就是为什么保持旋转值就像

    Camera.main.transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right) * Camera.main.transform.localRotation;
    transform.localRotation = Quaternion.AngleAxis(mouseLook.x  , transform.up) * transform.localRotation;
    

    【讨论】:

      【解决方案2】:

      mouseLook 在第一帧中始终是0, 0。所以当你这样做时

      mouseLook += smoothV;
      

      第一次总是有一个从 zero 向量开始的值。


      您应该存储初始旋转(顺便说一下 mainCamera 以避免总是通过Camera.main 获取它),例如

      private Transform cameraTransform;
      
      private void Start()
      {
          cameraTransform = Camera.main.transform;
      
          mouseLook.y = MathfClamp(-cameraTransform.localRotation.x, -75, 50);
          mouseLook.x = transform.localRotation.y;
      }
      

      然后在您的 smooth 计算中,因为 xy 两个分量都相等

      md = Vector2.Scale(md, new Vector2(cameraSpeed * smooth, cameraSpeed * smooth));
      

      您也可以使用简单的float 乘法,例如

      md *= cameraSpeed * smooth;
      

      然后,您可以单独使用 xy 组件而不是 Lerp

      smoothV = Vector2.Lerp(smoothV, md, 1f / smooth);
      

      我实际上建议更好地理解而不是使用

      [Range(0f, 1f)] public float smoothFactor = 0.5f;
      

      然后相应地

      md *= cameraSpeed / smoothFactor;
      smoothV = Vector2.Lerp(smoothV, md, smoothFactor);
      

      【讨论】:

      • 嗨,谢谢你的回答。我已经编辑了所有内容,但它会再次开始寻找 0,0,0,我已经用新代码更新了我的问题
      猜你喜欢
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-30
      相关资源
      最近更新 更多